answer stringlengths 17 10.2M |
|---|
package com.buuz135.industrial.utils;
import com.buuz135.industrial.proxy.block.BlockConveyor;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
public class MovementUtils {
public static void handleConveyorMovement(Entity entity, EnumFacing direction, BlockPos pos, BlockConveyor.EnumType type) {
if (entity instanceof EntityPlayer && entity.isSneaking()) return;
if (entity.posY - pos.getY() > 0.3 && !type.isVertical()) return;
AxisAlignedBB collision = entity.world.getBlockState(pos).getBlock().getCollisionBoundingBox(entity.world.getBlockState(pos), entity.world, pos).offset(pos);
// if (direction == EnumFacing.NORTH || direction == EnumFacing.SOUTH){
// collision = collision.contract(-0.1,0,0);
// collision = collision.contract(0.1,0,0);
// if (direction == EnumFacing.EAST || direction == EnumFacing.WEST) {
// collision = collision.contract(0,0,-0.1);
// collision = collision.contract(0,0,0.1);
if (!type.isVertical() && !collision.grow(0.01).intersects(entity.getEntityBoundingBox())) return;
//DIRECTION MOVEMENT
double speed = 0.2;
if (type.isFast()) speed *= 2;
Vec3d vec3d = new Vec3d(speed * direction.getDirectionVec().getX(), speed * direction.getDirectionVec().getY(), speed * direction.getDirectionVec().getZ());
if (type.isVertical()) {
vec3d = vec3d.addVector(0, type.isUp() ? 0.258 : -0.05, 0);
entity.onGround = false;
}
//CENTER
if (direction == EnumFacing.NORTH || direction == EnumFacing.SOUTH) {
if (entity.posX - pos.getX() < 0.45) {
vec3d = vec3d.addVector(0.08, 0, 0);
} else if (entity.posX - pos.getX() > 0.55) {
vec3d = vec3d.addVector(-0.08, 0, 0);
}
}
if (direction == EnumFacing.EAST || direction == EnumFacing.WEST) {
if (entity.posZ - pos.getZ() < 0.45) {
vec3d = vec3d.addVector(0, 0, 0.08);
} else if (entity.posZ - pos.getZ() > 0.55) {
vec3d = vec3d.addVector(0, 0, -0.08);
}
}
entity.motionX = vec3d.x;
if (vec3d.y != 0) entity.motionY = vec3d.y;
entity.motionZ = vec3d.z;
}
} |
package com.ecwid.consul.v1.agent.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* @author Vasily Vasilkov (vgv@ecwid.com)
* @author Spencer Gibb (spencer@gibb.us)
*/
public class NewService {
public static class Check {
@SerializedName("Script")
private String script;
@SerializedName("Interval")
private String interval;
@SerializedName("TTL")
private String ttl;
@SerializedName("HTTP")
private String http;
@SerializedName("TCP")
private String tcp;
@SerializedName("Timeout")
private String timeout;
@SerializedName("DeregisterCriticalServiceAfter")
private String deregisterCriticalServiceAfter;
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getInterval() {
return interval;
}
public void setInterval(String interval) {
this.interval = interval;
}
public String getTtl() {
return ttl;
}
public void setTtl(String ttl) {
this.ttl = ttl;
}
public String getHttp() {
return http;
}
public void setHttp(String http) {
this.http = http;
}
public String getTcp() {
return tcp;
}
public void setTcp(String tcp) {
this.tcp = tcp;
}
public String getTimeout() {
return timeout;
}
public void setTimeout(String timeout) {
this.timeout = timeout;
}
public String getDeregisterCriticalServiceAfter() {
return deregisterCriticalServiceAfter;
}
public void setDeregisterCriticalServiceAfter(String deregisterCriticalServiceAfter) {
this.deregisterCriticalServiceAfter = deregisterCriticalServiceAfter;
}
@Override
public String toString() {
return "Check{" +
"script='" + script + '\'' +
", interval=" + interval +
", ttl=" + ttl +
", http=" + http +
", tcp=" + tcp +
", timeout=" + timeout +
", deregisterCriticalServiceAfter=" + deregisterCriticalServiceAfter +
'}';
}
}
@SerializedName("ID")
private String id;
@SerializedName("Name")
private String name;
@SerializedName("Tags")
private List<String> tags;
@SerializedName("Address")
private String address;
@SerializedName("Port")
private Integer port;
@SerializedName("EnableTagOverride")
private Boolean enableTagOverride;
@SerializedName("Check")
private Check check;
@SerializedName("Checks")
private List<Check> checks;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Boolean getEnableTagOverride() {
return enableTagOverride;
}
public void setEnableTagOverride(Boolean enableTagOverride) {
this.enableTagOverride = enableTagOverride;
}
public Check getCheck() {
return check;
}
public void setCheck(Check check) {
this.check = check;
}
public List<Check> getChecks() {
return checks;
}
public void setChecks(List<Check> checks) {
this.checks = checks;
}
@Override
public String toString() {
return "NewService{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", tags=" + tags +
", address='" + address + '\'' +
", port=" + port +
", enableTagOverride=" + enableTagOverride +
", check=" + check +
", checks=" + checks +
'}';
}
} |
package com.gaocy.sample.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping("stat")
public class StatController {
@RequestMapping("home")
public String loadPage(HttpServletRequest req, HttpServletResponse resp) {
String remoteAddr = req.getRemoteAddr();
String remoteHost = req.getRemoteHost();
int remotePort = req.getRemotePort();
System.out.println("remoteAddr: " + remoteAddr);
System.out.println("remoteHost: " + remoteHost);
System.out.println("remotePort: " + remotePort);
return "index";
}
} |
package com.github.msemys.esjc;
import com.github.msemys.esjc.event.ClientConnected;
import com.github.msemys.esjc.util.Strings;
import com.github.msemys.esjc.util.Subscriptions.DropData;
import com.github.msemys.esjc.util.concurrent.ResettableLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static com.github.msemys.esjc.util.Numbers.isPositive;
import static com.github.msemys.esjc.util.Preconditions.checkArgument;
import static com.github.msemys.esjc.util.Preconditions.checkNotNull;
import static com.github.msemys.esjc.util.Ranges.BATCH_SIZE_RANGE;
import static com.github.msemys.esjc.util.Strings.defaultIfEmpty;
import static com.github.msemys.esjc.util.Strings.isNullOrEmpty;
import static com.github.msemys.esjc.util.Subscriptions.DROP_SUBSCRIPTION_EVENT;
import static com.github.msemys.esjc.util.Subscriptions.UNKNOWN_DROP_DATA;
/**
* Catch-up subscription.
*/
public abstract class CatchUpSubscription implements AutoCloseable {
protected final Logger logger = LoggerFactory.getLogger(getClass());
/**
* The name of the stream to which the subscription is subscribed (empty if subscribed to $all stream).
*/
public final String streamId;
private final EventStore eventstore;
private final boolean resolveLinkTos;
private final UserCredentials userCredentials;
protected final CatchUpSubscriptionListener listener;
protected final int readBatchSize;
protected final int maxPushQueueSize;
private final Executor executor;
private final Queue<ResolvedEvent> liveQueue = new ConcurrentLinkedQueue<>();
private Subscription subscription;
private final AtomicReference<DropData> dropData = new AtomicReference<>();
private volatile boolean allowProcessing;
private final AtomicBoolean isProcessing = new AtomicBoolean();
protected volatile boolean shouldStop;
private final AtomicBoolean isDropped = new AtomicBoolean();
private final ResettableLatch stopped = new ResettableLatch(true);
private final EventStoreListener reconnectionHook;
protected CatchUpSubscription(EventStore eventstore,
String streamId,
boolean resolveLinkTos,
CatchUpSubscriptionListener listener,
UserCredentials userCredentials,
int readBatchSize,
int maxPushQueueSize,
Executor executor) {
checkNotNull(eventstore, "eventstore is null");
checkNotNull(listener, "listener is null");
checkNotNull(listener, "executor is null");
checkArgument(BATCH_SIZE_RANGE.contains(readBatchSize), "readBatchSize is out of range. Allowed range: %s.", BATCH_SIZE_RANGE.toString());
checkArgument(isPositive(maxPushQueueSize), "maxPushQueueSize should be positive");
this.eventstore = eventstore;
this.streamId = defaultIfEmpty(streamId, Strings.EMPTY);
this.resolveLinkTos = resolveLinkTos;
this.listener = listener;
this.userCredentials = userCredentials;
this.readBatchSize = readBatchSize;
this.maxPushQueueSize = maxPushQueueSize;
this.executor = executor;
reconnectionHook = event -> {
if (event instanceof ClientConnected) {
onReconnect();
}
};
}
protected abstract void readEventsTill(EventStore eventstore,
boolean resolveLinkTos,
UserCredentials userCredentials,
Long lastCommitPosition,
Integer lastEventNumber) throws Exception;
protected abstract void tryProcess(ResolvedEvent event);
void start() {
logger.trace("Catch-up subscription to {}: starting...", streamId());
runSubscription();
}
/**
* Unsubscribes from the catch-up subscription.
*
* @param timeout the maximum wait time before it should timeout.
* @throws TimeoutException when timeouts
*/
public void stop(Duration timeout) throws TimeoutException {
stop();
logger.trace("Waiting on subscription to stop");
if (!stopped.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
throw new TimeoutException(String.format("Could not stop %s in time.", getClass().getSimpleName()));
}
}
/**
* Unsubscribes from the catch-up subscription asynchronously.
*/
public void stop() {
logger.trace("Catch-up subscription to {}: requesting stop...", streamId());
logger.trace("Catch-up subscription to {}: unhooking from connection. Connected.", streamId());
eventstore.removeListener(reconnectionHook);
shouldStop = true;
enqueueSubscriptionDropNotification(SubscriptionDropReason.UserInitiated, null);
}
/**
* Unsubscribes from the catch-up subscription (using 2 seconds wait time before it should timeout).
*
* @throws TimeoutException when timeouts
* @see #stop(Duration)
*/
@Override
public void close() throws TimeoutException {
stop(Duration.ofSeconds(2));
}
private void onReconnect() {
logger.trace("Catch-up subscription to {}: recovering after reconnection.", streamId());
logger.trace("Catch-up subscription to {}: unhooking from connection. Connected.", streamId());
eventstore.removeListener(reconnectionHook);
runSubscription();
}
private void runSubscription() {
executor.execute(() -> {
logger.trace("Catch-up subscription to {}: running...", streamId());
stopped.reset();
allowProcessing = false;
isDropped.set(false);
dropData.set(null);
try {
if (!shouldStop) {
logger.trace("Catch-up subscription to {}: pulling events...", streamId());
readEventsTill(eventstore, resolveLinkTos, userCredentials, null, null);
}
if (!shouldStop) {
logger.trace("Catch-up subscription to {}: subscribing...", streamId());
VolatileSubscriptionListener subscriptionListener = new VolatileSubscriptionListener() {
@Override
public void onEvent(Subscription s, ResolvedEvent event) {
if (dropData.get() == null) {
logger.trace("Catch-up subscription to {}: event appeared ({}, {}, {} @ {}).",
streamId(), event.originalStreamId(), event.originalEventNumber(),
event.originalEvent().eventType, event.originalPosition);
if (liveQueue.size() >= maxPushQueueSize) {
enqueueSubscriptionDropNotification(SubscriptionDropReason.ProcessingQueueOverflow, null);
subscription.unsubscribe();
} else {
liveQueue.offer(event);
if (allowProcessing) {
ensureProcessingPushQueue();
}
}
}
}
@Override
public void onClose(Subscription s, SubscriptionDropReason reason, Exception exception) {
enqueueSubscriptionDropNotification(reason, exception);
}
};
subscription = isSubscribedToAll() ?
eventstore.subscribeToAll(resolveLinkTos, subscriptionListener, userCredentials).get() :
eventstore.subscribeToStream(streamId, resolveLinkTos, subscriptionListener, userCredentials).get();
logger.trace("Catch-up subscription to {}: pulling events (if left)...", streamId());
readEventsTill(eventstore, resolveLinkTos, userCredentials, subscription.lastCommitPosition, subscription.lastEventNumber);
}
} catch (Exception e) {
dropSubscription(SubscriptionDropReason.CatchUpError, e);
return;
}
if (shouldStop) {
dropSubscription(SubscriptionDropReason.UserInitiated, null);
return;
}
logger.trace("Catch-up subscription to {}: processing live events...", streamId());
listener.onLiveProcessingStarted(this);
logger.trace("Catch-up subscription to {}: hooking to connection. Connected", streamId());
eventstore.addListener(reconnectionHook);
allowProcessing = true;
ensureProcessingPushQueue();
});
}
private void enqueueSubscriptionDropNotification(SubscriptionDropReason reason, Exception exception) {
// if drop data was already set -- no need to enqueue drop again, somebody did that already
if (dropData.compareAndSet(null, new DropData(reason, exception))) {
liveQueue.offer(DROP_SUBSCRIPTION_EVENT);
if (allowProcessing) {
ensureProcessingPushQueue();
}
}
}
private void ensureProcessingPushQueue() {
if (isProcessing.compareAndSet(false, true)) {
executor.execute(this::processLiveQueue);
}
}
private void processLiveQueue() {
do {
ResolvedEvent event;
while ((event = liveQueue.poll()) != null) {
// drop subscription artificial ResolvedEvent
if (event.equals(DROP_SUBSCRIPTION_EVENT)) {
DropData previousDropData = dropData.getAndAccumulate(UNKNOWN_DROP_DATA,
(current, update) -> (current == null) ? update : current);
if (previousDropData == null) {
previousDropData = UNKNOWN_DROP_DATA;
}
dropSubscription(previousDropData.reason, previousDropData.exception);
isProcessing.compareAndSet(true, false);
return;
}
try {
tryProcess(event);
} catch (Exception e) {
dropSubscription(SubscriptionDropReason.EventHandlerException, e);
return;
}
}
isProcessing.compareAndSet(true, false);
} while (!liveQueue.isEmpty() && isProcessing.compareAndSet(false, true));
}
private void dropSubscription(SubscriptionDropReason reason, Exception exception) {
if (isDropped.compareAndSet(false, true)) {
logger.trace("Catch-up subscription to {}: dropping subscription, reason: {}.", streamId(), reason, exception);
if (subscription != null) {
subscription.unsubscribe();
}
listener.onClose(this, reason, exception);
stopped.release();
}
}
/**
* Determines whether or not this subscription is to $all stream or to a specific stream.
*
* @return {@code true} if this subscription is to $all stream, otherwise {@code false}
*/
public boolean isSubscribedToAll() {
return isNullOrEmpty(streamId);
}
/**
* The last event number processed on the subscription.
*
* @return event number
*/
public abstract int lastProcessedEventNumber();
/**
* The last position processed on the subscription.
*
* @return position
*/
public abstract Position lastProcessedPosition();
protected String streamId() {
return defaultIfEmpty(streamId, "<all>");
}
} |
package allbegray.slack;
import allbegray.slack.type.*;
import allbegray.slack.webapi.SlackWebApiClient;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Map;
public class DndMethodTest {
private String token = "xoxp-18899142932-18905601458-41812031460-b54fb48eec";
private SlackWebApiClient webApiClient;
@Before
public void setup() {
webApiClient = SlackClientFactory.createWebApiClient(token);
}
@After
public void shutdown() {
webApiClient.shutdown();
}
@Test
public void basicTest() {
Authentication authentication = webApiClient.auth();
Map<String, DndSimpleInfo> dndTeamInfo = webApiClient.getDndTeamInfo();
Assert.assertTrue(dndTeamInfo.size() > 0);
DndInfo dndInfo = webApiClient.getDndInfo(authentication.getUser_id());
Assert.assertTrue(dndInfo.getSnooze_enabled() != null);
boolean isEndDnd = webApiClient.endDnd();
Assert.assertTrue(isEndDnd == true);
SetSnooze setSnooze = webApiClient.setSnooze(1);
Assert.assertTrue(setSnooze.getSnooze_enabled() == true);
EndSnooze endSnooze = webApiClient.endSnooze();
Assert.assertTrue(endSnooze.getSnooze_enabled() == false);
isEndDnd = webApiClient.endDnd();
Assert.assertTrue(isEndDnd == true);
}
} |
package it.innove.play.pdf;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import nu.validator.htmlparser.dom.HtmlDocumentBuilder;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
import play.Logger;
import play.Play;
import play.twirl.api.Html;
import play.mvc.Result;
import play.mvc.Results;
public class PdfGenerator {
private static List<String> defaultFonts = null;
public static void loadTemporaryFonts(List<String> fontsToLoad) {
defaultFonts = new ArrayList<String>();
addTemporaryFonts(fontsToLoad);
}
public static void addTemporaryFonts(List<String> fontsToLoad) {
if (defaultFonts == null)
defaultFonts = new ArrayList<String>();
for (String font : fontsToLoad) {
try {
InputStream fin = Play.application().resourceAsStream(font);
final File tempFile = File.createTempFile("tmp_" + FilenameUtils.getBaseName(font), "." + FilenameUtils.getExtension(font));
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(fin, out);
defaultFonts.add(tempFile.getAbsolutePath());
} catch (Exception e) {
Logger.error("Loading fonts", e);
}
}
}
public static void loadLocalFonts(List<String> fontsToLoad) {
defaultFonts = new ArrayList<String>();
addLocalFonts(fontsToLoad);
}
public static void addLocalFonts(List<String> fontsToLoad) {
if (defaultFonts == null)
defaultFonts = new ArrayList<String>();
for (String font : fontsToLoad)
defaultFonts.add(font);
}
public static Result ok(Html html, String documentBaseURL) {
byte[] pdf = toBytes(html.body(), documentBaseURL);
return Results.ok(pdf).as("application/pdf");
}
public static Result ok(Html html, String documentBaseURL, List<String> fonts) {
byte[] pdf = toBytes(html.body(), documentBaseURL, fonts);
return Results.ok(pdf).as("application/pdf");
}
public static byte[] toBytes(Html html, String documentBaseURL) {
byte[] pdf = toBytes(html.body(), documentBaseURL);
return pdf;
}
public static byte[] toBytes(Html html, String documentBaseURL, List<String> fonts) {
byte[] pdf = toBytes(html.body(), documentBaseURL, fonts);
return pdf;
}
public static byte[] toBytes(String string, String documentBaseURL) {
return toBytes(string, documentBaseURL, defaultFonts);
}
public static byte[] toBytes(String string, String documentBaseURL, List<String> fonts) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
toStream(string, os, documentBaseURL);
return os.toByteArray();
}
public static void toStream(String string, OutputStream os, String documentBaseURL) {
toStream(string, os, documentBaseURL, defaultFonts);
}
public static void toStream(String string, OutputStream os, String documentBaseURL, List<String> fonts) {
try {
InputStream input = new ByteArrayInputStream(string.getBytes("UTF-8"));
ITextRenderer renderer = new ITextRenderer();
for (String font : fonts) {
renderer.getFontResolver().addFont(font, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
PdfUserAgent myUserAgent = new PdfUserAgent(renderer.getOutputDevice());
myUserAgent.setSharedContext(renderer.getSharedContext());
renderer.getSharedContext().setUserAgentCallback(myUserAgent);
Document document = new HtmlDocumentBuilder().parse(input);
renderer.setDocument(document, documentBaseURL);
renderer.layout();
renderer.createPDF(os);
} catch (Exception e) {
Logger.error("Error creating document from template", e);
}
}
} |
package com.github.pagehelper.page;
import com.github.pagehelper.Dialect;
import com.github.pagehelper.PageException;
import com.github.pagehelper.dialect.AbstractHelperDialect;
import com.github.pagehelper.dialect.helper.*;
import com.github.pagehelper.util.StringUtil;
import org.apache.ibatis.mapping.MappedStatement;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
*
*
* @author liuzh
*/
public class PageAutoDialect {
private static Map<String, Class<? extends Dialect>> dialectAliasMap = new HashMap<String, Class<? extends Dialect>>();
public static void registerDialectAlias(String alias, Class<? extends Dialect> dialectClass){
dialectAliasMap.put(alias, dialectClass);
}
static {
registerDialectAlias("hsqldb", HsqldbDialect.class);
registerDialectAlias("h2", HsqldbDialect.class);
registerDialectAlias("postgresql", HsqldbDialect.class);
registerDialectAlias("phoenix", HsqldbDialect.class);
registerDialectAlias("mysql", MySqlDialect.class);
registerDialectAlias("mariadb", MySqlDialect.class);
registerDialectAlias("sqlite", MySqlDialect.class);
registerDialectAlias("oracle", OracleDialect.class);
registerDialectAlias("db2", Db2Dialect.class);
registerDialectAlias("informix", InformixDialect.class);
// informix-sqli #129
registerDialectAlias("informix-sqli", InformixDialect.class);
registerDialectAlias("sqlserver", SqlServerDialect.class);
registerDialectAlias("sqlserver2012", SqlServer2012Dialect.class);
registerDialectAlias("derby", SqlServer2012Dialect.class);
registerDialectAlias("dm", OracleDialect.class);
registerDialectAlias("edb", OracleDialect.class);
registerDialectAlias("oscar", MySqlDialect.class);
}
//dialect,setPropertiessetSqlUtilConfig
private boolean autoDialect = true;
//jdbcurl
private boolean closeConn = true;
private Properties properties;
private Map<String, AbstractHelperDialect> urlDialectMap = new ConcurrentHashMap<String, AbstractHelperDialect>();
private ReentrantLock lock = new ReentrantLock();
private AbstractHelperDialect delegate;
private ThreadLocal<AbstractHelperDialect> dialectThreadLocal = new ThreadLocal<AbstractHelperDialect>();
public void initDelegateDialect(MappedStatement ms) {
if (delegate == null) {
if (autoDialect) {
this.delegate = getDialect(ms);
} else {
dialectThreadLocal.set(getDialect(ms));
}
}
}
public AbstractHelperDialect getDelegate() {
if (delegate != null) {
return delegate;
}
return dialectThreadLocal.get();
}
public void clearDelegate() {
dialectThreadLocal.remove();
}
private String fromJdbcUrl(String jdbcUrl) {
for (String dialect : dialectAliasMap.keySet()) {
if (jdbcUrl.indexOf(":" + dialect + ":") != -1) {
return dialect;
}
}
return null;
}
/**
*
*
* @param className
* @return
* @throws Exception
*/
private Class resloveDialectClass(String className) throws Exception {
if (dialectAliasMap.containsKey(className.toLowerCase())) {
return dialectAliasMap.get(className.toLowerCase());
} else {
return Class.forName(className);
}
}
/**
* helper
*
* @param dialectClass
* @param properties
*/
private AbstractHelperDialect initDialect(String dialectClass, Properties properties) {
AbstractHelperDialect dialect;
if (StringUtil.isEmpty(dialectClass)) {
throw new PageException(" PageHelper helper ");
}
try {
Class sqlDialectClass = resloveDialectClass(dialectClass);
if (AbstractHelperDialect.class.isAssignableFrom(sqlDialectClass)) {
dialect = (AbstractHelperDialect) sqlDialectClass.newInstance();
} else {
throw new PageException(" PageHelper " + AbstractHelperDialect.class.getCanonicalName() + " !");
}
} catch (Exception e) {
throw new PageException(" helper [" + dialectClass + "]:" + e.getMessage(), e);
}
dialect.setProperties(properties);
return dialect;
}
/**
* url
*
* @param dataSource
* @return
*/
private String getUrl(DataSource dataSource) {
Connection conn = null;
try {
conn = dataSource.getConnection();
return conn.getMetaData().getURL();
} catch (SQLException e) {
throw new PageException(e);
} finally {
if (conn != null) {
try {
if (closeConn) {
conn.close();
}
} catch (SQLException e) {
//ignore
}
}
}
}
/**
* jdbcUrl
*
* @param ms
* @return
*/
private AbstractHelperDialect getDialect(MappedStatement ms) {
//dataSource
DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource();
String url = getUrl(dataSource);
if (urlDialectMap.containsKey(url)) {
return urlDialectMap.get(url);
}
try {
lock.lock();
if (urlDialectMap.containsKey(url)) {
return urlDialectMap.get(url);
}
if (StringUtil.isEmpty(url)) {
throw new PageException("jdbcUrldialect!");
}
String dialectStr = fromJdbcUrl(url);
if (dialectStr == null) {
throw new PageException(" helperDialect !");
}
AbstractHelperDialect dialect = initDialect(dialectStr, properties);
urlDialectMap.put(url, dialect);
return dialect;
} finally {
lock.unlock();
}
}
public void setProperties(Properties properties) {
// jdbcurl
String closeConn = properties.getProperty("closeConn");
if (StringUtil.isNotEmpty(closeConn)) {
this.closeConn = Boolean.parseBoolean(closeConn);
}
// sqlserver2012
String useSqlserver2012 = properties.getProperty("useSqlserver2012");
if (StringUtil.isNotEmpty(useSqlserver2012) && Boolean.parseBoolean(useSqlserver2012)) {
registerDialectAlias("sqlserver", SqlServer2012Dialect.class);
registerDialectAlias("sqlserver2008", SqlServerDialect.class);
}
String dialectAlias = properties.getProperty("dialectAlias");
if (StringUtil.isNotEmpty(dialectAlias)) {
String[] alias = dialectAlias.split(";");
for (int i = 0; i < alias.length; i++) {
String[] kv = alias[i].split("=");
if(kv.length != 2){
throw new IllegalArgumentException("dialectAlias " +
" alias1=xx.dialectClass;alias2=dialectClass2 !");
}
for (int j = 0; j < kv.length; j++) {
try {
Class<? extends Dialect> diallectClass = (Class<? extends Dialect>) Class.forName(kv[1]);
registerDialectAlias(kv[0], diallectClass);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(" dialectAlias Dialect !", e);
}
}
}
}
// Helper
String dialect = properties.getProperty("helperDialect");
String runtimeDialect = properties.getProperty("autoRuntimeDialect");
if (StringUtil.isNotEmpty(runtimeDialect) && "TRUE".equalsIgnoreCase(runtimeDialect)) {
this.autoDialect = false;
this.properties = properties;
}
else if (StringUtil.isEmpty(dialect)) {
autoDialect = true;
this.properties = properties;
}
else {
autoDialect = false;
this.delegate = initDialect(dialect, properties);
}
}
} |
package com.bigcommerce.api;
import java.util.Collection;
import com.bigcommerce.api.resources.Orders;
public class OrderTest {
public static void main(String[] args) {
String storeUrl = "https://examplestore.com";
String use = "admin";
String apiKey = "akjfalksjflksjflaskdjflasdk";
Store storeApi = new Store(storeUrl, user, apiKey);
Orders orders = storeApi.getOrders();
Collection<Order> allOrders = orders.listAll();
for (Order order : allOrders) {
System.out.println("Customer ID:" + order.getCustomerId());
System.out.println("Order ID:" + order.getId());
System.out.println("Order Status:" + order.getStatus());
}
}
} |
package com.versionone.hudson;
import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.model.Descriptor;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.tasks.BatchFile;
import hudson.tasks.Publisher;
import hudson.util.DescribableList;
import org.apache.commons.io.FileUtils;
import org.jvnet.hudson.test.HudsonTestCase;
import org.xml.sax.SAXException;
import org.junit.Ignore;
import java.io.IOException;
public class AppTest extends HudsonTestCase {
/*
public void test1() throws Exception {
FreeStyleProject project = createFreeStyleProject();
project.getBuildersList().add(new BatchFile("echo hello"));
// List<Action> actions = project.getActions();
DescribableList<Publisher, Descriptor<Publisher>> publishers = project.getPublishersList();
VersionOneNotifier versionOneNotifier = new VersionOneNotifier();
// VersionOneNotifier.DESCRIPTOR.configure()
publishers.add(versionOneNotifier);
FreeStyleBuild build = project.scheduleBuild2(0).get();
System.out.println(build.getDisplayName() + " completed");
// TODO: change this to use HtmlUnit
String s = FileUtils.readFileToString(build.getLogFile());
assertTrue(s.contains("echo hello"));
}
*/
/*
@Ignore
public void test2() throws IOException, SAXException {
final HtmlPage page = new WebClient().goTo("configure");
assertElementPresentByName(page, "com-versionone-hudson-VersionOneNotifier");
int j = 3;
int i = ((2009 - 2004) + j) > 1 ? 0 : 1;
}
*/
/**
* Verifies that the specified page contains an element with the specified ID.
*
* @param page the page to check
* @param name the expected Name of an element in the page
*/
/*
public static void assertElementPresentByName(final HtmlPage page, final String name) {
try {
page.getHtmlElementsByName(name);
} catch (final ElementNotFoundException e) {
throw new AssertionError("The page does not contain an element with name '" + name + "'.");
}
}
*/
} |
package hudson.plugins.git;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.matrix.Axis;
import hudson.matrix.AxisList;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
import hudson.model.*;
import hudson.plugins.git.GitSCM.BuildChooserContextImpl;
import hudson.plugins.git.GitSCM.DescriptorImpl;
import hudson.plugins.git.browser.GitRepositoryBrowser;
import hudson.plugins.git.browser.GithubWeb;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.impl.*;
import hudson.plugins.git.util.BuildChooser;
import hudson.plugins.git.util.BuildChooserContext;
import hudson.plugins.git.util.BuildChooserContext.ContextCallable;
import hudson.plugins.git.util.BuildData;
import hudson.plugins.git.util.GitUtils;
import hudson.plugins.parameterizedtrigger.BuildTrigger;
import hudson.plugins.parameterizedtrigger.ResultCondition;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogSet;
import hudson.scm.PollingResult;
import hudson.scm.PollingResult.Change;
import hudson.scm.SCMRevisionState;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.security.Permission;
import hudson.slaves.DumbSlave;
import hudson.slaves.EnvironmentVariablesNodeProperty.Entry;
import hudson.tools.ToolLocationNodeProperty;
import hudson.tools.ToolProperty;
import hudson.triggers.SCMTrigger;
import hudson.util.LogTaskListener;
import hudson.util.ReflectionUtils;
import hudson.util.RingBufferLogHandler;
import hudson.util.StreamTaskListener;
import jenkins.security.MasterToSlaveCallable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.jenkinsci.plugins.tokenmacro.TokenMacro;
import org.jenkinsci.plugins.gitclient.*;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
import org.jvnet.hudson.test.TestExtension;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.jgit.transport.RemoteConfig;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import jenkins.model.Jenkins;
import jenkins.plugins.git.CliGitCommand;
import jenkins.plugins.git.GitSampleRepoRule;
/**
* Tests for {@link GitSCM}.
* @author ishaaq
*/
public class GitSCMTest extends AbstractGitTestCase {
@Rule
public GitSampleRepoRule secondRepo = new GitSampleRepoRule();
private CredentialsStore store = null;
@BeforeClass
public static void setGitDefaults() throws Exception {
CliGitCommand gitCmd = new CliGitCommand(null);
gitCmd.setDefaults();
}
@Before
public void enableSystemCredentialsProvider() throws Exception {
SystemCredentialsProvider.getInstance().setDomainCredentialsMap(
Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList()));
for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) {
if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) {
store = s;
break;
}
}
assertThat("The system credentials provider is enabled", store, notNullValue());
}
@After
public void waitForJenkinsIdle() throws Exception {
if (cleanupIsUnreliable()) {
rule.waitUntilNoActivityUpTo(5001);
}
}
private StandardCredentials getInvalidCredential() {
String username = "bad-user";
String password = "bad-password";
CredentialsScope scope = CredentialsScope.GLOBAL;
String id = "username-" + username + "-password-" + password;
return new UsernamePasswordCredentialsImpl(scope, id, "desc: " + id, username, password);
}
@Test
public void manageShouldAccessGlobalConfig() {
final String USER = "user";
final String MANAGER = "manager";
Permission jenkinsManage;
try {
jenkinsManage = getJenkinsManage();
} catch (Exception e) {
Assume.assumeTrue("Jenkins baseline is too old for this test (requires Jenkins.MANAGE)", false);
return;
}
rule.jenkins.setSecurityRealm(rule.createDummySecurityRealm());
rule.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
// Read access
.grant(Jenkins.READ).everywhere().to(USER)
// Read and Manage
.grant(Jenkins.READ).everywhere().to(MANAGER)
.grant(jenkinsManage).everywhere().to(MANAGER)
);
try (ACLContext c = ACL.as(User.getById(USER, true))) {
Collection<Descriptor> descriptors = Functions.getSortedDescriptorsForGlobalConfigUnclassified();
assertThat("Global configuration should not be accessible to READ users", descriptors, is(empty()));
}
try (ACLContext c = ACL.as(User.getById(MANAGER, true))) {
Collection<Descriptor> descriptors = Functions.getSortedDescriptorsForGlobalConfigUnclassified();
Optional<Descriptor> found =
descriptors.stream().filter(descriptor -> descriptor instanceof GitSCM.DescriptorImpl).findFirst();
assertTrue("Global configuration should be accessible to MANAGE users", found.isPresent());
}
}
// TODO: remove when Jenkins core baseline is 2.222+
private Permission getJenkinsManage() throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
// Jenkins.MANAGE is available starting from Jenkins 2.222 (https://jenkins.io/changelog/#v2.222). See JEP-223 for more info
return (Permission) ReflectionUtils.getPublicProperty(Jenkins.get(), "MANAGE");
}
@Test
public void trackCredentials() throws Exception {
StandardCredentials credential = getInvalidCredential();
store.addCredentials(Domain.global(), credential);
Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credential);
assertThat("Fingerprint should not be set before job definition", fingerprint, nullValue());
JenkinsRule.WebClient wc = rule.createWebClient();
HtmlPage page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId());
assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue());
assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue());
assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue());
FreeStyleProject project = setupProject("master", credential);
fingerprint = CredentialsProvider.getFingerprintOf(credential);
assertThat("Fingerprint should not be set before first build", fingerprint, nullValue());
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
fingerprint = CredentialsProvider.getFingerprintOf(credential);
assertThat("Fingerprint should be set after first build", fingerprint, notNullValue());
assertThat(fingerprint.getJobs(), hasItem(is(project.getFullName())));
Fingerprint.RangeSet rangeSet = fingerprint.getRangeSet(project);
assertThat(rangeSet, notNullValue());
assertThat(rangeSet.includes(project.getLastBuild().getNumber()), is(true));
page = wc.goTo("credentials/store/system/domain/_/credentials/" + credential.getId());
assertThat(page.getElementById("usage-missing"), nullValue());
assertThat(page.getElementById("usage-present"), notNullValue());
assertThat(page.getAnchorByText(project.getFullDisplayName()), notNullValue());
}
/**
* Basic test - create a GitSCM based project, check it out and build for the first time.
* Next test that polling works correctly, make another commit, check that polling finds it,
* then build it and finally test the build culprits as well as the contents of the workspace.
* @throws Exception on error
*/
@Test
public void testBasic() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
@Issue("JENKINS-56176")
public void testBasicRemotePoll() throws Exception {
// FreeStyleProject project = setupProject("master", true, false);
FreeStyleProject project = setupProject("master", false, null, null, null, true, null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
String sha1String = commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
// ... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// JENKINS-56176 token macro expansion broke when BuildData was no longer updated
assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION,length=7}"), is(sha1String.substring(0, 7)));
assertThat(TokenMacro.expandAll(build2, listener, "${GIT_REVISION}"), is(sha1String));
assertThat(TokenMacro.expandAll(build2, listener, "$GIT_REVISION"), is(sha1String));
}
@Test
public void testBranchSpecWithRemotesMaster() throws Exception {
FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null);
// create initial commit and build
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(projectMasterBranch, Result.SUCCESS, commitFile1);
}
/**
* This test and testSpecificRefspecsWithoutCloneOption confirm behaviors of
* refspecs on initial clone. Without the CloneOption to honor refspec, all
* references are cloned, even if they will be later ignored due to the
* refspec. With the CloneOption to ignore refspec, the initial clone also
* honors the refspec and only retrieves references per the refspec.
* @throws Exception on error
*/
@Test
@Issue("JENKINS-31393")
public void testSpecificRefspecs() throws Exception {
List<UserRemoteConfig> repos = new ArrayList<>();
repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null));
/* Set CloneOption to honor refspec on initial clone */
FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null);
CloneOption cloneOptionMaster = new CloneOption(false, null, null);
cloneOptionMaster.setHonorRefspec(true);
((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionMaster);
/* Set CloneOption to honor refspec on initial clone */
FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null);
CloneOption cloneOptionFoo = new CloneOption(false, null, null);
cloneOptionFoo.setHonorRefspec(true);
((GitSCM)projectWithMaster.getScm()).getExtensions().add(cloneOptionFoo);
// create initial commit
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit in master");
// create branch and make initial commit
git.branch("foo");
git.checkout().branch("foo");
commit(commitFile1, johnDoe, "Commit in foo");
build(projectWithMaster, Result.FAILURE);
build(projectWithFoo, Result.SUCCESS, commitFile1);
}
/**
* This test and testSpecificRefspecs confirm behaviors of
* refspecs on initial clone. Without the CloneOption to honor refspec, all
* references are cloned, even if they will be later ignored due to the
* refspec. With the CloneOption to ignore refspec, the initial clone also
* honors the refspec and only retrieves references per the refspec.
* @throws Exception on error
*/
@Test
@Issue("JENKINS-36507")
public void testSpecificRefspecsWithoutCloneOption() throws Exception {
List<UserRemoteConfig> repos = new ArrayList<>();
repos.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "+refs/heads/foo:refs/remotes/foo", null));
FreeStyleProject projectWithMaster = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null);
FreeStyleProject projectWithFoo = setupProject(repos, Collections.singletonList(new BranchSpec("foo")), null, false, null);
// create initial commit
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit in master");
// create branch and make initial commit
git.branch("foo");
git.checkout().branch("foo");
commit(commitFile1, johnDoe, "Commit in foo");
build(projectWithMaster, Result.SUCCESS); /* If clone refspec had been honored, this would fail */
build(projectWithFoo, Result.SUCCESS, commitFile1);
}
/**
* An empty remote repo URL failed the job as expected but provided
* a poor diagnostic message. The fix for JENKINS-38608 improves
* the error message to be clear and helpful. This test checks for
* that error message.
* @throws Exception on error
*/
@Test
@Issue("JENKINS-38608")
public void testAddFirstRepositoryWithNullRepoURL() throws Exception{
List<UserRemoteConfig> repos = new ArrayList<>();
repos.add(new UserRemoteConfig(null, null, null, null));
FreeStyleProject project = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null);
FreeStyleBuild build = build(project, Result.FAILURE);
// Before JENKINS-38608 fix
assertThat("Build log reports 'Null value not allowed'",
build.getLog(175), not(hasItem("Null value not allowed as an environment variable: GIT_URL")));
// After JENKINS-38608 fix
assertThat("Build log did not report empty string in job definition",
build.getLog(175), hasItem("FATAL: Git repository URL 1 is an empty string in job definition. Checkout requires a valid repository URL"));
}
/**
* An empty remote repo URL failed the job as expected but provided
* a poor diagnostic message. The fix for JENKINS-38608 improves
* the error message to be clear and helpful. This test checks for
* that error message when the second URL is empty.
* @throws Exception on error
*/
@Test
@Issue("JENKINS-38608")
public void testAddSecondRepositoryWithNullRepoURL() throws Exception{
String repoURL = "https://example.com/non-empty/repo/url";
List<UserRemoteConfig> repos = new ArrayList<>();
repos.add(new UserRemoteConfig(repoURL, null, null, null));
repos.add(new UserRemoteConfig(null, null, null, null));
FreeStyleProject project = setupProject(repos, Collections.singletonList(new BranchSpec("master")), null, false, null);
FreeStyleBuild build = build(project, Result.FAILURE);
// Before JENKINS-38608 fix
assertThat("Build log reports 'Null value not allowed'",
build.getLog(175), not(hasItem("Null value not allowed as an environment variable: GIT_URL_2")));
// After JENKINS-38608 fix
assertThat("Build log did not report empty string in job definition for URL 2",
build.getLog(175), hasItem("FATAL: Git repository URL 2 is an empty string in job definition. Checkout requires a valid repository URL"));
}
@Test
public void testBranchSpecWithRemotesHierarchical() throws Exception {
FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null);
FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null);
// create initial commit
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
// create hierarchical branch, delete master branch, and build
git.branch("rel-1/xy");
git.checkout("rel-1/xy");
git.deleteBranch("master");
build(projectMasterBranch, Result.FAILURE);
build(projectHierarchicalBranch, Result.SUCCESS, commitFile1);
}
@Test
public void testBranchSpecUsingTagWithSlash() throws Exception {
FreeStyleProject projectMasterBranch = setupProject("path/tag", false, null, null, null, true, null);
// create initial commit and build
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1 will be tagged with path/tag");
testRepo.git.tag("path/tag", "tag with a slash in the tag name");
build(projectMasterBranch, Result.SUCCESS, commitFile1);
}
@Test
public void testBasicIncludedRegion() throws Exception {
FreeStyleProject project = setupProject("master", false, null, null, null, ".*3");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
/**
* testMergeCommitInExcludedRegionIsIgnored() confirms behavior of excluded regions with merge commits.
* This test has excluded and included regions, for files ending with .excluded and .included,
* respectively. The git repository is set up so that a non-fast-forward merge commit comes
* to master. The newly merged commit is a file ending with .excluded, so it should be ignored.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitInExcludedRegionIsIgnored() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, ".*\\.included");
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
final String fileToMerge = "fileToMerge.excluded";
commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// Should return false, because our merge commit falls within the excluded region.
assertFalse("Polling should report no changes, because they are in the excluded region.",
project.poll(listener).hasChanges());
}
/**
* testMergeCommitInExcludedDirectoryIsIgnored() confirms behavior of excluded directories with merge commits.
* This test has excluded and included directories, named /excluded/ and /included/,respectively. The repository
* is set up so that a non-fast-forward merge commit comes to master, and is in the directory /excluded/,
* so it should be ignored.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitInExcludedDirectoryIsIgnored() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, "included/.*");
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
final String fileToMerge = "excluded/should-be-ignored";
commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// Should return false, because our merge commit falls within the excluded directory.
assertFalse("Polling should see no changes, because they are in the excluded directory.",
project.poll(listener).hasChanges());
}
/**
* testMergeCommitInIncludedRegionIsProcessed() confirms behavior of included regions with merge commits.
* This test has excluded and included regions, for files ending with .excluded and .included, respectively.
* The git repository is set up so that a non-fast-forward merge commit comes to master. The newly merged
* commit is a file ending with .included, so it should be processed as a new change.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitInIncludedRegionIsProcessed() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, ".*\\.included");
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
final String fileToMerge = "fileToMerge.included";
commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// Should return true, because our commit falls within the included region.
assertTrue("Polling should report changes, because they fall within the included region.",
project.poll(listener).hasChanges());
}
/**
* testMergeCommitInIncludedRegionIsProcessed() confirms behavior of included directories with merge commits.
* This test has excluded and included directories, named /excluded/ and /included/, respectively. The repository
* is set up so that a non-fast-forward merge commit comes to master, and is in the directory /included/,
* so it should be processed as a new change.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitInIncludedDirectoryIsProcessed() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, "included/.*");
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
final String fileToMerge = "included/should-be-processed";
commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// When this test passes, project.poll(listener).hasChanges()) should return
// true, because our commit falls within the included region.
assertTrue("Polling should report changes, because they are in the included directory.",
project.poll(listener).hasChanges());
}
/**
* testMergeCommitOutsideIncludedRegionIsIgnored() confirms behavior of included regions with merge commits.
* This test has an included region defined, for files ending with .included. There is no excluded region
* defined. The repository is set up and a non-fast-forward merge commit comes to master. The newly merged commit
* is a file ending with .should-be-ignored, thus falling outside of the included region, so it should ignored.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitOutsideIncludedRegionIsIgnored() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, null, null, ".*\\.included");
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
final String fileToMerge = "fileToMerge.should-be-ignored";
commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// Should return false, because our commit falls outside the included region.
assertFalse("Polling should ignore the change, because it falls outside the included region.",
project.poll(listener).hasChanges());
}
/**
* testMergeCommitOutsideIncludedDirectoryIsIgnored() confirms behavior of included directories with merge commits.
* This test has only an included directory `/included` defined. The git repository is set up so that
* a non-fast-forward, but mergeable, commit comes to master. The newly merged commit is outside of the
* /included/ directory, so polling should report no changes.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitOutsideIncludedDirectoryIsIgnored() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, null, null, "included/.*");
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
final String fileToMerge = "directory-to-ignore/file-should-be-ignored";
commit(fileToMerge, johnDoe, "Commit should be ignored: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// Should return false, because our commit falls outside of the included directory
assertFalse("Polling should ignore the change, because it falls outside the included directory.",
project.poll(listener).hasChanges());
}
/**
* testMergeCommitOutsideExcludedRegionIsProcessed() confirms behavior of excluded regions with merge commits.
* This test has an excluded region defined, for files ending with .excluded. There is no included region defined.
* The repository is set up so a non-fast-forward merge commit comes to master. The newly merged commit is a file
* ending with .should-be-processed, thus falling outside of the excluded region, so it should processed
* as a new change.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitOutsideExcludedRegionIsProcessed() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, ".*\\.excluded", null, null);
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
final String fileToMerge = "fileToMerge.should-be-processed";
commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// Should return true, because our commit falls outside of the excluded region
assertTrue("Polling should process the change, because it falls outside the excluded region.",
project.poll(listener).hasChanges());
}
/**
* testMergeCommitOutsideExcludedDirectoryIsProcessed() confirms behavior of excluded directories with merge commits.
* This test has an excluded directory `excluded` defined. There is no `included` directory defined. The repository
* is set up so that a non-fast-forward merge commit comes to master. The newly merged commit resides in a
* directory of its own, thus falling outside of the excluded directory, so it should processed
* as a new change.
*
* @throws Exception on error
*/
@Issue({"JENKINS-20389","JENKINS-23606"})
@Test
public void testMergeCommitOutsideExcludedDirectoryIsProcessed() throws Exception {
final String branchToMerge = "new-branch-we-merge-to-master";
FreeStyleProject project = setupProject("master", false, null, "excluded/.*", null, null);
final String initialCommit = "initialCommit";
commit(initialCommit, johnDoe, "Commit " + initialCommit + " to master");
build(project, Result.SUCCESS, initialCommit);
final String secondCommit = "secondCommit";
commit(secondCommit, johnDoe, "Commit " + secondCommit + " to master");
testRepo.git.checkoutBranch(branchToMerge, "HEAD~");
// Create this new file outside of our excluded directory
final String fileToMerge = "directory-to-include/file-should-be-processed";
commit(fileToMerge, johnDoe, "Commit should be noticed and processed as a change: " + fileToMerge + " to " + branchToMerge);
ObjectId branchSHA = git.revParse("HEAD");
testRepo.git.checkoutBranch("master", "refs/heads/master");
MergeCommand mergeCommand = testRepo.git.merge();
mergeCommand.setRevisionToMerge(branchSHA);
mergeCommand.execute();
// Should return true, because our commit falls outside of the excluded directory
assertTrue("SCM polling should process the change, because it falls outside the excluded directory.",
project.poll(listener).hasChanges());
}
@Test
public void testIncludedRegionWithDeeperCommits() throws Exception {
FreeStyleProject project = setupProject("master", false, null, null, null, ".*3");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
final String commitFile4 = "commitFile4";
commit(commitFile4, janeDoe, "Commit number 4");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBasicExcludedRegion() throws Exception {
FreeStyleProject project = setupProject("master", false, null, ".*2", null, null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testCleanBeforeCheckout() throws Exception {
FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null);
((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout());
final String commitFile1 = "commitFile1";
final String commitFile2 = "commitFile2";
commit(commitFile1, johnDoe, janeDoe, "Commit number 1");
commit(commitFile2, johnDoe, janeDoe, "Commit number 2");
final FreeStyleBuild firstBuild = build(p, Result.SUCCESS, commitFile1);
final String branch1 = "Branch1";
final String branch2 = "Branch2";
List<BranchSpec> branches = new ArrayList<>();
branches.add(new BranchSpec("master"));
branches.add(new BranchSpec(branch1));
branches.add(new BranchSpec(branch2));
git.branch(branch1);
git.checkout(branch1);
p.poll(listener).hasChanges();
assertThat(firstBuild.getLog(175), hasItem("Cleaning workspace"));
assertTrue(firstBuild.getLog().indexOf("Cleaning") > firstBuild.getLog().indexOf("Cloning")); //clean should be after clone
assertTrue(firstBuild.getLog().indexOf("Cleaning") < firstBuild.getLog().indexOf("Checking out")); //clean before checkout
assertTrue(firstBuild.getWorkspace().child(commitFile1).exists());
git.checkout(branch1);
final FreeStyleBuild secondBuild = build(p, Result.SUCCESS, commitFile2);
p.poll(listener).hasChanges();
assertThat(secondBuild.getLog(175), hasItem("Cleaning workspace"));
assertTrue(secondBuild.getLog().indexOf("Cleaning") < secondBuild.getLog().indexOf("Fetching upstream changes"));
assertTrue(secondBuild.getWorkspace().child(commitFile2).exists());
}
@Issue("JENKINS-8342")
@Test
public void testExcludedRegionMultiCommit() throws Exception {
// Got 2 projects, each one should only build if changes in its own file
FreeStyleProject clientProject = setupProject("master", false, null, ".*serverFile", null, null);
FreeStyleProject serverProject = setupProject("master", false, null, ".*clientFile", null, null);
String initialCommitFile = "initialFile";
commit(initialCommitFile, johnDoe, "initial commit");
build(clientProject, Result.SUCCESS, initialCommitFile);
build(serverProject, Result.SUCCESS, initialCommitFile);
assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges());
assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges());
// Got commits on serverFile, so only server project should build.
commit("myserverFile", johnDoe, "commit first server file");
assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges());
assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges());
// Got commits on both client and serverFile, so both projects should build.
commit("myNewserverFile", johnDoe, "commit new server file");
commit("myclientFile", johnDoe, "commit first clientfile");
assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges());
assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges());
}
/*
* With multiple branches specified in the project and having commits from a user
* excluded should not build the excluded revisions when another branch changes.
*/
/*
@Issue("JENKINS-8342")
@Test
public void testMultipleBranchWithExcludedUser() throws Exception {
final String branch1 = "Branch1";
final String branch2 = "Branch2";
List<BranchSpec> branches = new ArrayList<BranchSpec>();
branches.add(new BranchSpec("master"));
branches.add(new BranchSpec(branch1));
branches.add(new BranchSpec(branch2));
final FreeStyleProject project = setupProject(branches, false, null, null, janeDoe.getName(), null, false, null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// create branches here so we can get back to them later...
git.branch(branch1);
git.branch(branch2);
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1, commitFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
// Add excluded commit
final String commitFile4 = "commitFile4";
commit(commitFile4, janeDoe, "Commit number 4");
assertFalse("scm polling detected change in 'master', which should have been excluded", project.poll(listener).hasChanges());
// now jump back...
git.checkout(branch1);
final String branch1File1 = "branch1File1";
commit(branch1File1, janeDoe, "Branch1 commit number 1");
assertFalse("scm polling detected change in 'Branch1', which should have been excluded", project.poll(listener).hasChanges());
// and the other branch...
git.checkout(branch2);
final String branch2File1 = "branch2File1";
commit(branch2File1, janeDoe, "Branch2 commit number 1");
assertFalse("scm polling detected change in 'Branch2', which should have been excluded", project.poll(listener).hasChanges());
final String branch2File2 = "branch2File2";
commit(branch2File2, johnDoe, "Branch2 commit number 2");
assertTrue("scm polling should detect changes in 'Branch2' branch", project.poll(listener).hasChanges());
//... and build it...
build(project, Result.SUCCESS, branch2File1, branch2File2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// now jump back again...
git.checkout(branch1);
// Commit excluded after non-excluded commit, should trigger build.
final String branch1File2 = "branch1File2";
commit(branch1File2, johnDoe, "Branch1 commit number 2");
final String branch1File3 = "branch1File3";
commit(branch1File3, janeDoe, "Branch1 commit number 3");
assertTrue("scm polling should detect changes in 'Branch1' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, branch1File1, branch1File2, branch1File3);
} */
@Test
public void testBasicExcludedUser() throws Exception {
FreeStyleProject project = setupProject("master", false, null, null, "Jane Doe", null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBasicInSubdir() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir"));
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, "subdir", Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS,
commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertEquals("The workspace should have a 'subdir' subdirectory, but does not.", true,
build2.getWorkspace().child("subdir").exists());
assertEquals("The 'subdir' subdirectory should contain commitFile2, but does not.", true,
build2.getWorkspace().child("subdir").child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBasicWithAgent() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
project.setAssignedLabel(rule.createSlave().getSelfLabel());
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Issue("HUDSON-7547")
@Test
public void testBasicWithAgentNoExecutorsOnMaster() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
rule.jenkins.setNumExecutors(0);
project.setAssignedLabel(rule.createSlave().getSelfLabel());
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testAuthorOrCommitterFalse() throws Exception {
// Test with authorOrCommitter set to false and make sure we get the committer.
FreeStyleProject project = setupSimpleProject("master");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, janeDoe, "Commit number 1");
final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final Set<User> secondCulprits = secondBuild.getCulprits();
assertEquals("The build should have only one culprit", 1, secondCulprits.size());
assertEquals("Did not get the committer as the change author with authorOrCommitter==false",
janeDoe.getName(), secondCulprits.iterator().next().getFullName());
}
@Test
public void testAuthorOrCommitterTrue() throws Exception {
// Next, test with authorOrCommitter set to true and make sure we get the author.
FreeStyleProject project = setupSimpleProject("master");
((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog());
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, janeDoe, "Commit number 1");
final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final Set<User> secondCulprits = secondBuild.getCulprits();
assertEquals("The build should have only one culprit", 1, secondCulprits.size());
assertEquals("Did not get the author as the change author with authorOrCommitter==true",
johnDoe.getName(), secondCulprits.iterator().next().getFullName());
}
@Test
public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
//now create and checkout a new branch:
git.checkout(Constants.HEAD, "untracked");
//.. and commit to it:
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges());
}
private String checkoutString(FreeStyleProject project, String envVar) {
return "checkout -f " + getEnvVars(project).get(envVar);
}
@Test
public void testEnvVarsAvailable() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
rule.waitForMessage(getEnvVars(project).get(GitSCM.GIT_BRANCH), build1);
rule.waitForMessage(checkoutString(project, GitSCM.GIT_COMMIT), build1);
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build2);
rule.waitForMessage(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build1);
rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build2);
rule.waitForMessage(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build1);
}
@Issue("HUDSON-7411")
@Test
public void testNodeEnvVarsAvailable() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
DumbSlave agent = rule.createSlave();
setVariables(agent, new Entry("TESTKEY", "agent value"));
project.setAssignedLabel(agent.getSelfLabel());
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertEquals("agent value", getEnvVars(project).get("TESTKEY"));
}
@Test
public void testNodeOverrideGit() throws Exception {
GitSCM scm = new GitSCM(null);
DumbSlave agent = rule.createSlave();
GitTool.DescriptorImpl gitToolDescriptor = rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class);
GitTool installation = new GitTool("Default", "/usr/bin/git", null);
gitToolDescriptor.setInstallations(installation);
String gitExe = scm.getGitExe(agent, TaskListener.NULL);
assertEquals("/usr/bin/git", gitExe);
ToolLocationNodeProperty nodeGitLocation = new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(gitToolDescriptor, "Default", "C:\\Program Files\\Git\\bin\\git.exe"));
agent.setNodeProperties(Collections.singletonList(nodeGitLocation));
gitExe = scm.getGitExe(agent, TaskListener.NULL);
assertEquals("C:\\Program Files\\Git\\bin\\git.exe", gitExe);
}
/*
* A previous version of GitSCM would only build against branches, not tags. This test checks that that
* regression has been fixed.
*/
@Test
public void testGitSCMCanBuildAgainstTags() throws Exception {
final String mytag = "mytag";
FreeStyleProject project = setupSimpleProject(mytag);
build(project, Result.FAILURE); // fail, because there's nothing to be checked out here
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
// Try again. The first build will leave the repository in a bad state because we
// cloned something without even a HEAD - which will mean it will want to re-clone once there is some
// actual data.
build(project, Result.FAILURE); // fail, because there's nothing to be checked out here
//now create and checkout a new branch:
final String tmpBranch = "tmp";
git.branch(tmpBranch);
git.checkout(tmpBranch);
// commit to it
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges());
build(project, Result.FAILURE); // fail, because there's nothing to be checked out here
// tag it, then delete the tmp branch
git.tag(mytag, "mytag initial");
git.checkout("master");
git.deleteBranch(tmpBranch);
// at this point we're back on master, there are no other branches, tag "mytag" exists but is
// not part of "master"
assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
// now, create tmp branch again against mytag:
git.checkout(mytag);
git.branch(tmpBranch);
// another commit:
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges());
// now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up:
git.tag(mytag, "mytag moved");
git.checkout("master");
git.deleteBranch(tmpBranch);
// at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit:
assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile3);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
}
/*
* Not specifying a branch string in the project implies that we should be polling for changes in
* all branches.
*/
@Test
public void testMultipleBranchBuild() throws Exception {
// empty string will result in a project that tracks against changes in all branches:
final FreeStyleProject project = setupSimpleProject("");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
// create a branch here so we can get back to this point later...
final String fork = "fork";
git.branch(fork);
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1, commitFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
// now jump back...
git.checkout(fork);
// add some commits to the fork branch...
final String forkFile1 = "forkFile1";
commit(forkFile1, johnDoe, "Fork commit number 1");
final String forkFile2 = "forkFile2";
commit(forkFile2, johnDoe, "Fork commit number 2");
assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, forkFile1, forkFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
}
@Test
public void testMultipleBranchesWithTags() throws Exception {
List<BranchSpec> branchSpecs = Arrays.asList(
new BranchSpec("refs/tags/v*"),
new BranchSpec("refs/remotes/origin/non-existent"));
FreeStyleProject project = setupProject(branchSpecs, false, null, null, janeDoe.getName(), null, false, null);
// create initial commit and then run the build against it:
// Here the changelog is by default empty (because changelog for first commit is always empty
commit("commitFileBase", johnDoe, "Initial Commit");
// there are no branches to be build
FreeStyleBuild freeStyleBuild = build(project, Result.FAILURE);
final String v1 = "v1";
git.tag(v1, "version 1");
assertTrue("v1 tag exists", git.tagExists(v1));
freeStyleBuild = build(project, Result.SUCCESS);
assertTrue("change set is empty", freeStyleBuild.getChangeSet().isEmptySet());
commit("file1", johnDoe, "change to file1");
git.tag("none", "latest");
freeStyleBuild = build(project, Result.SUCCESS);
ObjectId tag = git.revParse(Constants.R_TAGS + v1);
GitSCM scm = (GitSCM)project.getScm();
BuildData buildData = scm.getBuildData(freeStyleBuild);
assertEquals("last build matches the v1 tag revision", tag, buildData.lastBuild.getSHA1());
}
@Issue("JENKINS-19037")
@SuppressWarnings("ResultOfObjectAllocationIgnored")
@Test
public void testBlankRepositoryName() throws Exception {
new GitSCM(null);
}
@Issue("JENKINS-10060")
@Test
public void testSubmoduleFixup() throws Exception {
File repo = secondRepo.getRoot();
FilePath moduleWs = new FilePath(repo);
org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient();
{// first we create a Git repository with submodule
moduleRepo.init();
moduleWs.child("a").touch(0);
moduleRepo.add("a");
moduleRepo.commit("creating a module");
git.addSubmodule(repo.getAbsolutePath(), "module1");
git.commit("creating a super project");
}
// configure two uproject 'u' -> 'd' that's chained together.
FreeStyleProject u = createFreeStyleProject();
FreeStyleProject d = createFreeStyleProject();
u.setScm(new GitSCM(workDir.getPath()));
u.getPublishersList().add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig(d.getName(), ResultCondition.SUCCESS,
new GitRevisionBuildParameters())));
d.setScm(new GitSCM(workDir.getPath()));
rule.jenkins.rebuildDependencyGraph();
FreeStyleBuild ub = rule.assertBuildStatusSuccess(u.scheduleBuild2(0));
for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop
Thread.sleep(100);
FreeStyleBuild db = d.getLastBuild();
assertNotNull("downstream build didn't happen",db);
rule.assertBuildStatusSuccess(db);
}
@Test
public void testBuildChooserContext() throws Exception {
final FreeStyleProject p = createFreeStyleProject();
final FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0));
BuildChooserContextImpl c = new BuildChooserContextImpl(p, b, null);
c.actOnBuild(new ContextCallable<Run<?,?>, Object>() {
public Object invoke(Run param, VirtualChannel channel) throws IOException, InterruptedException {
assertSame(param,b);
return null;
}
});
c.actOnProject(new ContextCallable<Job<?,?>, Object>() {
public Object invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException {
assertSame(param,p);
return null;
}
});
DumbSlave agent = rule.createOnlineSlave();
assertEquals(p.toString(), agent.getChannel().call(new BuildChooserContextTestCallable(c)));
}
private static class BuildChooserContextTestCallable extends MasterToSlaveCallable<String,IOException> {
private final BuildChooserContext c;
public BuildChooserContextTestCallable(BuildChooserContext c) {
this.c = c;
}
public String call() throws IOException {
try {
return c.actOnProject(new ContextCallable<Job<?,?>, String>() {
public String invoke(Job<?,?> param, VirtualChannel channel) throws IOException, InterruptedException {
assertTrue(channel instanceof Channel);
assertTrue(Jenkins.getInstanceOrNull()!=null);
return param.toString();
}
});
} catch (InterruptedException e) {
throw new IOException(e);
}
}
}
// eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe])
static public void assertCulprits(String assertMsg, Set<User> actual, PersonIdent[] expected)
{
Collection<String> fullNames = Collections2.transform(actual, new Function<User,String>() {
public String apply(User u)
{
return u.getFullName();
}
});
for(PersonIdent p : expected)
{
assertTrue(assertMsg, fullNames.contains(p.getName()));
}
}
@Test
public void testEmailCommitter() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// setup global config
GitSCM scm = (GitSCM) project.getScm();
final DescriptorImpl descriptor = (DescriptorImpl) scm.getDescriptor();
assertFalse("Wrong initial value for create account based on e-mail", scm.isCreateAccountBasedOnEmail());
descriptor.setCreateAccountBasedOnEmail(true);
assertTrue("Create account based on e-mail not set", scm.isCreateAccountBasedOnEmail());
assertFalse("Wrong initial value for use existing user if same e-mail already found", scm.isUseExistingAccountWithSameEmail());
descriptor.setUseExistingAccountWithSameEmail(true);
assertTrue("Use existing user if same e-mail already found is not set", scm.isUseExistingAccountWithSameEmail());
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "jeff@doe.com");
commit(commitFile2, jeffDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
User culprit = culprits.iterator().next();
assertEquals("", jeffDoe.getEmailAddress(), culprit.getId());
assertEquals("", jeffDoe.getName(), culprit.getFullName());
rule.assertBuildStatusSuccess(build);
}
@Issue("JENKINS-59868")
@Test
public void testNonExistentWorkingDirectoryPoll() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// create initial commit and then run the build against it
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
project.setScm(new GitSCM(
((GitSCM)project.getScm()).getUserRemoteConfigs(),
Collections.singletonList(new BranchSpec("master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
// configure GitSCM with the DisableRemotePoll extension to ensure that polling use the workspace
Collections.singletonList(new DisableRemotePoll())));
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
// Empty the workspace directory
build1.getWorkspace().deleteRecursive();
// Setup a recorder for polling logs
RingBufferLogHandler pollLogHandler = new RingBufferLogHandler(10);
Logger pollLogger = Logger.getLogger(GitSCMTest.class.getName());
pollLogger.addHandler(pollLogHandler);
TaskListener taskListener = new LogTaskListener(pollLogger, Level.INFO);
// Make sure that polling returns BUILD_NOW and properly log the reason
FilePath filePath = build1.getWorkspace();
assertThat(project.getScm().compareRemoteRevisionWith(project, new Launcher.LocalLauncher(taskListener),
filePath, taskListener, null), is(PollingResult.BUILD_NOW));
assertTrue(pollLogHandler.getView().stream().anyMatch(m ->
m.getMessage().contains("[poll] Working Directory does not exist")));
}
// Disabled - consistently fails, needs more analysis
// @Test
public void testFetchFromMultipleRepositories() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener);
List<UserRemoteConfig> remotes = new ArrayList<>();
remotes.addAll(testRepo.remoteConfigs());
remotes.addAll(secondTestRepo.remoteConfigs());
project.setScm(new GitSCM(
remotes,
Collections.singletonList(new BranchSpec("master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList()));
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
/* Diagnostic help - for later use */
SCMRevisionState baseline = project.poll(listener).baseline;
Change change = project.poll(listener).change;
SCMRevisionState remote = project.poll(listener).remote;
String assertionMessage = MessageFormat.format("polling incorrectly detected change after build. Baseline: {0}, Change: {1}, Remote: {2}", baseline, change, remote);
assertFalse(assertionMessage, project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
private void branchSpecWithMultipleRepositories(String branchName) throws Exception {
FreeStyleProject project = setupSimpleProject("master");
TestGitRepo secondTestRepo = new TestGitRepo("second", secondRepo.getRoot(), listener);
List<UserRemoteConfig> remotes = new ArrayList<>();
remotes.addAll(testRepo.remoteConfigs());
remotes.addAll(secondTestRepo.remoteConfigs());
// create initial commit
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
project.setScm(new GitSCM(
remotes,
Collections.singletonList(new BranchSpec(branchName)),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList()));
final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1);
rule.assertBuildStatusSuccess(build);
}
@Issue("JENKINS-26268")
public void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception {
branchSpecWithMultipleRepositories(testRepo.git.revParse("HEAD").getName());
}
@Issue("JENKINS-26268")
public void testBranchSpecAsRemotesOriginMasterWithMultipleRepositories() throws Exception {
branchSpecWithMultipleRepositories("remotes/origin/master");
}
@Issue("JENKINS-25639")
@Test
public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
TestGitRepo secondTestRepo = new TestGitRepo("secondRepo", secondRepo.getRoot(), listener);
List<UserRemoteConfig> remotes = new ArrayList<>();
remotes.addAll(testRepo.remoteConfigs());
remotes.addAll(secondTestRepo.remoteConfigs());
GitSCM gitSCM = new GitSCM(
remotes,
Collections.singletonList(new BranchSpec("origin/master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(gitSCM);
/* Check that polling would force build through
* compareRemoteRevisionWith by detecting no last build */
FilePath filePath = new FilePath(new File("."));
assertThat(gitSCM.compareRemoteRevisionWith(project, new Launcher.LocalLauncher(listener), filePath, listener, null), is(PollingResult.BUILD_NOW));
commit("commitFile1", johnDoe, "Commit number 1");
FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1");
commit("commitFile2", johnDoe, "Commit number 2");
git = Git.with(listener, new EnvVars()).in(build.getWorkspace()).getClient();
for (RemoteConfig remoteConfig : gitSCM.getRepositories()) {
git.fetch_().from(remoteConfig.getURIs().get(0), remoteConfig.getFetchRefSpecs());
}
BuildChooser buildChooser = gitSCM.getBuildChooser();
Collection<Revision> candidateRevisions = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null);
assertEquals(1, candidateRevisions.size());
gitSCM.setBuildChooser(buildChooser); // Should be a no-op
Collection<Revision> candidateRevisions2 = buildChooser.getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null);
assertThat(candidateRevisions2, is(candidateRevisions));
}
private final Random random = new Random();
private boolean useChangelogToBranch = random.nextBoolean();
private void addChangelogToBranchExtension(GitSCM scm) {
if (useChangelogToBranch) {
/* Changelog should be no different with this enabled or disabled */
ChangelogToBranchOptions changelogOptions = new ChangelogToBranchOptions("origin", "master");
scm.getExtensions().add(new ChangelogToBranch(changelogOptions));
}
useChangelogToBranch = !useChangelogToBranch;
}
@Test
public void testMerge() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF)));
addChangelogToBranchExtension(scm);
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Issue("JENKINS-20392")
@Test
public void testMergeChangelog() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF)));
addChangelogToBranchExtension(scm);
project.setScm(scm);
// create initial commit and then run the build against it:
// Here the changelog is by default empty (because changelog for first commit is always empty
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
// Create second commit and run build
// Here the changelog should contain exactly this one new commit
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
String commitMessage = "Commit number 2";
commit(commitFile2, johnDoe, commitMessage);
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
ChangeLogSet<? extends ChangeLogSet.Entry> changeLog = build2.getChangeSet();
assertEquals("Changelog should contain one item", 1, changeLog.getItems().length);
GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0];
assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim());
}
@Test
public void testMergeWithAgent() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
project.setAssignedLabel(rule.createSlave().getSelfLabel());
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null)));
addChangelogToBranchExtension(scm);
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testMergeFailed() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF)));
addChangelogToBranchExtension(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
commit(commitFile1, "other content", johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.FAILURE);
rule.assertBuildStatus(Result.FAILURE, build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Issue("JENKINS-25191")
@Test
public void testMultipleMergeFailed() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF)));
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF)));
addChangelogToBranchExtension(scm);
commit("dummyFile", johnDoe, "Initial Commit");
testRepo.git.branch("integration1");
testRepo.git.branch("integration2");
build(project, Result.SUCCESS);
final String commitFile = "commitFile";
testRepo.git.checkoutBranch("integration1","master");
commit(commitFile,"abc", johnDoe, "merge conflict with integration2");
testRepo.git.checkoutBranch("integration2","master");
commit(commitFile,"cde", johnDoe, "merge conflict with integration1");
final FreeStyleBuild build = build(project, Result.FAILURE);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testMergeFailedWithAgent() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
project.setAssignedLabel(rule.createSlave().getSelfLabel());
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null)));
addChangelogToBranchExtension(scm);
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
commit(commitFile1, "other content", johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.FAILURE);
rule.assertBuildStatus(Result.FAILURE, build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testMergeWithMatrixBuild() throws Exception {
//Create a matrix project and a couple of axes
MatrixProject project = rule.jenkins.createProject(MatrixProject.class, "xyz");
project.setAxes(new AxisList(new Axis("VAR","a","b")));
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null)));
addChangelogToBranchExtension(scm);
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testEnvironmentVariableExpansion() throws Exception {
FreeStyleProject project = createFreeStyleProject();
project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath()));
// create initial commit and then run the build against it:
commit("a.txt", johnDoe, "Initial Commit");
build(project, Result.SUCCESS, "a.txt");
PollingResult r = project.poll(StreamTaskListener.fromStdout());
assertFalse(r.hasChanges());
commit("b.txt", johnDoe, "Another commit");
r = project.poll(StreamTaskListener.fromStdout());
assertTrue(r.hasChanges());
build(project, Result.SUCCESS, "b.txt");
}
@TestExtension("testEnvironmentVariableExpansion")
public static class SupplySomeEnvVars extends EnvironmentContributor {
@Override
public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {
envs.put("CAT","");
}
}
private List<UserRemoteConfig> createRepoList(String url) {
List<UserRemoteConfig> repoList = new ArrayList<>();
repoList.add(new UserRemoteConfig(url, null, null, null));
return repoList;
}
/*
* Makes sure that git browser URL is preserved across config round trip.
*/
@Issue("JENKINS-22604")
@Test
public void testConfigRoundtripURLPreserved() throws Exception {
FreeStyleProject p = createFreeStyleProject();
final String url = "https://github.com/jenkinsci/jenkins";
GitRepositoryBrowser browser = new GithubWeb(url);
GitSCM scm = new GitSCM(createRepoList(url),
Collections.singletonList(new BranchSpec("")),
false, Collections.<SubmoduleConfig>emptyList(),
browser, null, null);
p.setScm(scm);
rule.configRoundtrip(p);
rule.assertEqualDataBoundBeans(scm,p.getScm());
assertEquals("Wrong key", "git " + url, scm.getKey());
}
/*
* Makes sure that git extensions are preserved across config round trip.
*/
@Issue("JENKINS-33695")
@Test
public void testConfigRoundtripExtensionsPreserved() throws Exception {
FreeStyleProject p = createFreeStyleProject();
final String url = "git://github.com/jenkinsci/git-plugin.git";
GitRepositoryBrowser browser = new GithubWeb(url);
GitSCM scm = new GitSCM(createRepoList(url),
Collections.singletonList(new BranchSpec("*/master")),
false, Collections.<SubmoduleConfig>emptyList(),
browser, null, null);
p.setScm(scm);
/* Assert that no extensions are loaded initially */
assertEquals(Collections.emptyList(), scm.getExtensions().toList());
/* Add LocalBranch extension */
LocalBranch localBranchExtension = new LocalBranch("**");
scm.getExtensions().add(localBranchExtension);
assertTrue(scm.getExtensions().toList().contains(localBranchExtension));
/* Save the configuration */
rule.configRoundtrip(p);
List<GitSCMExtension> extensions = scm.getExtensions().toList();;
assertTrue(extensions.contains(localBranchExtension));
assertEquals("Wrong extension count before reload", 1, extensions.size());
/* Reload configuration from disc */
p.doReload();
GitSCM reloadedGit = (GitSCM) p.getScm();
List<GitSCMExtension> reloadedExtensions = reloadedGit.getExtensions().toList();
assertEquals("Wrong extension count after reload", 1, reloadedExtensions.size());
LocalBranch reloadedLocalBranch = (LocalBranch) reloadedExtensions.get(0);
assertEquals(localBranchExtension.getLocalBranch(), reloadedLocalBranch.getLocalBranch());
}
/*
* Makes sure that the configuration form works.
*/
@Test
public void testConfigRoundtrip() throws Exception {
FreeStyleProject p = createFreeStyleProject();
GitSCM scm = new GitSCM("https://github.com/jenkinsci/jenkins");
p.setScm(scm);
rule.configRoundtrip(p);
rule.assertEqualDataBoundBeans(scm,p.getScm());
}
/*
* Sample configuration that should result in no extensions at all
*/
@Test
public void testDataCompatibility1() throws Exception {
FreeStyleProject p = (FreeStyleProject) rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml"));
GitSCM oldGit = (GitSCM) p.getScm();
assertEquals(Collections.emptyList(), oldGit.getExtensions().toList());
assertEquals(0, oldGit.getSubmoduleCfg().size());
assertEquals("git git://github.com/jenkinsci/model-ant-project.git", oldGit.getKey());
assertThat(oldGit.getEffectiveBrowser(), instanceOf(GithubWeb.class));
GithubWeb browser = (GithubWeb) oldGit.getEffectiveBrowser();
assertEquals(browser.getRepoUrl(), "https://github.com/jenkinsci/model-ant-project.git/");
}
@Test
public void testPleaseDontContinueAnyway() throws Exception {
// create an empty repository with some commits
testRepo.commit("a","foo",johnDoe, "added");
FreeStyleProject p = createFreeStyleProject();
p.setScm(new GitSCM(testRepo.gitDir.getAbsolutePath()));
rule.assertBuildStatusSuccess(p.scheduleBuild2(0));
// this should fail as it fails to fetch
p.setScm(new GitSCM("http://localhost:4321/no/such/repository.git"));
rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
}
@Issue("JENKINS-19108")
@Test
public void testCheckoutToSpecificBranch() throws Exception {
FreeStyleProject p = createFreeStyleProject();
GitSCM oldGit = new GitSCM("https://github.com/jenkinsci/model-ant-project.git/");
setupJGit(oldGit);
oldGit.getExtensions().add(new LocalBranch("master"));
p.setScm(oldGit);
FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0));
GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient();
gc.withRepository(new RepositoryCallback<Void>() {
public Void invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException {
Ref head = repo.findRef("HEAD");
assertTrue("Detached HEAD",head.isSymbolic());
Ref t = head.getTarget();
assertEquals(t.getName(),"refs/heads/master");
return null;
}
});
}
/**
* Verifies that if project specifies LocalBranch with value of "**"
* that the checkout to a local branch using remote branch name sans 'origin'.
* This feature is necessary to support Maven release builds that push updated
* pom.xml to remote branch as
* <pre>
* git push origin localbranch:localbranch
* </pre>
* @throws Exception on error
*/
@Test
public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
GitSCM git = (GitSCM)project.getScm();
git.getExtensions().add(new LocalBranch("**"));
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH));
}
/**
* Verifies that if project specifies LocalBranch with null value (empty string)
* that the checkout to a local branch using remote branch name sans 'origin'.
* This feature is necessary to support Maven release builds that push updated
* pom.xml to remote branch as
* <pre>
* git push origin localbranch:localbranch
* </pre>
* @throws Exception on error
*/
@Test
public void testCheckoutToDefaultLocalBranch_NULL() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
GitSCM git = (GitSCM)project.getScm();
git.getExtensions().add(new LocalBranch(""));
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH));
}
/*
* Verifies that GIT_LOCAL_BRANCH is not set if LocalBranch extension
* is not configured.
*/
@Test
public void testCheckoutSansLocalBranchExtension() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
assertEquals("GIT_LOCAL_BRANCH", null, getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH));
}
/*
* Verifies that GIT_CHECKOUT_DIR is set to "checkoutDir" if RelativeTargetDirectory extension
* is configured.
*/
@Test
public void testCheckoutRelativeTargetDirectoryExtension() throws Exception {
FreeStyleProject project = setupProject("master", false, "checkoutDir");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
GitSCM git = (GitSCM)project.getScm();
git.getExtensions().add(new RelativeTargetDirectory("checkoutDir"));
FreeStyleBuild build1 = build(project, "checkoutDir", Result.SUCCESS, commitFile1);
assertEquals("GIT_CHECKOUT_DIR", "checkoutDir", getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR));
}
/*
* Verifies that GIT_CHECKOUT_DIR is not set if RelativeTargetDirectory extension
* is not configured.
*/
@Test
public void testCheckoutSansRelativeTargetDirectoryExtension() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("GIT_CHECKOUT_DIR", null, getEnvVars(project).get(GitSCM.GIT_CHECKOUT_DIR));
}
@Test
public void testCheckoutFailureIsRetryable() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// run build first to create workspace
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
// create lock file to simulate lock collision
File lock = new File(build1.getWorkspace().getRemote(), ".git/index.lock");
try {
FileUtils.touch(lock);
final FreeStyleBuild build2 = build(project, Result.FAILURE);
rule.waitForMessage("java.io.IOException: Could not checkout", build2);
} finally {
lock.delete();
}
}
@Test
public void testInitSparseCheckout() throws Exception {
if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("toto")));
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("toto").exists());
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse(build1.getWorkspace().child("titi").exists());
assertFalse(build1.getWorkspace().child(commitFile2).exists());
}
@Test
public void testInitSparseCheckoutBis() throws Exception {
if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi")));
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertFalse(build1.getWorkspace().child("toto").exists());
assertFalse(build1.getWorkspace().child(commitFile1).exists());
}
@Test
public void testSparseCheckoutAfterNormalCheckout() throws Exception {
if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupSimpleProject("master");
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertTrue(build1.getWorkspace().child("toto").exists());
assertTrue(build1.getWorkspace().child(commitFile1).exists());
((GitSCM) project.getScm()).getExtensions().add(new SparseCheckoutPaths(Lists.newArrayList(new SparseCheckoutPath("titi"))));
final FreeStyleBuild build2 = build(project, Result.SUCCESS);
assertTrue(build2.getWorkspace().child("titi").exists());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertFalse(build2.getWorkspace().child("toto").exists());
assertFalse(build2.getWorkspace().child(commitFile1).exists());
}
@Test
public void testNormalCheckoutAfterSparseCheckout() throws Exception {
if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi")));
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build2 = build(project, Result.SUCCESS);
assertTrue(build2.getWorkspace().child("titi").exists());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertFalse(build2.getWorkspace().child("toto").exists());
assertFalse(build2.getWorkspace().child(commitFile1).exists());
((GitSCM) project.getScm()).getExtensions().remove(SparseCheckoutPaths.class);
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertTrue(build1.getWorkspace().child("toto").exists());
assertTrue(build1.getWorkspace().child(commitFile1).exists());
}
@Test
public void testInitSparseCheckoutOverAgent() throws Exception {
if (!sampleRepo.gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi")));
project.setAssignedLabel(rule.createSlave().getSelfLabel());
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertFalse(build1.getWorkspace().child("toto").exists());
assertFalse(build1.getWorkspace().child(commitFile1).exists());
}
@Test
@Issue("JENKINS-22009")
public void testPolling_environmentValueInBranchSpec() throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("${MY_BRANCH}")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master")));
// commit something in order to create an initial base version in git
commit("toto/commitFile1", johnDoe, "Commit number 1");
// build the project
build(project, Result.SUCCESS);
assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges());
}
@Issue("JENKINS-29066")
public void baseTestPolling_parentHead(List<GitSCMExtension> extensions) throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("**")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
extensions);
project.setScm(scm);
// commit something in order to create an initial base version in git
commit("toto/commitFile1", johnDoe, "Commit number 1");
git.branch("someBranch");
commit("toto/commitFile2", johnDoe, "Commit number 2");
assertTrue("polling should detect changes",project.poll(listener).hasChanges());
// build the project
build(project, Result.SUCCESS);
/* Expects 1 build because the build of someBranch incorporates all
* the changes from the master branch as well as the changes from someBranch.
*/
assertEquals("Wrong number of builds", 1, project.getBuilds().size());
assertFalse("polling should not detect changes",project.poll(listener).hasChanges());
}
@Issue("JENKINS-29066")
@Test
public void testPolling_parentHead() throws Exception {
baseTestPolling_parentHead(Collections.<GitSCMExtension>emptyList());
}
@Issue("JENKINS-29066")
@Test
public void testPolling_parentHead_DisableRemotePoll() throws Exception {
baseTestPolling_parentHead(Collections.<GitSCMExtension>singletonList(new DisableRemotePoll()));
}
@Test
public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("${MY_BRANCH}")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch")));
// Initial commit to master
commit("file1", johnDoe, "Initial Commit");
// Create the branches
git.branch("trackedbranch");
git.branch("manualbranch");
final StringParameterValue branchParam = new StringParameterValue("MY_BRANCH", "manualbranch");
final Action[] actions = {new ParametersAction(branchParam)};
FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get();
rule.assertBuildStatus(Result.SUCCESS, build);
assertFalse("No changes to git since last build", project.poll(listener).hasChanges());
git.checkout("manualbranch");
commit("file2", johnDoe, "Commit to manually build branch");
assertFalse("No changes to tracked branch", project.poll(listener).hasChanges());
git.checkout("trackedbranch");
commit("file3", johnDoe, "Commit to tracked branch");
assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges());
}
private final class FakeParametersAction implements EnvironmentContributingAction, Serializable {
// Test class for testPolling_environmentValueAsEnvironmentContributingAction test case
final ParametersAction m_forwardingAction;
public FakeParametersAction(StringParameterValue params) {
this.m_forwardingAction = new ParametersAction(params);
}
public void buildEnvVars(AbstractBuild<?, ?> ab, EnvVars ev) {
this.m_forwardingAction.buildEnvVars(ab, ev);
}
public String getIconFileName() {
return this.m_forwardingAction.getIconFileName();
}
public String getDisplayName() {
return this.m_forwardingAction.getDisplayName();
}
public String getUrlName() {
return this.m_forwardingAction.getUrlName();
}
public List<ParameterValue> getParameters() {
return this.m_forwardingAction.getParameters();
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
}
private void readObjectNoData() throws ObjectStreamException {
}
}
@Test
public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception {
FreeStyleProject project = createFreeStyleProject();
List<UserRemoteConfig> remoteConfigs = new ArrayList<>();
remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null));
remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null));
GitSCM scm = new GitSCM(remoteConfigs,
Collections.singletonList(new BranchSpec("origin/master")), false,
Collections.<SubmoduleConfig> emptyList(), null, null,
Collections.<GitSCMExtension> emptyList());
project.setScm(scm);
commit("commitFile1", johnDoe, "Commit number 1");
FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause()).get();
rule.assertBuildStatus(Result.SUCCESS, first_build);
first_build.getWorkspace().deleteContents();
PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null);
assertFalse(pollingResult.hasChanges());
}
@Issue("JENKINS-24467")
@Test
public void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("${MY_BRANCH}")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
// Initial commit and build
commit("toto/commitFile1", johnDoe, "Commit number 1");
String brokenPath = "\\broken/path\\of/doom";
if (!sampleRepo.gitVersionAtLeast(1, 8)) {
/* Git 1.7.10.4 fails the first build unless the git-upload-pack
* program is available in its PATH.
* Later versions of git don't have that problem.
*/
final String systemPath = System.getenv("PATH");
brokenPath = systemPath + File.pathSeparator + brokenPath;
}
final StringParameterValue real_param = new StringParameterValue("MY_BRANCH", "master");
final StringParameterValue fake_param = new StringParameterValue("PATH", brokenPath);
final Action[] actions = {new ParametersAction(real_param), new FakeParametersAction(fake_param)};
// SECURITY-170 - have to use ParametersDefinitionProperty
project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master")));
FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get();
rule.assertBuildStatus(Result.SUCCESS, first_build);
Launcher launcher = workspace.createLauncher(listener);
final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener);
assertEquals(environment.get("MY_BRANCH"), "master");
assertNotSame("Environment path should not be broken path", environment.get("PATH"), brokenPath);
}
/**
* Tests that builds have the correctly specified Custom SCM names, associated with each build.
* @throws Exception on error
*/
@Ignore("Intermittent failures on stable-3.10 branch and master branch, not on stable-3.9")
@Test
public void testCustomSCMName() throws Exception {
final String branchName = "master";
final FreeStyleProject project = setupProject(branchName, false);
project.addTrigger(new SCMTrigger(""));
GitSCM git = (GitSCM) project.getScm();
setupJGit(git);
final String commitFile1 = "commitFile1";
final String scmNameString1 = "";
commit(commitFile1, johnDoe, "Commit number 1");
assertTrue("scm polling should not detect any more changes after build",
project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1);
final ObjectId commit1 = testRepo.git.revListAll().get(0);
// Check unset build SCM Name carries
final int buildNumber1 = notifyAndCheckScmName(
project, commit1, scmNameString1, 1, git);
final String scmNameString2 = "ScmName2";
git.getExtensions().replace(new ScmName(scmNameString2));
commit("commitFile2", johnDoe, "Commit number 2");
assertTrue("scm polling should detect commit 2 (commit1=" + commit1 + ")", project.poll(listener).hasChanges());
final ObjectId commit2 = testRepo.git.revListAll().get(0);
// Check second set SCM Name
final int buildNumber2 = notifyAndCheckScmName(
project, commit2, scmNameString2, 2, git, commit1);
checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git);
final String scmNameString3 = "ScmName3";
git.getExtensions().replace(new ScmName(scmNameString3));
commit("commitFile3", johnDoe, "Commit number 3");
assertTrue("scm polling should detect commit 3, (commit2=" + commit2 + ",commit1=" + commit1 + ")", project.poll(listener).hasChanges());
final ObjectId commit3 = testRepo.git.revListAll().get(0);
// Check third set SCM Name
final int buildNumber3 = notifyAndCheckScmName(
project, commit3, scmNameString3, 3, git, commit2, commit1);
checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git);
checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git);
commit("commitFile4", johnDoe, "Commit number 4");
assertTrue("scm polling should detect commit 4 (commit3=" + commit3 + ",commit2=" + commit2 + ",commit1=" + commit1 + ")", project.poll(listener).hasChanges());
final ObjectId commit4 = testRepo.git.revListAll().get(0);
// Check third set SCM Name still set
final int buildNumber4 = notifyAndCheckScmName(
project, commit4, scmNameString3, 4, git, commit3, commit2, commit1);
checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git);
checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git);
checkNumberedBuildScmName(project, buildNumber3, scmNameString3, git);
}
/**
* Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1
* and tests for custom SCM name build data consistency.
* @param project project to build
* @param commit commit to build
* @param expectedScmName Expected SCM name for commit.
* @param ordinal number of commit to log into errors, if any
* @param git git SCM
* @throws Exception on error
*/
private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit,
String expectedScmName, int ordinal, GitSCM git, ObjectId... priorCommits) throws Exception {
String priorCommitIDs = "";
for (ObjectId priorCommit : priorCommits) {
priorCommitIDs = priorCommitIDs + " " + priorCommit;
}
assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit));
final Build build = project.getLastBuild();
final BuildData buildData = git.getBuildData(build);
assertEquals("Expected SHA1 != built SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, commit, buildData
.getLastBuiltRevision().getSha1());
assertEquals("Expected SHA1 != retrieved SHA1 for commit " + ordinal + " priors:" + priorCommitIDs, commit, buildData.getLastBuild(commit).getSHA1());
assertTrue("Commit " + ordinal + " not marked as built", buildData.hasBeenBuilt(commit));
assertEquals("Wrong SCM Name for commit " + ordinal, expectedScmName, buildData.getScmName());
return build.getNumber();
}
private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber,
String expectedScmName, GitSCM git) throws Exception {
final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber));
assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName());
}
/*
* Tests that builds have the correctly specified branches, associated with
* the commit id, passed with "notifyCommit" URL.
*/
@Ignore("Intermittent failures on stable-3.10 branch, not on stable-3.9 or master")
@Issue("JENKINS-24133")
// Flaky test distracting from primary focus
// @Test
public void testSha1NotificationBranches() throws Exception {
final String branchName = "master";
final FreeStyleProject project = setupProject(branchName, false);
project.addTrigger(new SCMTrigger(""));
final GitSCM git = (GitSCM) project.getScm();
setupJGit(git);
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
assertTrue("scm polling should detect commit 1",
project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1);
final ObjectId commit1 = testRepo.git.revListAll().get(0);
notifyAndCheckBranch(project, commit1, branchName, 1, git);
commit("commitFile2", johnDoe, "Commit number 2");
assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges());
final ObjectId commit2 = testRepo.git.revListAll().get(0);
notifyAndCheckBranch(project, commit2, branchName, 2, git);
notifyAndCheckBranch(project, commit1, branchName, 1, git);
}
/* A null pointer exception was detected because the plugin failed to
* write a branch name to the build data, so there was a SHA1 recorded
* in the build data, but no branch name.
*/
@Test
public void testNoNullPointerExceptionWithNullBranch() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch(null, sha1);
List<Branch> branchList = new ArrayList<>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
scm.buildEnvVars(build, new EnvVars()); // NPE here before fix applied
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
@Test
public void testBuildEnvVarsLocalBranchStarStar() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch("origin/master", sha1);
List<Branch> branchList = new ArrayList<>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
scm.getExtensions().add(new LocalBranch("**"));
EnvVars env = new EnvVars();
scm.buildEnvVars(build, env); // NPE here before fix applied
assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH"));
assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH"));
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
@Test
public void testBuildEnvVarsLocalBranchNull() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch("origin/master", sha1);
List<Branch> branchList = new ArrayList<>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
scm.getExtensions().add(new LocalBranch(""));
EnvVars env = new EnvVars();
scm.buildEnvVars(build, env); // NPE here before fix applied
assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH"));
assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH"));
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
@Test
public void testBuildEnvVarsLocalBranchNotSet() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch("origin/master", sha1);
List<Branch> branchList = new ArrayList<>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
EnvVars env = new EnvVars();
scm.buildEnvVars(build, env); // NPE here before fix applied
assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH"));
assertEquals("GIT_LOCAL_BRANCH", null, env.get("GIT_LOCAL_BRANCH"));
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
@Issue("JENKINS-38241")
@Test
public void testCommitMessageIsPrintedToLogs() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=test commit");
FreeStyleProject p = setupSimpleProject("master");
Run<?,?> run = rule.buildAndAssertSuccess(p);
TaskListener mockListener = Mockito.mock(TaskListener.class);
Mockito.when(mockListener.getLogger()).thenReturn(Mockito.spy(StreamTaskListener.fromStdout().getLogger()));
p.getScm().checkout(run, new Launcher.LocalLauncher(listener),
new FilePath(run.getRootDir()).child("tmp-" + "master"),
mockListener, null, SCMRevisionState.NONE);
ArgumentCaptor<String> logCaptor = ArgumentCaptor.forClass(String.class);
verify(mockListener.getLogger(), atLeastOnce()).println(logCaptor.capture());
List<String> values = logCaptor.getAllValues();
assertThat(values, hasItem("Commit message: \"test commit\""));
}
/**
* Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1
* and tests for build data consistency.
* @param project project to build
* @param commit commit to build
* @param expectedBranch branch, that is expected to be built
* @param ordinal number of commit to log into errors, if any
* @param git git SCM
* @throws Exception on error
*/
private void notifyAndCheckBranch(FreeStyleProject project, ObjectId commit,
String expectedBranch, int ordinal, GitSCM git) throws Exception {
assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit));
final BuildData buildData = git.getBuildData(project.getLastBuild());
final Collection<Branch> builtBranches = buildData.lastBuild.getRevision().getBranches();
assertEquals("Commit " + ordinal + " should be built", commit, buildData
.getLastBuiltRevision().getSha1());
final String expectedBranchString = "origin/" + expectedBranch;
assertFalse("Branches should be detected for the build", builtBranches.isEmpty());
assertEquals(expectedBranch + " branch should be detected", expectedBranchString,
builtBranches.iterator().next().getName());
assertEquals(expectedBranchString, getEnvVars(project).get(GitSCM.GIT_BRANCH));
}
/**
* Method performs commit notification for the last committed SHA1 using
* notifyCommit URL.
* @param project project to trigger
* @return whether the new build has been triggered (<code>true</code>) or
* not (<code>false</code>).
* @throws Exception on error
*/
private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws Exception {
final int initialBuildNumber = project.getLastBuild().getNumber();
final String commit1 = ObjectId.toString(commitId);
final String notificationPath = rule.getURL().toExternalForm()
+ "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1;
final URL notifyUrl = new URL(notificationPath);
String notifyContent = null;
try (final InputStream is = notifyUrl.openStream()) {
notifyContent = IOUtils.toString(is, "UTF-8");
}
assertThat(notifyContent, containsString("No Git consumers using SCM API plugin for: " + testRepo.gitDir.toString()));
if ((project.getLastBuild().getNumber() == initialBuildNumber)
&& (rule.jenkins.getQueue().isEmpty())) {
return false;
} else {
while (!rule.jenkins.getQueue().isEmpty()) {
Thread.sleep(100);
}
final FreeStyleBuild build = project.getLastBuild();
while (build.isBuilding()) {
Thread.sleep(100);
}
return true;
}
}
private void setupJGit(GitSCM git) {
git.gitTool="jgit";
rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.<ToolProperty<?>>emptyList()));
}
/** We clean the environment, just in case the test is being run from a Jenkins job using this same plugin :). */
@TestExtension
public static class CleanEnvironment extends EnvironmentContributor {
@Override
public void buildEnvironmentFor(Run run, EnvVars envs, TaskListener listener) {
envs.remove(GitSCM.GIT_BRANCH);
envs.remove(GitSCM.GIT_LOCAL_BRANCH);
envs.remove(GitSCM.GIT_COMMIT);
envs.remove(GitSCM.GIT_PREVIOUS_COMMIT);
envs.remove(GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT);
}
}
/** Returns true if test cleanup is not reliable */
private boolean cleanupIsUnreliable() {
// Windows cleanup is unreliable on ci.jenkins.io
String jobUrl = System.getenv("JOB_URL");
return isWindows() && jobUrl != null && jobUrl.contains("ci.jenkins.io");
}
/** inline ${@link hudson.Functions#isWindows()} to prevent a transient remote classloader issue */
private boolean isWindows() {
return java.io.File.pathSeparatorChar==';';
}
} |
package com.gmail.nossr50.listeners;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerFishEvent.State;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.commands.general.XprateCommand;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.runnables.BleedTimer;
import com.gmail.nossr50.runnables.RemoveProfileFromMemoryTask;
import com.gmail.nossr50.spout.SpoutStuff;
import com.gmail.nossr50.datatypes.AbilityType;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.datatypes.SkillType;
import com.gmail.nossr50.events.chat.McMMOAdminChatEvent;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.Party;
import com.gmail.nossr50.skills.combat.Taming;
import com.gmail.nossr50.skills.gathering.BlastMining;
import com.gmail.nossr50.skills.gathering.Fishing;
import com.gmail.nossr50.skills.gathering.Herbalism;
import com.gmail.nossr50.util.BlockChecks;
import com.gmail.nossr50.util.Item;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.Skills;
import com.gmail.nossr50.util.Users;
public class PlayerListener implements Listener {
private final mcMMO plugin;
public PlayerListener(final mcMMO plugin) {
this.plugin = plugin;
}
/**
* Monitor PlayerChangedWorld events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerWorldChangeEvent(PlayerChangedWorldEvent event) {
Player player = event.getPlayer();
PlayerProfile PP = Users.getProfile(player);
if (PP.getGodMode()) {
if (!Permissions.getInstance().mcgod(player)) {
PP.toggleGodMode();
player.sendMessage(LocaleLoader.getString("Commands.GodMode.Forbidden"));
}
}
if (PP.inParty()) {
if (!Permissions.getInstance().party(player)) {
PP.removeParty();
player.sendMessage(LocaleLoader.getString("Party.Forbidden"));
}
}
}
/**
* Monitor PlayerFish events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerFish(PlayerFishEvent event) {
Player player = event.getPlayer();
if (Permissions.getInstance().fishing(player)) {
State state = event.getState();
switch (state) {
case CAUGHT_FISH:
Fishing.processResults(event);
break;
case CAUGHT_ENTITY:
if (Users.getProfile(player).getSkillLevel(SkillType.FISHING) >= 150 && Permissions.getInstance().shakeMob(player)) {
Fishing.shakeMob(event);
}
break;
default:
break;
}
}
}
/**
* Monitor PlaterPickupItem events.
*
* @param event The event to watch
*/
@EventHandler(ignoreCancelled = true)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if (Users.getProfile(event.getPlayer()).getAbilityMode(AbilityType.BERSERK)) {
event.setCancelled(true);
}
}
/**
* Monitor PlayerLogin events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Users.addUser(event.getPlayer());
}
/**
* Monitor PlayerQuit events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
/* GARBAGE COLLECTION */
//Remove Spout Stuff
if (plugin.spoutEnabled && SpoutStuff.playerHUDs.containsKey(player)) {
SpoutStuff.playerHUDs.remove(player);
}
//Bleed it out
BleedTimer.bleedOut(player);
//Schedule PlayerProfile removal 2 minutes after quitting
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RemoveProfileFromMemoryTask(player.getName()), 2400);
}
/**
* Monitor PlayerJoin events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (Config.getInstance().getMOTDEnabled() && Permissions.getInstance().motd(player)) {
String prefix = ChatColor.GOLD+"[mcMMO] ";
String perkPrefix = ChatColor.RED+"[mcMMO Perks] ";
player.sendMessage(prefix+ChatColor.YELLOW+"Running version " + ChatColor.DARK_AQUA + plugin.getDescription().getVersion()); //TODO: Locale
if(Config.getInstance().getHardcoreEnabled()) {
if(Config.getInstance().getHardcoreVampirismEnabled()) {
player.sendMessage(prefix+ChatColor.DARK_RED+"Hardcore & Vampirism enabled.");
player.sendMessage(prefix+ChatColor.DARK_AQUA+"Skill Death Penalty: "+ChatColor.DARK_RED+Config.getInstance().getHardcoreDeathStatPenaltyPercentage()+"% "+ChatColor.DARK_AQUA+"Vampirism Stat Leech: "+ChatColor.DARK_RED+Config.getInstance().getHardcoreVampirismStatLeechPercentage()+"%");
} else {
player.sendMessage(prefix+ChatColor.DARK_RED+"Hardcore enabled.");
player.sendMessage(prefix+ChatColor.DARK_AQUA+"Skill Death Penalty: "+ChatColor.DARK_RED+Config.getInstance().getHardcoreDeathStatPenaltyPercentage()+"%");
}
}
if(player.hasPermission("mcmmo.perks.xp.quadruple")) {
player.sendMessage(perkPrefix+ChatColor.DARK_AQUA+"Quadruple XP - Receive 4x XP.");
} else if (player.hasPermission("mcmmo.perks.xp.triple")) {
player.sendMessage(perkPrefix+ChatColor.DARK_AQUA+"Triple XP - Receive 3x XP.");
} else if (player.hasPermission("mcmmo.perks.xp.double")) {
player.sendMessage(perkPrefix+ChatColor.DARK_AQUA+"Double XP - Receive 2x XP.");
}
player.sendMessage(ChatColor.GOLD+"[mcMMO] "+ChatColor.GREEN+ "http:
//player.sendMessage(LocaleLoader.getString("mcMMO.MOTD", new Object[] {plugin.getDescription().getVersion()}));
//player.sendMessage(LocaleLoader.getString("mcMMO.Website"));
}
//THIS IS VERY BAD WAY TO DO THINGS, NEED BETTER WAY
if (XprateCommand.xpevent) {
player.sendMessage(LocaleLoader.getString("XPRate.Event", new Object[] {Config.getInstance().xpGainMultiplier}));
}
}
/**
* Monitor PlayerInteract events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.LOW)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action action = event.getAction();
Block block = event.getClickedBlock();
ItemStack inHand = player.getItemInHand();
Material material;
/* Fix for NPE on interacting with air */
if (block == null) {
material = Material.AIR;
}
else {
material = block.getType();
}
switch (action) {
case RIGHT_CLICK_BLOCK:
/* REPAIR CHECKS */
if (Permissions.getInstance().repair(player) && block.getTypeId() == Config.getInstance().getRepairAnvilId()) {
if (mcMMO.repairManager.isRepairable(inHand)) {
mcMMO.repairManager.handleRepair(player, inHand);
event.setCancelled(true);
player.updateInventory();
}
}
/* ACTIVATION CHECKS */
if (Config.getInstance().getAbilitiesEnabled() && BlockChecks.abilityBlockCheck(block)) {
if (!material.equals(Material.DIRT) && !material.equals(Material.GRASS) && !material.equals(Material.SOIL)) {
Skills.activationCheck(player, SkillType.HERBALISM);
}
Skills.activationCheck(player, SkillType.AXES);
Skills.activationCheck(player, SkillType.EXCAVATION);
Skills.activationCheck(player, SkillType.MINING);
Skills.activationCheck(player, SkillType.SWORDS);
Skills.activationCheck(player, SkillType.UNARMED);
Skills.activationCheck(player, SkillType.WOODCUTTING);
}
/* GREEN THUMB CHECK */
if (inHand.getType().equals(Material.SEEDS) && BlockChecks.makeMossy(block) && Permissions.getInstance().greenThumbBlocks(player)) {
Herbalism.greenThumbBlocks(inHand, player, block);
}
/* ITEM CHECKS */
if (BlockChecks.abilityBlockCheck(block)) {
Item.itemChecks(player);
}
/* BLAST MINING CHECK */
if (player.isSneaking() && inHand.getTypeId() == Config.getInstance().getDetonatorItemID() && Permissions.getInstance().blastMining(player)) {
BlastMining.detonate(event, player, plugin);
}
break;
case RIGHT_CLICK_AIR:
/* ACTIVATION CHECKS */
if (Config.getInstance().getAbilitiesEnabled()) {
Skills.activationCheck(player, SkillType.AXES);
Skills.activationCheck(player, SkillType.EXCAVATION);
Skills.activationCheck(player, SkillType.HERBALISM);
Skills.activationCheck(player, SkillType.MINING);
Skills.activationCheck(player, SkillType.SWORDS);
Skills.activationCheck(player, SkillType.UNARMED);
Skills.activationCheck(player, SkillType.WOODCUTTING);
}
/* ITEM CHECKS */
Item.itemChecks(player);
/* BLAST MINING CHECK */
if (player.isSneaking() && inHand.getTypeId() == Config.getInstance().getDetonatorItemID() && Permissions.getInstance().blastMining(player)) {
BlastMining.detonate(event, player, plugin);
}
break;
case LEFT_CLICK_AIR:
case LEFT_CLICK_BLOCK:
/* CALL OF THE WILD CHECKS */
if (player.isSneaking() && Permissions.getInstance().taming(player)) {
if (inHand.getType().equals(Material.RAW_FISH)) {
Taming.animalSummon(EntityType.OCELOT, player, plugin);
}
else if (inHand.getType().equals(Material.BONE)) {
Taming.animalSummon(EntityType.WOLF, player, plugin);
}
}
break;
default:
break;
}
}
/**
* Monitor PlayerChat events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerChat(PlayerChatEvent event) {
Player player = event.getPlayer();
PlayerProfile PP = Users.getProfile(player);
if (PP.getPartyChatMode()) {
if (!PP.inParty()) {
player.sendMessage("You're not in a party, type /p to leave party chat mode."); //TODO: Use mcLocale
return;
}
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(player.getName(), PP.getParty(), event.getMessage());
plugin.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return;
}
String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + player.getName() + ChatColor.GREEN + ") ";
plugin.getLogger().info("[P](" + PP.getParty() + ")" + "<" + player.getName() + "> " + chatEvent.getMessage());
for (Player p : Party.getInstance().getOnlineMembers(PP.getParty())) {
p.sendMessage(prefix + chatEvent.getMessage());
}
event.setCancelled(true);
}
else if (PP.getAdminChatMode()) {
McMMOAdminChatEvent chatEvent = new McMMOAdminChatEvent(player.getName(), event.getMessage());
plugin.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return;
}
String prefix = ChatColor.AQUA + "{" + ChatColor.WHITE + player.getName() + ChatColor.AQUA + "} ";
plugin.getLogger().info("[A]<" + player.getName() + "> " + chatEvent.getMessage());
for (Player p : plugin.getServer().getOnlinePlayers()) {
if (Permissions.getInstance().adminChat(player) || player.isOp()) {
p.sendMessage(prefix + chatEvent.getMessage());
}
}
}
}
/**
* Monitor PlayerCommandPreprocess events.
*
* @param event The event to watch
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
String message = event.getMessage();
String command = message.substring(1).split(" ")[0];
String lowerCaseCommand = command.toLowerCase();
if (plugin.aliasMap.containsKey(lowerCaseCommand)) {
//We should find a better way to avoid string replacement where the alias is equals to the command
if (command.equals(plugin.aliasMap.get(lowerCaseCommand))) {
return;
}
event.setMessage(message.replace(command, plugin.aliasMap.get(lowerCaseCommand)));
}
}
} |
package jlibs.xml.sax.dog;
import jlibs.xml.sax.helpers.NamespaceSupportReader;
import jlibs.xml.sax.helpers.SAXHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPathConstants;
import java.io.CharArrayWriter;
import java.io.File;
import java.util.*;
/**
* @author Santhosh Kumar T
*/
public class TestSuite{
public List<TestCase> testCases = new ArrayList<TestCase>();
public int total;
public TestSuite() throws Exception{
this("../resources/xpaths.xml");
}
public TestSuite(String configFile) throws Exception{
readTestCases(configFile);
}
public long usingJDK() throws Exception{
long time;
System.out.format("%6s: ", TestCase.domEngine.getName());
time = System.nanoTime();
for(TestCase testCase: testCases){
testCase.jdkResult = testCase.usingDOM();
System.out.print('.');
testCase.jdkResult = null;
}
long jdkTime = System.nanoTime() - time;
System.out.println("Done");
return jdkTime;
}
public long usingXMLDog() throws Exception{
System.out.format("%6s: ", "XMLDog");
long time = System.nanoTime();
for(TestCase testCase: testCases){
testCase.dogResult = testCase.usingXMLDog();
System.out.print('.');
testCase.dogResult = null;
}
long dogTime = System.nanoTime() - time;
System.out.println("Done");
return dogTime;
}
private static HashMap<QName, List<String>> types = new HashMap<QName, List<String>>();
static{
List<String> list = new ArrayList<String>();
list.add("name(");
list.add("local-name(");
list.add("namespace-uri(");
list.add("string(");
list.add("substring(");
list.add("substring-after(");
list.add("substring-before(");
list.add("normalize-space(");
list.add("concat(");
list.add("translate(");
list.add("upper-case(");
list.add("lower-case(");
types.put(XPathConstants.STRING, list);
list = new ArrayList<String>();
list.add("number(");
list.add("sum(");
list.add("count(");
list.add("string-length(");
types.put(XPathConstants.NUMBER, list);
list = new ArrayList<String>();
list.add("boolean(");
list.add("true(");
list.add("false(");
list.add("not(");
list.add("contains(");
list.add("starts-with(");
list.add("ends-with(");
types.put(XPathConstants.BOOLEAN, list);
}
private QName getResultType(String xpath){
for(Map.Entry<QName, List<String>> entry: types.entrySet()){
for(String str: entry.getValue()){
if(xpath.startsWith(str))
return entry.getKey();
}
}
return XPathConstants.NODESET;
}
public void readTestCases(final String configFile) throws Exception{
new NamespaceSupportReader(true).parse(configFile, new SAXHandler(){
boolean generateNewXPathsGlobal = true;
boolean generateNewXPathsCurrent = true;
TestCase testCase;
CharArrayWriter contents = new CharArrayWriter();
QName variableName;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
if(localName.equals("xpaths")){
String value = attributes.getValue("generate");
if(value!=null)
generateNewXPathsGlobal = Boolean.valueOf(value);
}else if(localName.equals("testcase")){
testCases.add(testCase = new TestCase());
Enumeration<String> enumer = nsSupport.getPrefixes();
while(enumer.hasMoreElements()){
String prefix = enumer.nextElement();
testCase.nsContext.declarePrefix(prefix, nsSupport.getURI(prefix));
}
if(nsSupport.getURI("")!=null)
testCase.nsContext.declarePrefix("", nsSupport.getURI(""));
}else if(localName.equals("xpath")){
String type = attributes.getValue("type");
if(type!=null){
if(type.equals("nodeset"))
testCase.resultTypes.add(XPathConstants.NODESET);
else if(type.equals("string"))
testCase.resultTypes.add(XPathConstants.STRING);
else if(type.equals("number"))
testCase.resultTypes.add(XPathConstants.NUMBER);
else if(type.equals("boolean"))
testCase.resultTypes.add(XPathConstants.BOOLEAN);
}
String value = attributes.getValue("generate");
generateNewXPathsCurrent = value!=null ? Boolean.valueOf(value) : generateNewXPathsGlobal;
}else if(localName.equals("variable"))
variableName = testCase.nsContext.toQName(attributes.getValue("name"));
contents.reset();
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException{
contents.write(ch, start, length);
}
private ArrayList<String> files = new ArrayList<String>();
@Override
public void endElement(String uri, String localName, String qName) throws SAXException{
if(localName.equals("file")){
File f = new File(contents.toString().trim());
if(!f.isAbsolute())
f = new File(new File(configFile).getParentFile(), f.getPath());
String file = f.getPath();
if(testCase.file==null){
testCase.file = file;
}else
files.add(file);
}else if(localName.equals("xpath")){
String xpath = contents.toString().trim();
testCase.xpaths.add(xpath);
if(testCase.resultTypes.size()!=testCase.xpaths.size())
testCase.resultTypes.add(getResultType(xpath));
if(generateNewXPathsGlobal && generateNewXPathsCurrent){
QName resultType = testCase.resultTypes.get(testCase.resultTypes.size()-1);
if(resultType.equals(XPathConstants.NODESET)){
if(xpath.indexOf("namespace::")==-1){
testCase.xpaths.add("name("+xpath+")");
testCase.resultTypes.add(XPathConstants.STRING);
testCase.xpaths.add("local-name("+xpath+")");
testCase.resultTypes.add(XPathConstants.STRING);
testCase.xpaths.add("namespace-uri("+xpath+")");
testCase.resultTypes.add(XPathConstants.STRING);
testCase.xpaths.add("string("+xpath+")");
testCase.resultTypes.add(XPathConstants.STRING);
testCase.xpaths.add(xpath+"[1]");
testCase.resultTypes.add(XPathConstants.NODESET);
testCase.xpaths.add(xpath+"[last()]");
testCase.resultTypes.add(XPathConstants.NODESET);
testCase.xpaths.add(xpath+"[position()>1 and position()<last()]");
testCase.resultTypes.add(XPathConstants.NODESET);
}
testCase.xpaths.add("count("+xpath+")");
testCase.resultTypes.add(XPathConstants.NUMBER);
testCase.xpaths.add("boolean("+xpath+")");
testCase.resultTypes.add(XPathConstants.BOOLEAN);
}
}
}else if(localName.equals("testcase")){
total += testCase.xpaths.size();
for(String file: files){
TestCase t = new TestCase();
t.file = file;
t.nsContext = testCase.nsContext;
t.xpaths = testCase.xpaths;
t.resultTypes = testCase.resultTypes;
testCases.add(t);
total += t.xpaths.size();
}
files.clear();
}else if(localName.equals("variable"))
testCase.variableResolver.defineVariable(variableName, contents.toString());
contents.reset();
}
});
}
} |
package hudson.plugins.git;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Launcher;
import hudson.matrix.Axis;
import hudson.matrix.AxisList;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
import hudson.model.*;
import hudson.plugins.git.GitSCM.BuildChooserContextImpl;
import hudson.plugins.git.GitSCM.DescriptorImpl;
import hudson.plugins.git.browser.GitRepositoryBrowser;
import hudson.plugins.git.browser.GithubWeb;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.impl.*;
import hudson.plugins.git.util.BuildChooserContext;
import hudson.plugins.git.util.BuildChooserContext.ContextCallable;
import hudson.plugins.git.util.BuildData;
import hudson.plugins.git.util.DefaultBuildChooser;
import hudson.plugins.git.util.GitUtils;
import hudson.plugins.parameterizedtrigger.BuildTrigger;
import hudson.plugins.parameterizedtrigger.ResultCondition;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogSet;
import hudson.scm.PollingResult;
import hudson.slaves.DumbSlave;
import hudson.slaves.EnvironmentVariablesNodeProperty.Entry;
import hudson.tools.ToolProperty;
import hudson.triggers.SCMTrigger;
import hudson.util.StreamTaskListener;
import java.io.ByteArrayOutputStream;
import jenkins.security.MasterToSlaveCallable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.jenkinsci.plugins.gitclient.*;
import org.junit.Test;
import org.jvnet.hudson.test.TestExtension;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.net.URL;
import java.util.*;
import org.eclipse.jgit.transport.RemoteConfig;
import static org.hamcrest.CoreMatchers.instanceOf;
import org.jvnet.hudson.test.Issue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.mockito.Mockito;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link GitSCM}.
* @author ishaaq
*/
public class GitSCMTest extends AbstractGitTestCase {
/**
* Basic test - create a GitSCM based project, check it out and build for the first time.
* Next test that polling works correctly, make another commit, check that polling finds it,
* then build it and finally test the build culprits as well as the contents of the workspace.
* @throws Exception if an exception gets thrown.
*/
@Test
public void testBasic() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBasicRemotePoll() throws Exception {
// FreeStyleProject project = setupProject("master", true, false);
FreeStyleProject project = setupProject("master", false, null, null, null, true, null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
// ... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBranchSpecWithRemotesMaster() throws Exception {
FreeStyleProject projectMasterBranch = setupProject("remotes/origin/master", false, null, null, null, true, null);
// create initial commit and build
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(projectMasterBranch, Result.SUCCESS, commitFile1);
}
@Test
public void testBranchSpecWithRemotesHierarchical() throws Exception {
FreeStyleProject projectMasterBranch = setupProject("master", false, null, null, null, true, null);
FreeStyleProject projectHierarchicalBranch = setupProject("remotes/origin/rel-1/xy", false, null, null, null, true, null);
// create initial commit
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
// create hierarchical branch, delete master branch, and build
git.branch("rel-1/xy");
git.checkout("rel-1/xy");
git.deleteBranch("master");
build(projectMasterBranch, Result.FAILURE);
build(projectHierarchicalBranch, Result.SUCCESS, commitFile1);
}
@Test
public void testBranchSpecUsingTagWithSlash() throws Exception {
FreeStyleProject projectMasterBranch = setupProject("path/tag", false, null, null, null, true, null);
// create initial commit and build
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1 will be tagged with path/tag");
testRepo.git.tag("path/tag", "tag with a slash in the tag name");
build(projectMasterBranch, Result.SUCCESS, commitFile1);
}
@Test
public void testBasicIncludedRegion() throws Exception {
FreeStyleProject project = setupProject("master", false, null, null, null, ".*3");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testIncludedRegionWithDeeperCommits() throws Exception {
FreeStyleProject project = setupProject("master", false, null, null, null, ".*3");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should not have been included", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
final String commitFile4 = "commitFile4";
commit(commitFile4, janeDoe, "Commit number 4");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBasicExcludedRegion() throws Exception {
FreeStyleProject project = setupProject("master", false, null, ".*2", null, null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testCleanBeforeCheckout() throws Exception {
FreeStyleProject p = setupProject("master", false, null, null, "Jane Doe", null);
((GitSCM)p.getScm()).getExtensions().add(new CleanBeforeCheckout());
final String commitFile1 = "commitFile1";
final String commitFile2 = "commitFile2";
commit(commitFile1, johnDoe, janeDoe, "Commit number 1");
commit(commitFile2, johnDoe, janeDoe, "Commit number 2");
final FreeStyleBuild firstBuild = build(p, Result.SUCCESS, commitFile1);
final String branch1 = "Branch1";
final String branch2 = "Branch2";
List<BranchSpec> branches = new ArrayList<BranchSpec>();
branches.add(new BranchSpec("master"));
branches.add(new BranchSpec(branch1));
branches.add(new BranchSpec(branch2));
git.branch(branch1);
git.checkout(branch1);
p.poll(listener).hasChanges();
assertTrue(firstBuild.getLog().contains("Cleaning"));
assertTrue(firstBuild.getLog().indexOf("Cleaning") > firstBuild.getLog().indexOf("Cloning")); //clean should be after clone
assertTrue(firstBuild.getLog().indexOf("Cleaning") < firstBuild.getLog().indexOf("Checking out")); //clean before checkout
assertTrue(firstBuild.getWorkspace().child(commitFile1).exists());
git.checkout(branch1);
final FreeStyleBuild secondBuild = build(p, Result.SUCCESS, commitFile2);
p.poll(listener).hasChanges();
assertTrue(secondBuild.getLog().contains("Cleaning"));
assertTrue(secondBuild.getLog().indexOf("Cleaning") < secondBuild.getLog().indexOf("Fetching upstream changes"));
assertTrue(secondBuild.getWorkspace().child(commitFile2).exists());
}
@Issue("JENKINS-8342")
@Test
public void testExcludedRegionMultiCommit() throws Exception {
// Got 2 projects, each one should only build if changes in its own file
FreeStyleProject clientProject = setupProject("master", false, null, ".*serverFile", null, null);
FreeStyleProject serverProject = setupProject("master", false, null, ".*clientFile", null, null);
String initialCommitFile = "initialFile";
commit(initialCommitFile, johnDoe, "initial commit");
build(clientProject, Result.SUCCESS, initialCommitFile);
build(serverProject, Result.SUCCESS, initialCommitFile);
assertFalse("scm polling should not detect any more changes after initial build", clientProject.poll(listener).hasChanges());
assertFalse("scm polling should not detect any more changes after initial build", serverProject.poll(listener).hasChanges());
// Got commits on serverFile, so only server project should build.
commit("myserverFile", johnDoe, "commit first server file");
assertFalse("scm polling should not detect any changes in client project", clientProject.poll(listener).hasChanges());
assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges());
// Got commits on both client and serverFile, so both projects should build.
commit("myNewserverFile", johnDoe, "commit new server file");
commit("myclientFile", johnDoe, "commit first clientfile");
assertTrue("scm polling did not detect changes in client project", clientProject.poll(listener).hasChanges());
assertTrue("scm polling did not detect changes in server project", serverProject.poll(listener).hasChanges());
}
/**
* With multiple branches specified in the project and having commits from a user
* excluded should not build the excluded revisions when another branch changes.
*/
/*
@Issue("JENKINS-8342")
@Test
public void testMultipleBranchWithExcludedUser() throws Exception {
final String branch1 = "Branch1";
final String branch2 = "Branch2";
List<BranchSpec> branches = new ArrayList<BranchSpec>();
branches.add(new BranchSpec("master"));
branches.add(new BranchSpec(branch1));
branches.add(new BranchSpec(branch2));
final FreeStyleProject project = setupProject(branches, false, null, null, janeDoe.getName(), null, false, null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// create branches here so we can get back to them later...
git.branch(branch1);
git.branch(branch2);
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1, commitFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
// Add excluded commit
final String commitFile4 = "commitFile4";
commit(commitFile4, janeDoe, "Commit number 4");
assertFalse("scm polling detected change in 'master', which should have been excluded", project.poll(listener).hasChanges());
// now jump back...
git.checkout(branch1);
final String branch1File1 = "branch1File1";
commit(branch1File1, janeDoe, "Branch1 commit number 1");
assertFalse("scm polling detected change in 'Branch1', which should have been excluded", project.poll(listener).hasChanges());
// and the other branch...
git.checkout(branch2);
final String branch2File1 = "branch2File1";
commit(branch2File1, janeDoe, "Branch2 commit number 1");
assertFalse("scm polling detected change in 'Branch2', which should have been excluded", project.poll(listener).hasChanges());
final String branch2File2 = "branch2File2";
commit(branch2File2, johnDoe, "Branch2 commit number 2");
assertTrue("scm polling should detect changes in 'Branch2' branch", project.poll(listener).hasChanges());
//... and build it...
build(project, Result.SUCCESS, branch2File1, branch2File2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// now jump back again...
git.checkout(branch1);
// Commit excluded after non-excluded commit, should trigger build.
final String branch1File2 = "branch1File2";
commit(branch1File2, johnDoe, "Branch1 commit number 2");
final String branch1File3 = "branch1File3";
commit(branch1File3, janeDoe, "Branch1 commit number 3");
assertTrue("scm polling should detect changes in 'Branch1' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, branch1File1, branch1File2, branch1File3);
} */
@Test
public void testBasicExcludedUser() throws Exception {
FreeStyleProject project = setupProject("master", false, null, null, "Jane Doe", null);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertFalse("scm polling detected commit2 change, which should have been excluded", project.poll(listener).hasChanges());
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling did not detect commit3 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2, commitFile3);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have two culprit", 2, culprits.size());
PersonIdent[] expected = {johnDoe, janeDoe};
assertCulprits("jane doe and john doe should be the culprits", culprits, expected);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertTrue(build2.getWorkspace().child(commitFile3).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBasicInSubdir() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
((GitSCM)project.getScm()).getExtensions().add(new RelativeTargetDirectory("subdir"));
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, "subdir", Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, "subdir", Result.SUCCESS,
commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertEquals("The workspace should have a 'subdir' subdirectory, but does not.", true,
build2.getWorkspace().child("subdir").exists());
assertEquals("The 'subdir' subdirectory should contain commitFile2, but does not.", true,
build2.getWorkspace().child("subdir").child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testBasicWithSlave() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
project.setAssignedLabel(rule.createSlave().getSelfLabel());
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Issue("HUDSON-7547")
@Test
public void testBasicWithSlaveNoExecutorsOnMaster() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
rule.jenkins.setNumExecutors(0);
project.setAssignedLabel(rule.createSlave().getSelfLabel());
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testAuthorOrCommitterFalse() throws Exception {
// Test with authorOrCommitter set to false and make sure we get the committer.
FreeStyleProject project = setupSimpleProject("master");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, janeDoe, "Commit number 1");
final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final Set<User> secondCulprits = secondBuild.getCulprits();
assertEquals("The build should have only one culprit", 1, secondCulprits.size());
assertEquals("Did not get the committer as the change author with authorOrCommiter==false",
janeDoe.getName(), secondCulprits.iterator().next().getFullName());
}
@Test
public void testAuthorOrCommitterTrue() throws Exception {
// Next, test with authorOrCommitter set to true and make sure we get the author.
FreeStyleProject project = setupSimpleProject("master");
((GitSCM)project.getScm()).getExtensions().add(new AuthorInChangelog());
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, janeDoe, "Commit number 1");
final FreeStyleBuild firstBuild = build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild secondBuild = build(project, Result.SUCCESS, commitFile2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final Set<User> secondCulprits = secondBuild.getCulprits();
assertEquals("The build should have only one culprit", 1, secondCulprits.size());
assertEquals("Did not get the author as the change author with authorOrCommiter==true",
johnDoe.getName(), secondCulprits.iterator().next().getFullName());
}
/**
* Method name is self-explanatory.
*/
@Test
public void testNewCommitToUntrackedBranchDoesNotTriggerBuild() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
//now create and checkout a new branch:
git.checkout(Constants.HEAD, "untracked");
//.. and commit to it:
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertFalse("scm polling should not detect commit2 change because it is not in the branch we are tracking.", project.poll(listener).hasChanges());
}
private String checkoutString(FreeStyleProject project, String envVar) {
return "checkout -f " + getEnvVars(project).get(envVar);
}
@Test
public void testEnvVarsAvailable() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
rule.assertLogContains(getEnvVars(project).get(GitSCM.GIT_BRANCH), build1);
rule.assertLogContains(checkoutString(project, GitSCM.GIT_COMMIT), build1);
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build2);
rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_COMMIT), build1);
rule.assertLogNotContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build2);
rule.assertLogContains(checkoutString(project, GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT), build1);
}
@Issue("HUDSON-7411")
@Test
public void testNodeEnvVarsAvailable() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
Node s = rule.createSlave();
setVariables(s, new Entry("TESTKEY", "slaveValue"));
project.setAssignedLabel(s.getSelfLabel());
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertEquals("slaveValue", getEnvVars(project).get("TESTKEY"));
}
/**
* A previous version of GitSCM would only build against branches, not tags. This test checks that that
* regression has been fixed.
*/
@Test
public void testGitSCMCanBuildAgainstTags() throws Exception {
final String mytag = "mytag";
FreeStyleProject project = setupSimpleProject(mytag);
build(project, Result.FAILURE); // fail, because there's nothing to be checked out here
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
// Try again. The first build will leave the repository in a bad state because we
// cloned something without even a HEAD - which will mean it will want to re-clone once there is some
// actual data.
build(project, Result.FAILURE); // fail, because there's nothing to be checked out here
//now create and checkout a new branch:
final String tmpBranch = "tmp";
git.branch(tmpBranch);
git.checkout(tmpBranch);
// commit to it
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges());
build(project, Result.FAILURE); // fail, because there's nothing to be checked out here
// tag it, then delete the tmp branch
git.tag(mytag, "mytag initial");
git.checkout("master");
git.deleteBranch(tmpBranch);
// at this point we're back on master, there are no other branches, tag "mytag" exists but is
// not part of "master"
assertTrue("scm polling should detect commit2 change in 'mytag'", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
// now, create tmp branch again against mytag:
git.checkout(mytag);
git.branch(tmpBranch);
// another commit:
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertFalse("scm polling should not detect any more changes since mytag is untouched right now", project.poll(listener).hasChanges());
// now we're going to force mytag to point to the new commit, if everything goes well, gitSCM should pick the change up:
git.tag(mytag, "mytag moved");
git.checkout("master");
git.deleteBranch(tmpBranch);
// at this point we're back on master, there are no other branches, "mytag" has been updated to a new commit:
assertTrue("scm polling should detect commit3 change in 'mytag'", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile3);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
}
/**
* Not specifying a branch string in the project implies that we should be polling for changes in
* all branches.
*/
@Test
public void testMultipleBranchBuild() throws Exception {
// empty string will result in a project that tracks against changes in all branches:
final FreeStyleProject project = setupSimpleProject("");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
// create a branch here so we can get back to this point later...
final String fork = "fork";
git.branch(fork);
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final String commitFile3 = "commitFile3";
commit(commitFile3, johnDoe, "Commit number 3");
assertTrue("scm polling should detect changes in 'master' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1, commitFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
// now jump back...
git.checkout(fork);
// add some commits to the fork branch...
final String forkFile1 = "forkFile1";
commit(forkFile1, johnDoe, "Fork commit number 1");
final String forkFile2 = "forkFile2";
commit(forkFile2, johnDoe, "Fork commit number 2");
assertTrue("scm polling should detect changes in 'fork' branch", project.poll(listener).hasChanges());
build(project, Result.SUCCESS, forkFile1, forkFile2);
assertFalse("scm polling should not detect any more changes after last build", project.poll(listener).hasChanges());
}
@Issue("JENKINS-19037")
@SuppressWarnings("ResultOfObjectAllocationIgnored")
@Test
public void testBlankRepositoryName() throws Exception {
new GitSCM(null);
}
@Issue("JENKINS-10060")
@Test
public void testSubmoduleFixup() throws Exception {
File repo = tempFolder.newFolder();
FilePath moduleWs = new FilePath(repo);
org.jenkinsci.plugins.gitclient.GitClient moduleRepo = Git.with(listener, new EnvVars()).in(repo).getClient();
{// first we create a Git repository with submodule
moduleRepo.init();
moduleWs.child("a").touch(0);
moduleRepo.add("a");
moduleRepo.commit("creating a module");
git.addSubmodule(repo.getAbsolutePath(), "module1");
git.commit("creating a super project");
}
// configure two uproject 'u' -> 'd' that's chained together.
FreeStyleProject u = createFreeStyleProject();
FreeStyleProject d = createFreeStyleProject();
u.setScm(new GitSCM(workDir.getPath()));
u.getPublishersList().add(new BuildTrigger(new hudson.plugins.parameterizedtrigger.BuildTriggerConfig(d.getName(), ResultCondition.SUCCESS,
new GitRevisionBuildParameters())));
d.setScm(new GitSCM(workDir.getPath()));
rule.jenkins.rebuildDependencyGraph();
FreeStyleBuild ub = rule.assertBuildStatusSuccess(u.scheduleBuild2(0));
System.out.println(ub.getLog());
for (int i=0; (d.getLastBuild()==null || d.getLastBuild().isBuilding()) && i<100; i++) // wait only up to 10 sec to avoid infinite loop
Thread.sleep(100);
FreeStyleBuild db = d.getLastBuild();
assertNotNull("downstream build didn't happen",db);
rule.assertBuildStatusSuccess(db);
}
@Test
public void testBuildChooserContext() throws Exception {
final FreeStyleProject p = createFreeStyleProject();
final FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0));
BuildChooserContextImpl c = new BuildChooserContextImpl(p, b, null);
c.actOnBuild(new ContextCallable<Run<?,?>, Object>() {
public Object invoke(Run param, VirtualChannel channel) throws IOException, InterruptedException {
assertSame(param,b);
return null;
}
});
c.actOnProject(new ContextCallable<Job<?,?>, Object>() {
public Object invoke(Job param, VirtualChannel channel) throws IOException, InterruptedException {
assertSame(param,p);
return null;
}
});
DumbSlave s = rule.createOnlineSlave();
assertEquals(p.toString(), s.getChannel().call(new BuildChooserContextTestCallable(c)));
}
private static class BuildChooserContextTestCallable extends MasterToSlaveCallable<String,IOException> {
private final BuildChooserContext c;
public BuildChooserContextTestCallable(BuildChooserContext c) {
this.c = c;
}
public String call() throws IOException {
try {
return c.actOnProject(new ContextCallable<Job<?,?>, String>() {
public String invoke(Job<?,?> param, VirtualChannel channel) throws IOException, InterruptedException {
assertTrue(channel instanceof Channel);
assertTrue(Hudson.getInstance()!=null);
return param.toString();
}
});
} catch (InterruptedException e) {
throw new IOException(e);
}
}
}
// eg: "jane doe and john doe should be the culprits", culprits, [johnDoe, janeDoe])
static public void assertCulprits(String assertMsg, Set<User> actual, PersonIdent[] expected)
{
Collection<String> fullNames = Collections2.transform(actual, new Function<User,String>() {
public String apply(User u)
{
return u.getFullName();
}
});
for(PersonIdent p : expected)
{
assertTrue(assertMsg, fullNames.contains(p.getName()));
}
}
@Test
public void testEmailCommitter() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// setup global config
final DescriptorImpl descriptor = (DescriptorImpl) project.getScm().getDescriptor();
descriptor.setCreateAccountBasedOnEmail(true);
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
final PersonIdent jeffDoe = new PersonIdent("Jeff Doe", "jeff@doe.com");
commit(commitFile2, jeffDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
final Set<User> culprits = build2.getCulprits();
assertEquals("The build should have only one culprit", 1, culprits.size());
User culprit = culprits.iterator().next();
assertEquals("", jeffDoe.getEmailAddress(), culprit.getId());
assertEquals("", jeffDoe.getName(), culprit.getFullName());
rule.assertBuildStatusSuccess(build);
}
@Test
public void testFetchFromMultipleRepositories() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
TestGitRepo secondTestRepo = new TestGitRepo("second", tempFolder.newFolder(), listener);
List<UserRemoteConfig> remotes = new ArrayList<UserRemoteConfig>();
remotes.addAll(testRepo.remoteConfigs());
remotes.addAll(secondTestRepo.remoteConfigs());
project.setScm(new GitSCM(
remotes,
Collections.singletonList(new BranchSpec("master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList()));
// create initial commit and then run the build against it:
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
build(project, Result.SUCCESS, commitFile1);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
final String commitFile2 = "commitFile2";
secondTestRepo.commit(commitFile2, janeDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
//... and build it...
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Issue("JENKINS-26268")
public void testBranchSpecAsSHA1WithMultipleRepositories() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
TestGitRepo secondTestRepo = new TestGitRepo("second", tempFolder.newFolder(), listener);
List<UserRemoteConfig> remotes = new ArrayList<UserRemoteConfig>();
remotes.addAll(testRepo.remoteConfigs());
remotes.addAll(secondTestRepo.remoteConfigs());
// create initial commit
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
String sha1 = testRepo.git.revParse("HEAD").getName();
project.setScm(new GitSCM(
remotes,
Collections.singletonList(new BranchSpec(sha1)),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList()));
final FreeStyleBuild build = build(project, Result.SUCCESS, commitFile1);
rule.assertBuildStatusSuccess(build);
}
@Issue("JENKINS-25639")
@Test
public void testCommitDetectedOnlyOnceInMultipleRepositories() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
TestGitRepo secondTestRepo = new TestGitRepo("secondRepo", tempFolder.newFolder(), listener);
List<UserRemoteConfig> remotes = new ArrayList<UserRemoteConfig>();
remotes.addAll(testRepo.remoteConfigs());
remotes.addAll(secondTestRepo.remoteConfigs());
GitSCM gitSCM = new GitSCM(
remotes,
Collections.singletonList(new BranchSpec("origin/master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(gitSCM);
commit("commitFile1", johnDoe, "Commit number 1");
FreeStyleBuild build = build(project, Result.SUCCESS, "commitFile1");
commit("commitFile2", johnDoe, "Commit number 2");
git = Git.with(listener, new EnvVars()).in(build.getWorkspace()).getClient();
for (RemoteConfig remoteConfig : gitSCM.getRepositories()) {
git.fetch_().from(remoteConfig.getURIs().get(0), remoteConfig.getFetchRefSpecs());
}
Collection<Revision> candidateRevisions = ((DefaultBuildChooser) (gitSCM).getBuildChooser()).getCandidateRevisions(false, "origin/master", git, listener, project.getLastBuild().getAction(BuildData.class), null);
assertEquals(1, candidateRevisions.size());
}
@Test
public void testMerge() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF)));
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Issue("JENKINS-20392")
@Test
public void testMergeChangelog() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "default", MergeCommand.GitPluginFastForwardMode.FF)));
project.setScm(scm);
// create initial commit and then run the build against it:
// Here the changelog is by default empty (because changelog for first commit is always empty
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
// Create second commit and run build
// Here the changelog should contain exactly this one new commit
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
String commitMessage = "Commit number 2";
commit(commitFile2, johnDoe, commitMessage);
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
ChangeLogSet<? extends ChangeLogSet.Entry> changeLog = build2.getChangeSet();
assertEquals("Changelog should contain one item", 1, changeLog.getItems().length);
GitChangeSet singleChange = (GitChangeSet) changeLog.getItems()[0];
assertEquals("Changelog should contain commit number 2", commitMessage, singleChange.getComment().trim());
}
@Test
public void testMergeWithSlave() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
project.setAssignedLabel(rule.createSlave().getSelfLabel());
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null)));
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testMergeFailed() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", "", MergeCommand.GitPluginFastForwardMode.FF)));
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
commit(commitFile1, "other content", johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.FAILURE);
rule.assertBuildStatus(Result.FAILURE, build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Issue("JENKINS-25191")
@Test
public void testMultipleMergeFailed() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("master")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration1", "", MergeCommand.GitPluginFastForwardMode.FF)));
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration2", "", MergeCommand.GitPluginFastForwardMode.FF)));
commit("dummyFile", johnDoe, "Initial Commit");
testRepo.git.branch("integration1");
testRepo.git.branch("integration2");
build(project, Result.SUCCESS);
final String commitFile = "commitFile";
testRepo.git.checkoutBranch("integration1","master");
commit(commitFile,"abc", johnDoe, "merge conflict with integration2");
testRepo.git.checkoutBranch("integration2","master");
commit(commitFile,"cde", johnDoe, "merge conflict with integration1");
final FreeStyleBuild build = build(project, Result.FAILURE);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testMergeFailedWithSlave() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
project.setAssignedLabel(rule.createSlave().getSelfLabel());
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null)));
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
commit(commitFile1, "other content", johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final FreeStyleBuild build2 = build(project, Result.FAILURE);
rule.assertBuildStatus(Result.FAILURE, build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testMergeWithMatrixBuild() throws Exception {
//Create a matrix project and a couple of axes
MatrixProject project = rule.jenkins.createProject(MatrixProject.class, "xyz");
project.setAxes(new AxisList(new Axis("VAR","a","b")));
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("*")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null)));
project.setScm(scm);
// create initial commit and then run the build against it:
commit("commitFileBase", johnDoe, "Initial Commit");
testRepo.git.branch("integration");
build(project, Result.SUCCESS, "commitFileBase");
testRepo.git.checkout(null, "topic1");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final MatrixBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
// do what the GitPublisher would do
testRepo.git.deleteBranch("integration");
testRepo.git.checkout("topic1", "integration");
testRepo.git.checkout("master", "topic2");
final String commitFile2 = "commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
assertTrue("scm polling did not detect commit2 change", project.poll(listener).hasChanges());
final MatrixBuild build2 = build(project, Result.SUCCESS, commitFile2);
assertTrue(build2.getWorkspace().child(commitFile2).exists());
rule.assertBuildStatusSuccess(build2);
assertFalse("scm polling should not detect any more changes after build", project.poll(listener).hasChanges());
}
@Test
public void testEnvironmentVariableExpansion() throws Exception {
FreeStyleProject project = createFreeStyleProject();
project.setScm(new GitSCM("${CAT}"+testRepo.gitDir.getPath()));
// create initial commit and then run the build against it:
commit("a.txt", johnDoe, "Initial Commit");
build(project, Result.SUCCESS, "a.txt");
PollingResult r = project.poll(StreamTaskListener.fromStdout());
assertFalse(r.hasChanges());
commit("b.txt", johnDoe, "Another commit");
r = project.poll(StreamTaskListener.fromStdout());
assertTrue(r.hasChanges());
build(project, Result.SUCCESS, "b.txt");
}
@TestExtension("testEnvironmentVariableExpansion")
public static class SupplySomeEnvVars extends EnvironmentContributor {
@Override
public void buildEnvironmentFor(Run r, EnvVars envs, TaskListener listener) throws IOException, InterruptedException {
envs.put("CAT","");
}
}
private List<UserRemoteConfig> createRepoList(String url) {
List<UserRemoteConfig> repoList = new ArrayList<UserRemoteConfig>();
repoList.add(new UserRemoteConfig(url, null, null, null));
return repoList;
}
/**
* Makes sure that git browser URL is preserved across config round trip.
*/
@Issue("JENKINS-22604")
@Test
public void testConfigRoundtripURLPreserved() throws Exception {
FreeStyleProject p = createFreeStyleProject();
final String url = "https://github.com/jenkinsci/jenkins";
GitRepositoryBrowser browser = new GithubWeb(url);
GitSCM scm = new GitSCM(createRepoList(url),
Collections.singletonList(new BranchSpec("")),
false, Collections.<SubmoduleConfig>emptyList(),
browser, null, null);
p.setScm(scm);
rule.configRoundtrip(p);
rule.assertEqualDataBoundBeans(scm,p.getScm());
assertEquals("Wrong key", "git " + url, scm.getKey());
}
/**
* Makes sure that git extensions are preserved across config round trip.
*/
@Issue("JENKINS-33695")
@Test
public void testConfigRoundtripExtensionsPreserved() throws Exception {
FreeStyleProject p = createFreeStyleProject();
final String url = "git://github.com/jenkinsci/git-plugin.git";
GitRepositoryBrowser browser = new GithubWeb(url);
GitSCM scm = new GitSCM(createRepoList(url),
Collections.singletonList(new BranchSpec("*/master")),
false, Collections.<SubmoduleConfig>emptyList(),
browser, null, null);
p.setScm(scm);
/* Assert that no extensions are loaded initially */
assertEquals(Collections.emptyList(), scm.getExtensions().toList());
/* Add LocalBranch extension */
LocalBranch localBranchExtension = new LocalBranch("**");
scm.getExtensions().add(localBranchExtension);
assertTrue(scm.getExtensions().toList().contains(localBranchExtension));
/* Save the configuration */
rule.configRoundtrip(p);
List<GitSCMExtension> extensions = scm.getExtensions().toList();;
assertTrue(extensions.contains(localBranchExtension));
assertEquals("Wrong extension count before reload", 1, extensions.size());
/* Reload configuration from disc */
p.doReload();
GitSCM reloadedGit = (GitSCM) p.getScm();
List<GitSCMExtension> reloadedExtensions = reloadedGit.getExtensions().toList();
assertEquals("Wrong extension count after reload", 1, reloadedExtensions.size());
LocalBranch reloadedLocalBranch = (LocalBranch) reloadedExtensions.get(0);
assertEquals(localBranchExtension.getLocalBranch(), reloadedLocalBranch.getLocalBranch());
}
/**
* Makes sure that the configuration form works.
*/
@Test
public void testConfigRoundtrip() throws Exception {
FreeStyleProject p = createFreeStyleProject();
GitSCM scm = new GitSCM("https://github.com/jenkinsci/jenkins");
p.setScm(scm);
rule.configRoundtrip(p);
rule.assertEqualDataBoundBeans(scm,p.getScm());
}
/**
* Sample configuration that should result in no extensions at all
*/
@Test
public void testDataCompatibility1() throws Exception {
FreeStyleProject p = (FreeStyleProject) rule.jenkins.createProjectFromXML("foo", getClass().getResourceAsStream("GitSCMTest/old1.xml"));
GitSCM oldGit = (GitSCM) p.getScm();
assertEquals(Collections.emptyList(), oldGit.getExtensions().toList());
assertEquals(0, oldGit.getSubmoduleCfg().size());
assertEquals("git git://github.com/jenkinsci/model-ant-project.git", oldGit.getKey());
assertThat(oldGit.getEffectiveBrowser(), instanceOf(GithubWeb.class));
GithubWeb browser = (GithubWeb) oldGit.getEffectiveBrowser();
assertEquals(browser.getRepoUrl(), "https://github.com/jenkinsci/model-ant-project.git/");
}
@Test
public void testPleaseDontContinueAnyway() throws Exception {
// create an empty repository with some commits
testRepo.commit("a","foo",johnDoe, "added");
FreeStyleProject p = createFreeStyleProject();
p.setScm(new GitSCM(testRepo.gitDir.getAbsolutePath()));
rule.assertBuildStatusSuccess(p.scheduleBuild2(0));
// this should fail as it fails to fetch
p.setScm(new GitSCM("http://localhost:4321/no/such/repository.git"));
rule.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
}
@Issue("JENKINS-19108")
@Test
public void testCheckoutToSpecificBranch() throws Exception {
FreeStyleProject p = createFreeStyleProject();
GitSCM oldGit = new GitSCM("https://github.com/jenkinsci/model-ant-project.git/");
setupJGit(oldGit);
oldGit.getExtensions().add(new LocalBranch("master"));
p.setScm(oldGit);
FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0));
GitClient gc = Git.with(StreamTaskListener.fromStdout(),null).in(b.getWorkspace()).getClient();
gc.withRepository(new RepositoryCallback<Void>() {
public Void invoke(Repository repo, VirtualChannel channel) throws IOException, InterruptedException {
Ref head = repo.getRef("HEAD");
assertTrue("Detached HEAD",head.isSymbolic());
Ref t = head.getTarget();
assertEquals(t.getName(),"refs/heads/master");
return null;
}
});
}
/**
* Verifies that if project specifies LocalBranch with value of "**"
* that the checkout to a local branch using remote branch name sans 'origin'.
* This feature is necessary to support Maven release builds that push updated
* pom.xml to remote branch as
* <br/>
* <pre>
* git push origin localbranch:localbranch
* </pre>
* @throws Exception
*/
@Test
public void testCheckoutToDefaultLocalBranch_StarStar() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
GitSCM git = (GitSCM)project.getScm();
git.getExtensions().add(new LocalBranch("**"));
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH));
}
/**
* Verifies that if project specifies LocalBranch with null value (empty string)
* that the checkout to a local branch using remote branch name sans 'origin'.
* This feature is necessary to support Maven release builds that push updated
* pom.xml to remote branch as
* <br/>
* <pre>
* git push origin localbranch:localbranch
* </pre>
* @throws Exception
*/
@Test
public void testCheckoutToDefaultLocalBranch_NULL() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
GitSCM git = (GitSCM)project.getScm();
git.getExtensions().add(new LocalBranch(""));
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
assertEquals("GIT_LOCAL_BRANCH", "master", getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH));
}
/**
* Verifies that GIT_LOCAL_BRANCH is not set if LocalBranch extension
* is not configured.
* @throws Exception
*/
@Test
public void testCheckoutSansLocalBranchExtension() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
assertEquals("GIT_BRANCH", "origin/master", getEnvVars(project).get(GitSCM.GIT_BRANCH));
assertEquals("GIT_LOCAL_BRANCH", null, getEnvVars(project).get(GitSCM.GIT_LOCAL_BRANCH));
}
@Test
public void testCheckoutFailureIsRetryable() throws Exception {
FreeStyleProject project = setupSimpleProject("master");
// run build first to create workspace
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
final String commitFile2 = "commitFile2";
commit(commitFile2, janeDoe, "Commit number 2");
// create lock file to simulate lock collision
File lock = new File(build1.getWorkspace().toString(), ".git/index.lock");
try {
FileUtils.touch(lock);
final FreeStyleBuild build2 = build(project, Result.FAILURE);
rule.assertLogContains("java.io.IOException: Could not checkout", build2);
} finally {
lock.delete();
}
}
@Test
public void testInitSparseCheckout() throws Exception {
if (!gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("toto")));
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("toto").exists());
assertTrue(build1.getWorkspace().child(commitFile1).exists());
assertFalse(build1.getWorkspace().child("titi").exists());
assertFalse(build1.getWorkspace().child(commitFile2).exists());
}
@Test
public void testInitSparseCheckoutBis() throws Exception {
if (!gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi")));
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertFalse(build1.getWorkspace().child("toto").exists());
assertFalse(build1.getWorkspace().child(commitFile1).exists());
}
@Test
public void testSparseCheckoutAfterNormalCheckout() throws Exception {
if (!gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupSimpleProject("master");
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertTrue(build1.getWorkspace().child("toto").exists());
assertTrue(build1.getWorkspace().child(commitFile1).exists());
((GitSCM) project.getScm()).getExtensions().add(new SparseCheckoutPaths(Lists.newArrayList(new SparseCheckoutPath("titi"))));
final FreeStyleBuild build2 = build(project, Result.SUCCESS);
assertTrue(build2.getWorkspace().child("titi").exists());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertFalse(build2.getWorkspace().child("toto").exists());
assertFalse(build2.getWorkspace().child(commitFile1).exists());
}
@Test
public void testNormalCheckoutAfterSparseCheckout() throws Exception {
if (!gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi")));
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build2 = build(project, Result.SUCCESS);
assertTrue(build2.getWorkspace().child("titi").exists());
assertTrue(build2.getWorkspace().child(commitFile2).exists());
assertFalse(build2.getWorkspace().child("toto").exists());
assertFalse(build2.getWorkspace().child(commitFile1).exists());
((GitSCM) project.getScm()).getExtensions().remove(SparseCheckoutPaths.class);
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertTrue(build1.getWorkspace().child("toto").exists());
assertTrue(build1.getWorkspace().child(commitFile1).exists());
}
@Test
public void testInitSparseCheckoutOverSlave() throws Exception {
if (!gitVersionAtLeast(1, 7, 10)) {
/* Older git versions have unexpected behaviors with sparse checkout */
return;
}
FreeStyleProject project = setupProject("master", Lists.newArrayList(new SparseCheckoutPath("titi")));
project.setAssignedLabel(rule.createSlave().getSelfLabel());
// run build first to create workspace
final String commitFile1 = "toto/commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
final String commitFile2 = "titi/commitFile2";
commit(commitFile2, johnDoe, "Commit number 2");
final FreeStyleBuild build1 = build(project, Result.SUCCESS);
assertTrue(build1.getWorkspace().child("titi").exists());
assertTrue(build1.getWorkspace().child(commitFile2).exists());
assertFalse(build1.getWorkspace().child("toto").exists());
assertFalse(build1.getWorkspace().child(commitFile1).exists());
}
/**
* Test for JENKINS-22009.
*
* @throws Exception
*/
@Test
public void testPolling_environmentValueInBranchSpec() throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("${MY_BRANCH}")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "master")));
// commit something in order to create an initial base version in git
commit("toto/commitFile1", johnDoe, "Commit number 1");
// build the project
build(project, Result.SUCCESS);
assertFalse("No changes to git since last build, thus no new build is expected", project.poll(listener).hasChanges());
}
@Issue("JENKINS-29066")
public void baseTestPolling_parentHead(List<GitSCMExtension> extensions) throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("**")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
extensions);
project.setScm(scm);
// commit something in order to create an initial base version in git
commit("toto/commitFile1", johnDoe, "Commit number 1");
git.branch("someBranch");
commit("toto/commitFile2", johnDoe, "Commit number 2");
assertTrue("polling should detect changes",project.poll(listener).hasChanges());
// build the project
build(project, Result.SUCCESS);
/* Expects 1 build because the build of someBranch incorporates all
* the changes from the master branch as well as the changes from someBranch.
*/
assertEquals("Wrong number of builds", 1, project.getBuilds().size());
assertFalse("polling should not detect changes",project.poll(listener).hasChanges());
}
@Issue("JENKINS-29066")
@Test
public void testPolling_parentHead() throws Exception {
baseTestPolling_parentHead(Collections.<GitSCMExtension>emptyList());
}
@Issue("JENKINS-29066")
@Test
public void testPolling_parentHead_DisableRemotePoll() throws Exception {
baseTestPolling_parentHead(Collections.<GitSCMExtension>singletonList(new DisableRemotePoll()));
}
@Test
public void testPollingAfterManualBuildWithParametrizedBranchSpec() throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("${MY_BRANCH}")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("MY_BRANCH", "trackedbranch")));
// Initial commit to master
commit("file1", johnDoe, "Initial Commit");
// Create the branches
git.branch("trackedbranch");
git.branch("manualbranch");
final StringParameterValue branchParam = new StringParameterValue("MY_BRANCH", "manualbranch");
final Action[] actions = {new ParametersAction(branchParam)};
FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get();
rule.assertBuildStatus(Result.SUCCESS, build);
assertFalse("No changes to git since last build", project.poll(listener).hasChanges());
git.checkout("manualbranch");
commit("file2", johnDoe, "Commit to manually build branch");
assertFalse("No changes to tracked branch", project.poll(listener).hasChanges());
git.checkout("trackedbranch");
commit("file3", johnDoe, "Commit to tracked branch");
assertTrue("A change should be detected in tracked branch", project.poll(listener).hasChanges());
}
private final class FakeParametersAction implements EnvironmentContributingAction, Serializable {
// Test class for testPolling_environmentValueAsEnvironmentContributingAction test case
final ParametersAction m_forwardingAction;
public FakeParametersAction(StringParameterValue params) {
this.m_forwardingAction = new ParametersAction(params);
}
public void buildEnvVars(AbstractBuild<?, ?> ab, EnvVars ev) {
this.m_forwardingAction.buildEnvVars(ab, ev);
}
public String getIconFileName() {
return this.m_forwardingAction.getIconFileName();
}
public String getDisplayName() {
return this.m_forwardingAction.getDisplayName();
}
public String getUrlName() {
return this.m_forwardingAction.getUrlName();
}
public List<ParameterValue> getParameters() {
return this.m_forwardingAction.getParameters();
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
}
private void readObjectNoData() throws ObjectStreamException {
}
}
private boolean gitVersionAtLeast(int neededMajor, int neededMinor) throws IOException, InterruptedException {
return gitVersionAtLeast(neededMajor, neededMinor, 0);
}
private boolean gitVersionAtLeast(int neededMajor, int neededMinor, int neededPatch) throws IOException, InterruptedException {
final TaskListener procListener = StreamTaskListener.fromStderr();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final int returnCode = new Launcher.LocalLauncher(procListener).launch().cmds("git", "--version").stdout(out).join();
assertEquals("git --version non-zero return code", 0, returnCode);
assertFalse("Process listener logged an error", procListener.getLogger().checkError());
final String versionOutput = out.toString().trim();
final String[] fields = versionOutput.split(" ")[2].replaceAll("msysgit.", "").split("\\.");
final int gitMajor = Integer.parseInt(fields[0]);
final int gitMinor = Integer.parseInt(fields[1]);
final int gitPatch = Integer.parseInt(fields[2]);
return gitMajor >= neededMajor && gitMinor >= neededMinor && gitPatch >= neededPatch;
}
@Test
public void testPolling_CanDoRemotePollingIfOneBranchButMultipleRepositories() throws Exception {
FreeStyleProject project = createFreeStyleProject();
List<UserRemoteConfig> remoteConfigs = new ArrayList<UserRemoteConfig>();
remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "origin", "", null));
remoteConfigs.add(new UserRemoteConfig(testRepo.gitDir.getAbsolutePath(), "someOtherRepo", "", null));
GitSCM scm = new GitSCM(remoteConfigs,
Collections.singletonList(new BranchSpec("origin/master")), false,
Collections.<SubmoduleConfig> emptyList(), null, null,
Collections.<GitSCMExtension> emptyList());
project.setScm(scm);
commit("commitFile1", johnDoe, "Commit number 1");
FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause()).get();
rule.assertBuildStatus(Result.SUCCESS, first_build);
first_build.getWorkspace().deleteContents();
PollingResult pollingResult = scm.poll(project, null, first_build.getWorkspace(), listener, null);
assertFalse(pollingResult.hasChanges());
}
/**
* Test for JENKINS-24467.
*
* @throws Exception
*/
@Test
public void testPolling_environmentValueAsEnvironmentContributingAction() throws Exception {
// create parameterized project with environment value in branch specification
FreeStyleProject project = createFreeStyleProject();
GitSCM scm = new GitSCM(
createRemoteRepositories(),
Collections.singletonList(new BranchSpec("${MY_BRANCH}")),
false, Collections.<SubmoduleConfig>emptyList(),
null, null,
Collections.<GitSCMExtension>emptyList());
project.setScm(scm);
// Inital commit and build
commit("toto/commitFile1", johnDoe, "Commit number 1");
String brokenPath = "\\broken/path\\of/doom";
if (!gitVersionAtLeast(1, 8)) {
/* Git 1.7.10.4 fails the first build unless the git-upload-pack
* program is available in its PATH.
* Later versions of git don't have that problem.
*/
final String systemPath = System.getenv("PATH");
brokenPath = systemPath + File.pathSeparator + brokenPath;
}
final StringParameterValue real_param = new StringParameterValue("MY_BRANCH", "master");
final StringParameterValue fake_param = new StringParameterValue("PATH", brokenPath);
final Action[] actions = {new ParametersAction(real_param), new FakeParametersAction(fake_param)};
FreeStyleBuild first_build = project.scheduleBuild2(0, new Cause.UserCause(), actions).get();
rule.assertBuildStatus(Result.SUCCESS, first_build);
Launcher launcher = workspace.createLauncher(listener);
final EnvVars environment = GitUtils.getPollEnvironment(project, workspace, launcher, listener);
assertEquals(environment.get("MY_BRANCH"), "master");
assertNotSame("Enviroment path should not be broken path", environment.get("PATH"), brokenPath);
}
/**
* Tests that builds have the correctly specified Custom SCM names, associated with
* each build.
* @throws Exception on various exceptions
*/
@Test
public void testCustomSCMName() throws Exception {
final String branchName = "master";
final FreeStyleProject project = setupProject(branchName, false);
project.addTrigger(new SCMTrigger(""));
GitSCM git = (GitSCM) project.getScm();
setupJGit(git);
final String commitFile1 = "commitFile1";
final String scmNameString1 = "";
commit(commitFile1, johnDoe, "Commit number 1");
assertTrue("scm polling should not detect any more changes after build",
project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1);
final ObjectId commit1 = testRepo.git.revListAll().get(0);
// Check unset build SCM Name carries
final int buildNumber1 = notifyAndCheckScmName(
project, commit1, scmNameString1, 1, git);
final String scmNameString2 = "ScmName2";
git.getExtensions().replace(new ScmName(scmNameString2));
commit("commitFile2", johnDoe, "Commit number 2");
assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges());
final ObjectId commit2 = testRepo.git.revListAll().get(0);
// Check second set SCM Name
final int buildNumber2 = notifyAndCheckScmName(
project, commit2, scmNameString2, 2, git);
checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git);
final String scmNameString3 = "ScmName3";
git.getExtensions().replace(new ScmName(scmNameString3));
commit("commitFile3", johnDoe, "Commit number 3");
assertTrue("scm polling should detect commit 3", project.poll(listener).hasChanges());
final ObjectId commit3 = testRepo.git.revListAll().get(0);
// Check third set SCM Name
final int buildNumber3 = notifyAndCheckScmName(
project, commit3, scmNameString3, 3, git);
checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git);
checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git);
commit("commitFile4", johnDoe, "Commit number 4");
assertTrue("scm polling should detect commit 4", project.poll(listener).hasChanges());
final ObjectId commit4 = testRepo.git.revListAll().get(0);
// Check third set SCM Name still set
final int buildNumber4 = notifyAndCheckScmName(
project, commit4, scmNameString3, 4, git);
checkNumberedBuildScmName(project, buildNumber1, scmNameString1, git);
checkNumberedBuildScmName(project, buildNumber2, scmNameString2, git);
checkNumberedBuildScmName(project, buildNumber3, scmNameString3, git);
}
/**
* Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1
* and tests for custom SCM name build data consistency.
* @param project project to build
* @param commit commit to build
* @param expectedScmName Expected SCM name for commit.
* @param ordinal number of commit to log into errors, if any
* @param git git SCM
* @throws Exception on various exceptions occur
*/
private int notifyAndCheckScmName(FreeStyleProject project, ObjectId commit,
String expectedScmName, int ordinal, GitSCM git) throws Exception {
assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit));
final Build build = project.getLastBuild();
final BuildData buildData = git.getBuildData(build);
assertEquals("Expected SHA1 != built SHA1 for commit " + ordinal, commit, buildData
.getLastBuiltRevision().getSha1());
assertEquals("Expected SHA1 != retrieved SHA1 for commit " + ordinal, commit, buildData.getLastBuild(commit).getSHA1());
assertTrue("Commit " + ordinal + " not marked as built", buildData.hasBeenBuilt(commit));
assertEquals("Wrong SCM Name for commit " + ordinal, expectedScmName, buildData.getScmName());
return build.getNumber();
}
private void checkNumberedBuildScmName(FreeStyleProject project, int buildNumber,
String expectedScmName, GitSCM git) throws Exception {
final BuildData buildData = git.getBuildData(project.getBuildByNumber(buildNumber));
assertEquals("Wrong SCM Name", expectedScmName, buildData.getScmName());
}
/**
* Tests that builds have the correctly specified branches, associated with
* the commit id, passed with "notifyCommit" URL.
* @throws Exception on various exceptions
*/
@Issue("JENKINS-24133")
@Test
public void testSha1NotificationBranches() throws Exception {
final String branchName = "master";
final FreeStyleProject project = setupProject(branchName, false);
project.addTrigger(new SCMTrigger(""));
final GitSCM git = (GitSCM) project.getScm();
setupJGit(git);
final String commitFile1 = "commitFile1";
commit(commitFile1, johnDoe, "Commit number 1");
assertTrue("scm polling should detect commit 1",
project.poll(listener).hasChanges());
build(project, Result.SUCCESS, commitFile1);
final ObjectId commit1 = testRepo.git.revListAll().get(0);
notifyAndCheckBranch(project, commit1, branchName, 1, git);
commit("commitFile2", johnDoe, "Commit number 2");
assertTrue("scm polling should detect commit 2", project.poll(listener).hasChanges());
final ObjectId commit2 = testRepo.git.revListAll().get(0);
notifyAndCheckBranch(project, commit2, branchName, 2, git);
notifyAndCheckBranch(project, commit1, branchName, 1, git);
}
/* A null pointer exception was detected because the plugin failed to
* write a branch name to the build data, so there was a SHA1 recorded
* in the build data, but no branch name.
*/
@Test
public void testNoNullPointerExceptionWithNullBranch() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch(null, sha1);
List<Branch> branchList = new ArrayList<Branch>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<BuildData>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
scm.buildEnvVars(build, new EnvVars()); // NPE here before fix applied
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
@Test
public void testBuildEnvVarsLocalBranchStarStar() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch("origin/master", sha1);
List<Branch> branchList = new ArrayList<Branch>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<BuildData>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
scm.getExtensions().add(new LocalBranch("**"));
EnvVars env = new EnvVars();
scm.buildEnvVars(build, env); // NPE here before fix applied
assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH"));
assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH"));
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
@Test
public void testBuildEnvVarsLocalBranchNull() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch("origin/master", sha1);
List<Branch> branchList = new ArrayList<Branch>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<BuildData>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
scm.getExtensions().add(new LocalBranch(""));
EnvVars env = new EnvVars();
scm.buildEnvVars(build, env); // NPE here before fix applied
assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH"));
assertEquals("GIT_LOCAL_BRANCH", "master", env.get("GIT_LOCAL_BRANCH"));
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
@Test
public void testBuildEnvVarsLocalBranchNotSet() throws Exception {
ObjectId sha1 = ObjectId.fromString("2cec153f34767f7638378735dc2b907ed251a67d");
/* This is the null that causes NPE */
Branch branch = new Branch("origin/master", sha1);
List<Branch> branchList = new ArrayList<Branch>();
branchList.add(branch);
Revision revision = new Revision(sha1, branchList);
/* BuildData mock that will use the Revision with null branch name */
BuildData buildData = Mockito.mock(BuildData.class);
Mockito.when(buildData.getLastBuiltRevision()).thenReturn(revision);
Mockito.when(buildData.hasBeenReferenced(anyString())).thenReturn(true);
/* List of build data that will be returned by the mocked BuildData */
List<BuildData> buildDataList = new ArrayList<BuildData>();
buildDataList.add(buildData);
/* AbstractBuild mock which returns the buildDataList that contains a null branch name */
AbstractBuild build = Mockito.mock(AbstractBuild.class);
Mockito.when(build.getActions(BuildData.class)).thenReturn(buildDataList);
final FreeStyleProject project = setupProject("*/*", false);
GitSCM scm = (GitSCM) project.getScm();
EnvVars env = new EnvVars();
scm.buildEnvVars(build, env); // NPE here before fix applied
assertEquals("GIT_BRANCH", "origin/master", env.get("GIT_BRANCH"));
assertEquals("GIT_LOCAL_BRANCH", null, env.get("GIT_LOCAL_BRANCH"));
/* Verify mocks were called as expected */
verify(buildData, times(1)).getLastBuiltRevision();
verify(buildData, times(1)).hasBeenReferenced(anyString());
verify(build, times(1)).getActions(BuildData.class);
}
/**
* Method performs HTTP get on "notifyCommit" URL, passing it commit by SHA1
* and tests for build data consistency.
* @param project project to build
* @param commit commit to build
* @param expectedBranch branch, that is expected to be built
* @param ordinal number of commit to log into errors, if any
* @param git git SCM
* @throws Exception on various exceptions occur
*/
private void notifyAndCheckBranch(FreeStyleProject project, ObjectId commit,
String expectedBranch, int ordinal, GitSCM git) throws Exception {
assertTrue("scm polling should detect commit " + ordinal, notifyCommit(project, commit));
final BuildData buildData = git.getBuildData(project.getLastBuild());
final Collection<Branch> builtBranches = buildData.lastBuild.getRevision().getBranches();
assertEquals("Commit " + ordinal + " should be built", commit, buildData
.getLastBuiltRevision().getSha1());
final String expectedBranchString = "origin/" + expectedBranch;
assertFalse("Branches should be detected for the build", builtBranches.isEmpty());
assertEquals(expectedBranch + " branch should be detected", expectedBranchString,
builtBranches.iterator().next().getName());
assertEquals(expectedBranchString, getEnvVars(project).get(GitSCM.GIT_BRANCH));
}
/**
* Method performs commit notification for the last committed SHA1 using
* notifyCommit URL.
* @param project project to trigger
* @return whether the new build has been triggered (<code>true</code>) or
* not (<code>false</code>).
* @throws Exception on various exceptions
*/
private boolean notifyCommit(FreeStyleProject project, ObjectId commitId) throws Exception {
final int initialBuildNumber = project.getLastBuild().getNumber();
final String commit1 = ObjectId.toString(commitId);
final String notificationPath = rule.getURL().toExternalForm()
+ "git/notifyCommit?url=" + testRepo.gitDir.toString() + "&sha1=" + commit1;
final URL notifyUrl = new URL(notificationPath);
final InputStream is = notifyUrl.openStream();
IOUtils.toString(is);
IOUtils.closeQuietly(is);
if ((project.getLastBuild().getNumber() == initialBuildNumber)
&& (rule.jenkins.getQueue().isEmpty())) {
return false;
} else {
while (!rule.jenkins.getQueue().isEmpty()) {
Thread.sleep(100);
}
final FreeStyleBuild build = project.getLastBuild();
while (build.isBuilding()) {
Thread.sleep(100);
}
return true;
}
}
private void setupJGit(GitSCM git) {
git.gitTool="jgit";
rule.jenkins.getDescriptorByType(GitTool.DescriptorImpl.class).setInstallations(new JGitTool(Collections.<ToolProperty<?>>emptyList()));
}
/** We clean the environment, just in case the test is being run from a Jenkins job using this same plugin :). */
@TestExtension
public static class CleanEnvironment extends EnvironmentContributor {
@Override
public void buildEnvironmentFor(Run run, EnvVars envs, TaskListener listener) {
envs.remove(GitSCM.GIT_BRANCH);
envs.remove(GitSCM.GIT_LOCAL_BRANCH);
envs.remove(GitSCM.GIT_COMMIT);
envs.remove(GitSCM.GIT_PREVIOUS_COMMIT);
envs.remove(GitSCM.GIT_PREVIOUS_SUCCESSFUL_COMMIT);
}
}
} |
package com.googlecode.test.phone;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.sdp.SessionDescription;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.InvalidArgumentException;
import javax.sip.ListeningPoint;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import javax.sip.address.Address;
import javax.sip.address.SipURI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import org.apache.log4j.Logger;
import com.googlecode.test.phone.rtp.RtpSession;
import com.googlecode.test.phone.rtp.codec.AudioCodec;
import com.googlecode.test.phone.sip.ReceivedMessages;
import com.googlecode.test.phone.sip.SipConstants;
import com.googlecode.test.phone.sip.SipListenerImpl;
import com.googlecode.test.phone.sip.SipStackFactory;
import com.googlecode.test.phone.sip.sdp.SdpUtil;
import com.googlecode.test.phone.sip.util.NetUtil;
import com.googlecode.test.phone.sip.util.PortUtil;
import gov.nist.javax.sip.Utils;
import gov.nist.javax.sip.message.SIPRequest;
public abstract class AbstractSipPhone implements SipPhone {
public static enum ReceivedCallHandleType{
IGNORE,BUSY,ACCEPT;
}
private static final Logger LOG=Logger.getLogger(AbstractSipPhone.class);
protected String localIp;
protected int localSipPort;
protected int localRtpPort;
protected SipURI localSipUri;
protected Set<AudioCodec> supportAudioCodec=new HashSet<AudioCodec>();
protected boolean isEarlyOffer;
protected boolean isPlayListened;
protected boolean isSupportRefer;
protected Dialog dialog;
protected SipStack sipStack;
protected SipProvider sipProvider;
protected RtpSession rtpSession;
protected Map<String,RtpSession> rtpSessionMap=new HashMap<String,RtpSession>();
protected ReceivedCallHandleType receivedCallHandleType;
protected SipListenerImpl sipListenerImpl;
protected ReferFuture referFuture;
{
localIp=NetUtil.getLocalIp();
localSipPort=PortUtil.allocateLocalPort();
localRtpPort=PortUtil.allocateLocalPort();
isEarlyOffer=true;
supportAudioCodec.add(AudioCodec.PCMA);
supportAudioCodec.add(AudioCodec.PCMU);
supportAudioCodec.add(AudioCodec.TELEPHONE_EVENT);
receivedCallHandleType=ReceivedCallHandleType.ACCEPT;
}
public boolean isSupportRefer() {
return isSupportRefer;
}
@Override
public void setSupportRefer(boolean isSupportRefer) {
this.isSupportRefer = isSupportRefer;
}
protected SipURI getLocalSipUrl(String user) {
SipURI createSipURI=null;
try {
createSipURI= SipConstants.Factorys.ADDRESS_FACTORY.createSipURI(user, localIp);
createSipURI.setPort(this.localSipPort);
createSipURI.setTransportParam(ListeningPoint.UDP);
} catch (ParseException e) {
e.printStackTrace();
}
return createSipURI;
}
public boolean isEarlyOffer() {
return isEarlyOffer;
}
@Override
public void setEarlyOffer(boolean isEarlyOffer) {
this.isEarlyOffer = isEarlyOffer;
}
public AbstractSipPhone() {
super();
sipStack = SipStackFactory.getInstance().createSipStack();
try {
ListeningPoint sipListeningPoint = sipStack.createListeningPoint(localIp, localSipPort, ListeningPoint.UDP);
sipProvider = sipStack.createSipProvider(sipListeningPoint);
sipListenerImpl = new SipListenerImpl(this);
sipProvider.addSipListener(sipListenerImpl);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
LOG.info("[sipstack]sip stack start for :"+this);
}
public ReceivedCallHandleType getReceivedCallHandleType() {
return receivedCallHandleType;
}
public void setReceivedCallHandleType(ReceivedCallHandleType receivedCallHandleType) {
this.receivedCallHandleType = receivedCallHandleType;
}
public SipListenerImpl getSipListenerImpl() {
return sipListenerImpl;
}
public void setSipListenerImpl(SipListenerImpl sipListenerImpl) {
this.sipListenerImpl = sipListenerImpl;
}
@Override
public ReceivedMessages getReceivedMessages() {
return sipListenerImpl.getReceivedMessages();
}
@Override
public void enablePlayListened() {
this.isPlayListened = true;
}
public SipProvider getSipProvider() {
return sipProvider;
}
public RtpSession getRtpSession() {
return rtpSession;
}
public void setRtpSession(String dialog,String localIp,int localRtpPort,String remoteIp, int remoteRtpPort, Set<AudioCodec> audioCodecs){
RtpSession rtpSession = new RtpSession(localIp,localRtpPort,remoteIp,remoteRtpPort,audioCodecs);
rtpSessionMap.put(dialog, rtpSession);
this.rtpSession = rtpSession;
if(isPlayListened)
this.rtpSession.enablePlay();
}
public SipStack getSipStack() {
return sipStack;
}
@Override
public void sendDtmf(String dtmfs){
sendDtmf(dtmfs,0);
}
@Override
public void sendDtmf(String digits, int sleepTimeByMilliSecond){
if(rtpSession==null)
throw new RuntimeException("sip negotition not setup");
rtpSession.sendDtmf(digits,sleepTimeByMilliSecond);
}
@Override
public void invite(String requestUrl,String callId) {
try{
Request request = createInviteRequestWithSipHeader(requestUrl, callId);
if(isEarlyOffer){
SessionDescription sessionDescription = SdpUtil.createSessionDescription(localIp, localRtpPort, supportAudioCodec);
request.setContent(sessionDescription, SipConstants.Factorys.HEADER_FACTORY.createContentTypeHeader("application", "sdp"));
}
LOG.info(request);
ClientTransaction newClientTransaction = sipProvider.getNewClientTransaction(request);
dialog=newClientTransaction.getDialog();
newClientTransaction.sendRequest();
}catch(Exception exception){
throw new RuntimeException(exception.getMessage(),exception);
}
}
@Override
public void bye() {
try {
if(dialog==null){
return;
}
Request byeRequest = this.dialog.createRequest(Request.BYE);
LOG.info(byeRequest);
ClientTransaction ct = sipProvider.getNewClientTransaction(byeRequest);
dialog.sendRequest(ct);
} catch (SipException e) {
e.printStackTrace();
}
}
/**
*
* @param requestUrl
* @param callId
* @return
* @throws ParseException
* @throws InvalidArgumentException
*/
private Request createInviteRequestWithSipHeader(String requestUrl,String callId)
throws ParseException, InvalidArgumentException {
Address requestAddress = SipConstants.Factorys.ADDRESS_FACTORY.createAddress(requestUrl);
Address localSipAddress = SipConstants.Factorys.ADDRESS_FACTORY.createAddress(localSipUri);
String fromTag = Utils.getInstance().generateTag();
FromHeader fromHeader = SipConstants.Factorys.HEADER_FACTORY.createFromHeader(localSipAddress, fromTag);
ToHeader toHeader = SipConstants.Factorys.HEADER_FACTORY.createToHeader(requestAddress, null);
CSeqHeader cSeqHeader = SipConstants.Factorys.HEADER_FACTORY.createCSeqHeader(1l, SIPRequest.INVITE);
CallIdHeader callIdHeader = SipConstants.Factorys.HEADER_FACTORY.createCallIdHeader(callId);
List<ViaHeader> viaHeaders = new ArrayList<ViaHeader>();
ViaHeader viaHeader = SipConstants.Factorys.HEADER_FACTORY.createViaHeader(localIp,
localSipPort, ListeningPoint.UDP, Utils.getInstance().generateBranchId());
viaHeaders.add(viaHeader);
ContactHeader createContactHeader = SipConstants.Factorys.HEADER_FACTORY.createContactHeader(localSipAddress);
Request request = SipConstants.Factorys.MESSAGE_FACTORY.createRequest(requestAddress.getURI(),
SIPRequest.INVITE, callIdHeader, cSeqHeader, fromHeader,
toHeader, viaHeaders, SipConstants.DefaultHeaders.DEFAULT_MAXFORWARDS_HEADER);
request.addHeader(createContactHeader);
return request;
}
/* (non-Javadoc)
* @see com.googlecode.test.phone.SipPhone#stop()
*/
@Override
public void stop(){
LOG.info("sip stack stop for:"+this);
try{
TimeUnit.MILLISECONDS.sleep(500);
Collection<RtpSession> values = rtpSessionMap.values();
for (RtpSession rtpSession : values) {
rtpSession.stop();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
sipStack.stop();
}
}
public void stopRtpSession(String dialogId){
RtpSession rtpSessionInMaps = this.rtpSessionMap.remove(dialogId);
if(rtpSessionInMaps!=null){
rtpSessionInMaps.stop();
}
if(rtpSessionInMaps==this.rtpSession)
this.rtpSession=null;
}
public Set<AudioCodec> getSupportAudioCodec() {
return supportAudioCodec;
}
public void setSupportAudioCodec(Set<AudioCodec> supportAudioCodec) {
this.supportAudioCodec = supportAudioCodec;
}
public String getLocalIp() {
return localIp;
}
public int getLocalSipPort() {
return localSipPort;
}
public int getLocalRtpPort() {
return localRtpPort;
}
public SipURI getLocalSipUri() {
return localSipUri;
}
public Dialog getDialog() {
return dialog;
}
public void setDialog(Dialog dialog) {
this.dialog = dialog;
}
public ReferFuture getReferFuture() {
return referFuture;
}
public void setReferFuture(ReferFuture referFuture) {
this.referFuture = referFuture;
}
@Override
public String toString() {
return "AbstractSipPhone [localIp=" + localIp + ", sipPort=" + localSipPort + ", rtpPort=" + localRtpPort + "]";
}
} |
package innovimax.mixthem;
import innovimax.mixthem.arguments.Mode;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.arguments.Rule;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.io.InputResource;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.theories.*;
import org.junit.runner.RunWith;
public class GenericTest {
@Test
public final void testCharRules() throws MixException, FileNotFoundException, IOException, NumberFormatException {
testRules(Mode.CHAR);
}
@Test
public final void testBytesRules() throws MixException, FileNotFoundException, IOException, NumberFormatException {
testRules(Mode.BYTE);
}
private final void testRules(final Mode mode) throws MixException, FileNotFoundException, IOException, NumberFormatException {
MixThem.setLogging(Level.FINE);
int testId = 1;
List<String> failed = new ArrayList<String>();
boolean result = true;
while (true) {
MixThem.LOGGER.info("TEST [" + mode.getName().toUpperCase() + "] N° " + testId + "***********************************************************");
String prefix = "test" + String.format("%03d", testId) +"_";
List<URL> urlF = new ArrayList<URL>();
int index = 1;
while (true) {
final url = getClass().getResource(prefix + "file" + index + ".txt");
if (url != null) {
urlF.add(url);
index++;
} else {
break;
}
}
if( urlF.size() < 2) break;
for (int i=0; i < urlF.size(); i++) {
MixThem.LOGGER.info("File " + i + ": " + urlF.get(i));
}
for(Rule rule : Rule.values()) {
if (rule.isImplemented() && rule.acceptMode(mode)) {
String paramsFile = prefix + "params-" + rule.getExtension() + ".txt";
URL urlP = getClass().getResource(paramsFile);
List<RuleRun> runs = RuleRuns.getRuns(rule, urlP);
for (RuleRun run : runs) {
String resultFile = prefix + "output-" + rule.getExtension();
if (run.hasSuffix()) {
resultFile += "-" + run.getSuffix();
}
resultFile += ".txt";
URL urlR = getClass().getResource(resultFile);
if (urlR != null) {
MixThem.LOGGER.info("
if (urlP != null) {
MixThem.LOGGER.info("Params file : " + urlP);
}
MixThem.LOGGER.info("Result file : " + urlR);
MixThem.LOGGER.info("
boolean res = check(new File(urlF.get(0).getFile()), new File(urlF.get(1).getFile()), new File(urlR.getFile()), mode, rule, run.getParams());
MixThem.LOGGER.info("Run " + (res ? "pass" : "FAIL") + " with params " + run.getParams().toString());
result &= res;
if (!res) {
failed.add(Integer.toString(testId));
}
}
}
}
}
testId++;
}
MixThem.LOGGER.info("*********************************************************************");
MixThem.LOGGER.info("FAILED [" + mode.getName().toUpperCase() + "] TESTS : " + (failed.size() > 0 ? failed.toString() : "None"));
MixThem.LOGGER.info("*********************************************************************");
Assert.assertTrue(result);
}
private final static boolean check(final File file1, final File file2, final File expected, final Mode mode, final Rule rule, final Map<RuleParam, ParamValue> params) throws MixException, FileNotFoundException, IOException {
MixThem.LOGGER.info("Run and check result...");
List<InputResource> inputs = new ArrayList<InputResource>();
inputs.add(InputResource.createFile(file1));
inputs.add(InputResource.createFile(file2));
ByteArrayOutputStream baos_rule = new ByteArrayOutputStream();
MixThem mixThem = new MixThem(inputs, baos_rule);
mixThem.process(mode, rule, params);
MixThem.LOGGER.info("Run and print result...");
mixThem = new MixThem(inputs, System.out);
mixThem.process(mode, rule, params);
return checkFileEquals(expected, baos_rule.toByteArray());
}
private static boolean checkFileEquals(final File fileExpected, final byte[] result) throws FileNotFoundException, IOException {
FileInputStream fisExpected = new FileInputStream(fileExpected);
int c;
int offset = 0;
while ((c = fisExpected.read()) != -1) {
if (offset >= result.length) return false;
int d = result[offset++];
if (c != d) return false;
}
if (offset > result.length) return false;
return true;
}
} |
package com.hyperfresh.mchyperchat;
import java.util.Collection;
import java.util.UUID;
public interface HyperChatPlugin
{
/**
* Gets a Player by their UUID.
* <p/>
* If this method returns null, then the Player is not online.
*
* @param id
* @return a Player or null if that player is not online
*/
public Player getPlayer(UUID id);
/**
* Gets all Users on the server, which includes both all online players and the console.
*
* @return a set of Players on the server
*/
public Collection<User> getUsers();
} |
package innovimax.mixthem;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.arguments.Rule;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.io.InputResource;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.theories.*;
import org.junit.runner.RunWith;
public class GenericTest {
@Test
public final void parameter() throws MixException, FileNotFoundException, IOException, NumberFormatException {
MixThem.setLogging(Level.FINE);
int testId = 1;
List<String> failed = new ArrayList<String>();
boolean result = true;
while (true) {
MixThem.LOGGER.info("TEST N° " + testId + "***********************************************************");
String prefix = "test" + String.format("%03d", testId) +"_";
URL url1 = getClass().getResource(prefix + "file1.txt");
URL url2 = getClass().getResource(prefix + "file2.txt");
if( url1 == null || url2 == null) break;
MixThem.LOGGER.info("File 1 : " + prefix + "file1.txt");
MixThem.LOGGER.info("File 2 : " + prefix + "file2.txt");
for(Rule rule : Rule.values()) {
if (rule.isImplemented()) {
String paramsFile = prefix + "params-" + rule.getExtension() + ".txt";
URL urlP = getClass().getResource(paramsFile);
List<RuleRun> runs = RuleRuns.getRuns(rule, urlP);
for (RuleRun run : runs) {
String resultFile = prefix + "output-" + rule.getExtension();
if (run.hasSuffix()) {
resultFile += "-" + run.getSuffix();
}
resultFile += ".txt";
URL urlR = getClass().getResource(resultFile);
if (urlR != null) {
MixThem.LOGGER.info("
if (urlP != null) {
MixThem.LOGGER.info("Params file : " + paramsFile);
}
MixThem.LOGGER.info("Result file : " + resultFile);
MixThem.LOGGER.info("
boolean res = check(new File(url1.getFile()), new File(url2.getFile()), new File(urlR.getFile()), rule, run.getParams());
MixThem.LOGGER.info("Run " + (res ? "pass" : "FAIL") + " with params " + run.getParams().toString());
result &= res;
if (!res) {
failed.add(Integer.toString(testId));
}
}
}
}
}
testId++;
}
MixThem.LOGGER.info("*********************************************************************");
MixThem.LOGGER.info("FAILED TESTS : " + (failed.size() > 0 ? failed.toString() : "None"));
MixThem.LOGGER.info("*********************************************************************");
Assert.assertTrue(result);
}
private final static boolean check(final File final file1, final File file2, final File expected, final Mode mode, final Rule rule, final Map<RuleParam, ParamValue> params) throws MixException, FileNotFoundException, IOException {
MixThem.LOGGER.info("Run and check result...");
InputResource input1 = InputResource.createFile(file1);
InputResource input2 = InputResource.createFile(file2);
ByteArrayOutputStream baos_rule = new ByteArrayOutputStream();
MixThem mixThem = new MixThem(input1, input2, baos_rule);
mixThem.process(mode, rule, params);
MixThem.LOGGER.info("Run and print result...");
mixThem = new MixThem(input1, input2, System.out);
mixThem.process(mode, rule, params);
return checkFileEquals(expected, baos_rule.toByteArray());
}
private static boolean checkFileEquals(final File fileExpected, final byte[] result) throws FileNotFoundException, IOException {
FileInputStream fisExpected = new FileInputStream(fileExpected);
int c;
int offset = 0;
while ((c = fisExpected.read()) != -1) {
if (offset >= result.length) return false;
int d = result[offset++];
if (c != d) return false;
}
if (offset > result.length) return false;
return true;
}
} |
package org.m2mp.db.ts;
import com.datastax.driver.core.utils.UUIDs;
import org.json.simple.JSONObject;
import java.util.*;
/**
* Timed data wrapper.
* <p/>
* We have the same data as the TimedData class except we are working in JSON only, we can modify the content efficiently
* and we can save it to modify an existing time serie element (a timedData).
*/
public class TimedDataWrapper {
private final String id;
private final String type;
private final UUID date;
private Map<String, Object> map;
private boolean mod;
public TimedDataWrapper(String id, String type, UUID date, Map<String, Object> map) {
if (id != null) {
int p = id.indexOf('!');
if (p != -1) {
String srcId = id;
id = srcId.substring(0, p);
type = srcId.substring(p + 1);
}
}
this.id = id;
this.type = type;
this.date = date;
this.map = map;
this.mod = true;
}
public TimedDataWrapper(String type, UUID date, Map<String, Object> map) {
this(null, type, date, map);
}
public TimedDataWrapper(String type, Date date, Map<String, Object> map) {
this(null, type, new UUID(UUIDs.startOf(date.getTime()).getMostSignificantBits(), System.nanoTime()), map);
}
public TimedDataWrapper(String type) {
this(type, new Date(), new TreeMap<String, Object>());
}
public TimedDataWrapper(TimedData td) {
this(td.getId(), td.getType(), td.getDateUUID(), td.getJsonMap());
}
public TimedDataWrapper(String id, String type, Map<String, Object> map) {
this(id, type, new UUID(UUIDs.startOf(System.currentTimeMillis()).getMostSignificantBits(), System.nanoTime()), map);
}
public TimedDataWrapper(String id, String type) {
this(id, type, new TreeMap<String, Object>());
}
public String getId() {
return id;
}
public String getType() {
return type;
}
public UUID getDateUUID() {
return date;
}
public Date getDate() {
return new Date(UUIDs.unixTimestamp(date));
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
modified();
}
public void set(String name, Object obj) {
map.put(name, obj);
modified();
}
public List<String> getStrings(String name) {
return (List<String>) map.get(name);
}
public void set(String name, Iterable<String> many) {
map.put(name, many);
modified();
}
public String getString(String name) {
return (String) map.get(name);
}
public Long getLong(String name) {
Object obj = map.get(name);
if (obj instanceof Long) // New format
return (Long) obj;
else if (obj instanceof Integer)
return new Long((Integer) obj);
else if (obj instanceof String) // Old format
return Long.parseLong((String) obj);
else
return null;
}
public Double getDouble(String name) {
Object obj = map.get(name);
if (obj instanceof Double) // New format
return (Double) obj;
else if (obj instanceof String) // Old format
return Double.parseDouble((String) obj);
else
return null;
}
public Boolean getBoolean(String name) {
Object obj = map.get(name);
if (obj instanceof Boolean) // New format
return (Boolean) obj;
else if (obj instanceof String) // Old format
return Boolean.parseBoolean((String) obj);
else
return null;
}
public String get(String name, String defaultValue) {
String value = getString(name);
return value != null ? value : defaultValue;
}
public long get(String name, long defaultValue) {
Long value = getLong(name);
return value != null ? value : defaultValue;
}
public int get(String name, int defaultValue) {
return (int) get(name, (long) defaultValue);
}
public double get(String name, double defaultValue) {
Double value = getDouble(name);
return value != null ? value : defaultValue;
}
public boolean get(String name, boolean defaultValue) {
Boolean value = getBoolean(name);
return value != null ? value : defaultValue;
}
public void modified() {
mod = true;
}
public String getJson() {
return JSONObject.toJSONString(map);
}
public void save() {
if (mod) {
// We don't need to re-read the data, everything is on the map
TimeSerie.save(this);
}
}
public void delete() {
TimeSerie.delete(this);
}
public String toString() {
return "TDW{id=\"" + id + "\",type=\"" + type + "\",map=" + map + "}";
}
public static Iterable<TimedDataWrapper> iter(final Iterable<TimedData> iterable) {
return new Iterable<TimedDataWrapper>() {
@Override
public Iterator<TimedDataWrapper> iterator() {
return new Iterator<TimedDataWrapper>() {
private final Iterator<TimedData> iterator = iterable.iterator();
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public TimedDataWrapper next() {
return new TimedDataWrapper(iterator.next());
}
@Override
public void remove() {
iterator().remove();
}
};
}
};
}
} |
package com.instructure.canvasapi.model;
import android.content.Context;
import android.os.Parcel;
import com.instructure.canvasapi.R;
import com.instructure.canvasapi.utilities.APIHelpers;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Assignment extends CanvasModel<Assignment>{
private long id;
private String name;
private String description;
private List<String> submission_types = new ArrayList<String>();
private String due_at;
private double points_possible;
private long course_id;
private String grading_type;
private long needs_grading_count;
private String html_url;
private String url;
private long quiz_id; // (Optional) id of the associated quiz (applies only when submission_types is ["online_quiz"])
private List<RubricCriterion> rubric = new ArrayList<RubricCriterion>();
private boolean use_rubric_for_grading;
private List<String> allowed_extensions = new ArrayList<String>();
private Submission submission;
private long assignment_group_id;
private int position;
private boolean peer_reviews;
//Module lock info
private LockInfo lock_info;
private boolean locked_for_user;
private String lock_at; //Date the teacher no longer accepts submissions.
private String unlock_at;
private String lock_explanation;
private DiscussionTopicHeader discussion_topic;
private List<NeedsGradingCount> needs_grading_count_by_section = new ArrayList<NeedsGradingCount>();
private boolean free_form_criterion_comments;
private boolean published;
private boolean muted;
private long group_category_id;
private List<AssignmentDueDate> all_dates = new ArrayList<AssignmentDueDate>();
// Getters and Setters
@Override
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDueDate() {
if(due_at == null) {
return null;
}
return APIHelpers.stringToDate(due_at);
}
public Date getlockAtDate(){
if(lock_at == null){
return null;
}
return APIHelpers.stringToDate(lock_at);
}
public void setDueDate(String dueDate) {
this.due_at = dueDate;
}
public void setDueDate(Date dueDate){
setDueDate(APIHelpers.dateToString(dueDate));
}
public void setLockAtDate(String lockAtDate){
this.lock_at = lockAtDate;
}
public List<SUBMISSION_TYPE> getSubmissionTypes() {
if(submission_types == null) {
return new ArrayList<SUBMISSION_TYPE>();
}
List<SUBMISSION_TYPE> submissionTypeList = new ArrayList<SUBMISSION_TYPE>();
for(String submissionType : submission_types){
submissionTypeList.add(getSubmissionTypeFromAPIString(submissionType));
}
return submissionTypeList;
}
public void setSubmissionTypes(ArrayList<String> submissionTypes) {
if(submissionTypes == null){
return;
}
this.submission_types = submissionTypes;
}
public void setSubmissionTypes(SUBMISSION_TYPE[] submissionTypes){
if(submissionTypes == null){
return;
}
ArrayList<String> listSubmissionTypes = new ArrayList<String>();
for(SUBMISSION_TYPE submissionType: submissionTypes){
listSubmissionTypes.add(submissionTypeToAPIString(submissionType));
}
setSubmissionTypes(listSubmissionTypes);
}
public long getNeedsGradingCount() {return needs_grading_count;}
public void setNeedsGradingCount(long needs_grading_count) { this.needs_grading_count = needs_grading_count; }
public double getPointsPossible() {
return points_possible;
}
public void setPointsPossible(double pointsPossible) {
this.points_possible = pointsPossible;
}
public long getCourseId() {
return course_id;
}
public void setCourseId(long courseId) {
this.course_id = courseId;
}
public void setDiscussionTopicHeader(DiscussionTopicHeader header) {
discussion_topic = header;
}
public DiscussionTopicHeader getDiscussionTopicHeader() {
return discussion_topic;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHtmlUrl() {
return html_url;
}
public void setHtmlUrl(String htmlUrl) {
this.html_url = htmlUrl;
}
public long getQuizId() {
return quiz_id;
}
public void setQuizId(long id) {
quiz_id = id;
}
public List<RubricCriterion> getRubric() {
return rubric;
}
public void setRubric(List<RubricCriterion> rubric) {
this.rubric = rubric;
}
public boolean isUseRubricForGrading() {
return use_rubric_for_grading;
}
public void setUseRubricForGrading(boolean useRubricForGrading) {
this.use_rubric_for_grading = useRubricForGrading;
}
public List<String> getAllowedExtensions() {
return allowed_extensions;
}
public void setAllowedExtensions(List<String> allowedExtensions) {
this.allowed_extensions = allowedExtensions;
}
public Submission getLastSubmission() {
return submission;
}
public void setLastSubmission(Submission lastSubmission) {
this.submission = lastSubmission;
}
public long getAssignmentGroupId() {
return assignment_group_id;
}
public void setAssignmentGroupId(Long assignmentGroupId) {
this.assignment_group_id = assignmentGroupId == null ?0:assignmentGroupId;
}
public LockInfo getLockInfo() {
return lock_info;
}
public void setLockInfo(LockInfo lockInfo) {
this.lock_info = lockInfo;
}
public boolean isLockedForUser() {
return locked_for_user;
}
public void setLockedForUser(boolean locked) {
this.locked_for_user = locked;
}
public GRADING_TYPE getGradingType(){return getGradingTypeFromAPIString(grading_type);}
@Deprecated
public GRADING_TYPE getGradingType(Context context){
return getGradingTypeFromString(grading_type, context);
}
public void setGradingType(GRADING_TYPE grading_type) {
this.grading_type = gradingTypeToAPIString(grading_type);
}
public TURN_IN_TYPE getTurnInType(){return turnInTypeFromSubmissionType(getSubmissionTypes());}
public Submission getLastActualSubmission() {
if(submission == null) {
return null;
}
if(submission.getWorkflowState() != null && submission.getWorkflowState().equals("submitted")) {
return submission;
}
else {
return null;
}
}
public Date getUnlockAt() {
if(unlock_at == null){
return null;
}
return APIHelpers.stringToDate(unlock_at);
}
public void setUnlockAt(Date unlockAt){
unlock_at = APIHelpers.dateToString(unlockAt);
}
public boolean hasPeerReviews() {
return peer_reviews;
}
public void setPeerReviews(boolean peerReviews) {
this.peer_reviews = peer_reviews;
}
public List<NeedsGradingCount> getNeedsGradingCountBySection(){
return needs_grading_count_by_section;
}
public void setNeedsGradingCountBySection(List<NeedsGradingCount> needs_grading_count_by_section){
this.needs_grading_count_by_section = needs_grading_count_by_section;
}
public boolean isFreeFormCriterionComments() {
return free_form_criterion_comments;
}
public void setFreeFormCriterionComments(boolean free_form_criterion_comments) {
this.free_form_criterion_comments = free_form_criterion_comments;
}
public boolean isPublished() {
return published;
}
public void setPublished(boolean published) {
this.published = published;
}
public long getGroupCategoryId(){
return this.group_category_id;
}
public void setGroupCategoryId(long groupId){
this.group_category_id = groupId;
}
public List<AssignmentDueDate> getDueDates(){
return this.all_dates;
}
public void setAllDates(List<AssignmentDueDate> all_dates){
this.all_dates = all_dates;
}
public void setMuted(boolean isMuted){
this.muted = isMuted;
}
public boolean isMuted(){
return this.muted;
}
public String getLock_explanation() {
return lock_explanation;
}
// Required Overrides
@Override
public Date getComparisonDate() {
return getDueDate();
}
@Override
public String getComparisonString() {
return getName();
}
// Constructors
public Assignment() {}
// Helpers
public static final SUBMISSION_TYPE[] ONLINE_SUBMISSIONS = {SUBMISSION_TYPE.ONLINE_UPLOAD, SUBMISSION_TYPE.ONLINE_URL, SUBMISSION_TYPE.ONLINE_TEXT_ENTRY, SUBMISSION_TYPE.MEDIA_RECORDING};
public enum TURN_IN_TYPE {ONLINE, ON_PAPER, NONE, DISCUSSION, QUIZ, EXTERNAL_TOOL}
private boolean expectsSubmissions() {
List<SUBMISSION_TYPE> submissionTypes = getSubmissionTypes();
return submissionTypes.size() > 0 && !submissionTypes.contains(SUBMISSION_TYPE.NONE) && !submissionTypes.contains(SUBMISSION_TYPE.NOT_GRADED) && !submissionTypes.contains(SUBMISSION_TYPE.ON_PAPER) && !submissionTypes.contains(SUBMISSION_TYPE.EXTERNAL_TOOL);
}
public boolean isAllowedToSubmit() {
List<SUBMISSION_TYPE> submissionTypes = getSubmissionTypes();
return expectsSubmissions() && !isLockedForUser() && !submissionTypes.contains(SUBMISSION_TYPE.ONLINE_QUIZ) && !submissionTypes.contains(SUBMISSION_TYPE.ATTENDANCE);
}
public boolean isWithoutGradedSubmission() {
Submission submission = getLastActualSubmission();
return submission == null || submission.isWithoutGradedSubmission();
}
public static TURN_IN_TYPE stringToTurnInType(String turnInType, Context context){
if(turnInType == null){
return null;
}
if(turnInType.equals(context.getString(R.string.canvasAPI_online))){
return TURN_IN_TYPE.ONLINE;
} else if(turnInType.equals(context.getString(R.string.canvasAPI_onPaper))){
return TURN_IN_TYPE.ON_PAPER;
} else if(turnInType.equals(context.getString(R.string.canvasAPI_discussion))){
return TURN_IN_TYPE.DISCUSSION;
} else if(turnInType.equals(context.getString(R.string.canvasAPI_quiz))){
return TURN_IN_TYPE.QUIZ;
} else if(turnInType.equals(context.getString(R.string.canvasAPI_externalTool))){
return TURN_IN_TYPE.EXTERNAL_TOOL;
} else{
return TURN_IN_TYPE.NONE;
}
}
public static String turnInTypeToPrettyPrintString(TURN_IN_TYPE turnInType, Context context){
if(turnInType == null){
return null;
}
switch (turnInType){
case ONLINE:
return context.getString(R.string.canvasAPI_online);
case ON_PAPER:
return context.getString(R.string.canvasAPI_onPaper);
case NONE:
return context.getString(R.string.canvasAPI_none);
case DISCUSSION:
return context.getString(R.string.canvasAPI_discussion);
case QUIZ:
return context.getString(R.string.canvasAPI_quiz);
case EXTERNAL_TOOL:
return context.getString(R.string.canvasAPI_externalTool);
default:
return null;
}
}
private TURN_IN_TYPE turnInTypeFromSubmissionType(List<SUBMISSION_TYPE> submissionTypes){
if(submissionTypes == null || submissionTypes.size() == 0){
return TURN_IN_TYPE.NONE;
}
SUBMISSION_TYPE submissionType = submissionTypes.get(0);
if(submissionType == SUBMISSION_TYPE.MEDIA_RECORDING || submissionType == SUBMISSION_TYPE.ONLINE_TEXT_ENTRY ||
submissionType == SUBMISSION_TYPE.ONLINE_URL || submissionType == SUBMISSION_TYPE.ONLINE_UPLOAD ){
return TURN_IN_TYPE.ONLINE;
}else if(submissionType == SUBMISSION_TYPE.ONLINE_QUIZ){
return TURN_IN_TYPE.QUIZ;
}else if(submissionType == SUBMISSION_TYPE.DISCUSSION_TOPIC){
return TURN_IN_TYPE.DISCUSSION;
}else if(submissionType == SUBMISSION_TYPE.ON_PAPER){
return TURN_IN_TYPE.ON_PAPER;
}else if(submissionType == SUBMISSION_TYPE.EXTERNAL_TOOL){
return TURN_IN_TYPE.EXTERNAL_TOOL;
}
return TURN_IN_TYPE.NONE;
}
public boolean isLocked() {
Date currentDate = new Date();
if(getLockInfo() == null || getLockInfo().isEmpty()) {
return false;
} else if(getLockInfo().getLockedModuleName() != null && getLockInfo().getLockedModuleName().length() > 0 && !getLockInfo().getLockedModuleName().equals("null")) {
return true;
} else if(getLockInfo().getUnlockedAt().after(currentDate)){
return true;
}
return false;
}
public void populateScheduleItem(ScheduleItem scheduleItem) {
scheduleItem.setId(this.getId());
scheduleItem.setTitle(this.getName());
scheduleItem.setStartDate(this.getDueDate());
scheduleItem.setType(ScheduleItem.Type.TYPE_ASSIGNMENT);
scheduleItem.setDescription(this.getDescription());
scheduleItem.setSubmissionTypes(getSubmissionTypes());
scheduleItem.setPointsPossible(this.getPointsPossible());
scheduleItem.setHtmlUrl(this.getHtmlUrl());
scheduleItem.setQuizId(this.getQuizId());
scheduleItem.setDiscussionTopicHeader(this.getDiscussionTopicHeader());
scheduleItem.setAssignment(this);
if(getLockInfo() != null && getLockInfo().getLockedModuleName() != null) {
scheduleItem.setLockedModuleName(this.getLockInfo().getLockedModuleName());
}
}
public ScheduleItem toScheduleItem() {
ScheduleItem scheduleItem = new ScheduleItem();
populateScheduleItem(scheduleItem);
return scheduleItem;
}
public boolean hasRubric() {
if (rubric == null) {
return false;
}
return rubric.size() > 0;
}
public enum SUBMISSION_TYPE {ONLINE_QUIZ, NONE, ON_PAPER, DISCUSSION_TOPIC, EXTERNAL_TOOL, ONLINE_UPLOAD, ONLINE_TEXT_ENTRY, ONLINE_URL, MEDIA_RECORDING, ATTENDANCE, NOT_GRADED}
private SUBMISSION_TYPE getSubmissionTypeFromAPIString(String submissionType){
if(submissionType.equals("online_quiz")){
return SUBMISSION_TYPE.ONLINE_QUIZ;
} else if(submissionType.equals("none")){
return SUBMISSION_TYPE.NONE;
} else if(submissionType.equals("on_paper")){
return SUBMISSION_TYPE.ON_PAPER;
} else if(submissionType.equals("discussion_topic")){
return SUBMISSION_TYPE.DISCUSSION_TOPIC;
} else if(submissionType.equals("external_tool")){
return SUBMISSION_TYPE.EXTERNAL_TOOL;
} else if(submissionType.equals("online_upload")){
return SUBMISSION_TYPE.ONLINE_UPLOAD;
} else if(submissionType.equals("online_text_entry")){
return SUBMISSION_TYPE.ONLINE_TEXT_ENTRY;
} else if(submissionType.equals("online_url")){
return SUBMISSION_TYPE.ONLINE_URL;
} else if(submissionType.equals("media_recording")){
return SUBMISSION_TYPE.MEDIA_RECORDING;
} else if(submissionType.equals("attendance")) {
return SUBMISSION_TYPE.ATTENDANCE;
} else if(submissionType.equals("not_graded")) {
return SUBMISSION_TYPE.NOT_GRADED;
} else {
return null;
}
}
public static String submissionTypeToAPIString(SUBMISSION_TYPE submissionType){
if(submissionType == null){
return null;
}
switch (submissionType){
case ONLINE_QUIZ:
return "online_quiz";
case NONE:
return "none";
case ON_PAPER:
return "on_paper";
case DISCUSSION_TOPIC:
return "discussion_topic";
case EXTERNAL_TOOL:
return "external_tool";
case ONLINE_UPLOAD:
return "online_upload";
case ONLINE_TEXT_ENTRY:
return "online_text_entry";
case ONLINE_URL:
return "online_url";
case MEDIA_RECORDING:
return "media_recording";
case ATTENDANCE:
return "attendance";
case NOT_GRADED:
return "not_graded";
default:
return "";
}
}
public static String submissionTypeToPrettyPrintString(SUBMISSION_TYPE submissionType, Context context){
if(submissionType == null){
return null;
}
switch (submissionType){
case ONLINE_QUIZ:
return context.getString(R.string.canvasAPI_onlineQuiz);
case NONE:
return context.getString(R.string.canvasAPI_none);
case ON_PAPER:
return context.getString(R.string.canvasAPI_onPaper);
case DISCUSSION_TOPIC:
return context.getString(R.string.canvasAPI_discussionTopic);
case EXTERNAL_TOOL:
return context.getString(R.string.canvasAPI_externalTool);
case ONLINE_UPLOAD:
return context.getString(R.string.canvasAPI_onlineUpload);
case ONLINE_TEXT_ENTRY:
return context.getString(R.string.canvasAPI_onlineTextEntry);
case ONLINE_URL:
return context.getString(R.string.canvasAPI_onlineURL);
case MEDIA_RECORDING:
return context.getString(R.string.canvasAPI_mediaRecording);
case ATTENDANCE:
return context.getString(R.string.canvasAPI_attendance);
case NOT_GRADED:
return context.getString(R.string.canvasAPI_notGraded);
default:
return "";
}
}
public enum GRADING_TYPE {PASS_FAIL, PERCENT, LETTER_GRADE, POINTS, GPA_SCALE, NOT_GRADED}
public static GRADING_TYPE getGradingTypeFromString(String gradingType, Context context){
if(gradingType.equals("pass_fail") || gradingType.equals(context.getString(R.string.canvasAPI_passFail))){
return GRADING_TYPE.PASS_FAIL;
} else if(gradingType.equals("percent") || gradingType.equals(context.getString(R.string.canvasAPI_percent))){
return GRADING_TYPE.PERCENT;
} else if(gradingType.equals("letter_grade") || gradingType.equals(context.getString(R.string.canvasAPI_letterGrade))){
return GRADING_TYPE.LETTER_GRADE;
} else if (gradingType.equals("points") || gradingType.equals(context.getString(R.string.canvasAPI_points))){
return GRADING_TYPE.POINTS;
} else if (gradingType.equals("gpa_scale") || gradingType.equals(context.getString(R.string.canvasAPI_gpaScale))){
return GRADING_TYPE.GPA_SCALE;
} else if(gradingType.equals("not_graded") || gradingType.equals(context.getString(R.string.canvasAPI_notGraded))){
return GRADING_TYPE.NOT_GRADED;
}else {
return null;
}
}
public static GRADING_TYPE getGradingTypeFromAPIString(String gradingType){
if(gradingType.equals("pass_fail")){
return GRADING_TYPE.PASS_FAIL;
} else if(gradingType.equals("percent")){
return GRADING_TYPE.PERCENT;
} else if(gradingType.equals("letter_grade")){
return GRADING_TYPE.LETTER_GRADE;
} else if (gradingType.equals("points")){
return GRADING_TYPE.POINTS;
} else if (gradingType.equals("gpa_scale")){
return GRADING_TYPE.GPA_SCALE;
} else if(gradingType.equals("not_graded")){
return GRADING_TYPE.NOT_GRADED;
}else{
return null;
}
}
public static String gradingTypeToAPIString(GRADING_TYPE gradingType){
if(gradingType == null){ return null;}
switch (gradingType){
case PASS_FAIL:
return "pass_fail";
case PERCENT:
return "percent";
case LETTER_GRADE:
return "letter_grade";
case POINTS:
return "points";
case GPA_SCALE:
return "gpa_scale";
case NOT_GRADED:
return "not_graded";
default:
return "";
}
}
public static String gradingTypeToPrettyPrintString(GRADING_TYPE gradingType, Context context){
if(gradingType == null){ return null;}
switch (gradingType){
case PASS_FAIL:
return context.getString(R.string.canvasAPI_passFail);
case PERCENT:
return context.getString(R.string.canvasAPI_percent);
case LETTER_GRADE:
return context.getString(R.string.canvasAPI_letterGrade);
case POINTS:
return context.getString(R.string.canvasAPI_points);
case GPA_SCALE:
return context.getString(R.string.canvasAPI_gpaScale);
case NOT_GRADED:
return context.getString(R.string.canvasAPI_notGraded);
default:
return "";
}
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.id);
dest.writeString(this.name);
dest.writeString(this.description);
dest.writeList(this.submission_types);
dest.writeString(this.due_at);
dest.writeDouble(this.points_possible);
dest.writeLong(this.course_id);
dest.writeString(this.grading_type);
dest.writeString(this.html_url);
dest.writeString(this.url);
dest.writeLong(this.quiz_id);
dest.writeList(this.rubric);
dest.writeByte(use_rubric_for_grading ? (byte) 1 : (byte) 0);
dest.writeList(this.allowed_extensions);
dest.writeParcelable(this.submission, flags);
dest.writeLong(this.assignment_group_id);
dest.writeByte(peer_reviews ? (byte) 1 : (byte) 0);
dest.writeParcelable(this.lock_info, flags);
dest.writeString(this.lock_at);
dest.writeString(this.unlock_at);
dest.writeParcelable(this.discussion_topic, flags);
dest.writeLong(this.needs_grading_count);
dest.writeList(this.needs_grading_count_by_section);
dest.writeByte(free_form_criterion_comments ? (byte) 1 : (byte) 0);
dest.writeByte(published ? (byte) 1 : (byte) 0);
dest.writeLong(this.group_category_id);
dest.writeList(this.all_dates);
dest.writeByte(this.muted ? (byte)1 : (byte) 0);
dest.writeByte(this.locked_for_user ? (byte)1 : (byte) 0);
}
private Assignment(Parcel in) {
this.id = in.readLong();
this.name = in.readString();
this.description = in.readString();
in.readList(this.submission_types, String.class.getClassLoader());
this.due_at = in.readString();
this.points_possible = in.readDouble();
this.course_id = in.readLong();
this.grading_type = in.readString();
this.html_url = in.readString();
this.url = in.readString();
this.quiz_id = in.readLong();
in.readList(this.rubric, RubricCriterion.class.getClassLoader());
this.use_rubric_for_grading = in.readByte() != 0;
in.readList(this.allowed_extensions, String.class.getClassLoader());
this.submission = in.readParcelable(Submission.class.getClassLoader());
this.assignment_group_id = in.readLong();
this.peer_reviews = in.readByte() != 0;
this.lock_info = in.readParcelable(LockInfo.class.getClassLoader());
this.lock_at = in.readString();
this.unlock_at = in.readString();
this.discussion_topic = in.readParcelable(DiscussionTopicHeader.class.getClassLoader());
this.needs_grading_count = in.readLong();
in.readList(this.needs_grading_count_by_section, NeedsGradingCount.class.getClassLoader());
this.free_form_criterion_comments = in.readByte() != 0;
this.published = in.readByte() != 0;
this.group_category_id = in.readLong();
in.readList(this.all_dates, AssignmentDueDate.class.getClassLoader());
this.muted = in.readByte() != 0;
this.locked_for_user = in.readByte() != 0;
}
public static Creator<Assignment> CREATOR = new Creator<Assignment>() {
public Assignment createFromParcel(Parcel source) {
return new Assignment(source);
}
public Assignment[] newArray(int size) {
return new Assignment[size];
}
};
} |
package com.qulice.ant;
import com.jcabi.log.Logger;
import com.qulice.checkstyle.CheckstyleValidator;
import com.qulice.codenarc.CodeNarcValidator;
import com.qulice.findbugs.FindBugsValidator;
import com.qulice.pmd.PMDValidator;
import com.qulice.spi.Environment;
import com.qulice.spi.ValidationException;
import com.qulice.spi.Validator;
import java.io.File;
import java.util.LinkedHashSet;
import java.util.Set;
import com.qulice.xml.XmlValidator;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Path;
/**
* Ant Task for Qulice.
*
* @checkstyle ClassDataAbstractionCouplingCheck (150 lines)
* @author Yuriy Alevohin (alevohin@mail.ru)
* @version $Id$
*/
public final class QuliceTask extends Task {
/**
* Sources dirs.
*/
private transient Path sources;
/**
* Classes dir (only one dir is supported).
*/
private transient File classes;
/**
* Classpath dirs and files.
*/
private transient Path classpath;
/**
* Set source dirs.
* @param srcdr Source dirs
*/
public void setSrcdir(final Path srcdr) {
this.sources = srcdr;
}
/**
* Set classes dir.
* @param clssedr Classes dir
*/
public void setClassesdir(final File clssedr) {
this.classes = clssedr;
}
/**
* Set classpath.
* @param clsspth Classpath
*/
public void setClasspath(final Path clsspth) {
this.classpath = clsspth;
}
@Override
public void execute() {
super.execute();
final Environment env = this.environment();
try {
final long start = System.nanoTime();
this.validate(env);
Logger.info(
this,
"Qulice quality check completed in %[nano]s",
System.nanoTime() - start
);
} catch (final ValidationException ex) {
Logger.info(
this,
"Read our quality policy: http:
);
throw new BuildException("Failure", ex);
}
}
/**
* Create Environment.
* @return Environment.
*/
private Environment environment() {
if (this.sources == null) {
throw new BuildException("srcdir not defined for QuliceTask");
}
if (this.classes == null) {
throw new BuildException("classesdir not defined for QuliceTask");
}
if (this.classpath == null) {
throw new BuildException("classpath not defined for QuliceTask");
}
return new AntEnvironment(
this.getProject(),
this.sources,
this.classes,
this.classpath
);
}
/**
* Validate and throws exception if there are any problems.
* @param env Environment
* @throws ValidationException If there are any problems.
*/
private void validate(final Environment env) throws ValidationException {
for (final Validator validator : this.validators()) {
validator.validate(env);
}
}
/**
* Create set of Validators.
* @return Set of Validators.
*/
private Set<Validator> validators() {
final Set<Validator> validators = new LinkedHashSet<Validator>();
validators.add(new CheckstyleValidator());
validators.add(new PMDValidator());
validators.add(new XmlValidator());
validators.add(new CodeNarcValidator());
validators.add(new FindBugsValidator());
return validators;
}
} |
package mm.tstring;
public class MemoryFileProvider implements IFileProvider
{
private Iterable<IFile> files;
private IFile tstringTable;
public MemoryFileProvider(IFile tstringTable, Iterable<IFile> files)
{
this.tstringTable = tstringTable;
this.files = files;
}
@Override
public boolean backupFiles()
{
return true;
}
@Override
public Iterable<IFile> getFiles()
{
return files;
}
@Override
public IFile getTStringTable()
{
return tstringTable;
}
} |
package org.mwc.cmap.core;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IOperationHistory;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.mwc.cmap.core.operations.DebriefActionWrapper;
import org.mwc.cmap.core.ui_support.SelectImportModeDialog;
import org.mwc.cmap.core.wizards.ImportRepFreqDialog;
import Debrief.ReaderWriter.Replay.ImportReplay;
import Debrief.ReaderWriter.Replay.ImportReplay.ProvidesModeSelector;
import MWC.GUI.ToolParent;
import MWC.GUI.Tools.Action;
import MWC.GUI.Tools.Palette.CreateVPFLayers;
/**
* @author ian.mayo
*/
public class DebriefToolParent implements ToolParent, ProvidesModeSelector
{
/**
* the set of preferences we support
*/
private final IPreferenceStore _myPrefs;
/**
* the undo buffer we support
*
*/
private final IOperationHistory _myUndo;
/**
* convenience object, used to get selected import mode back from the popup dialog
*
*/
private static ImportSettings _selectedImportSettings = null;
public DebriefToolParent(final IPreferenceStore prefs,
final IOperationHistory undoBuffer)
{
_myPrefs = prefs;
_myUndo = undoBuffer;
}
/**
* @param theCursor
*/
public void setCursor(final int theCursor)
{
}
public void restoreCursor()
{
}
/**
* @param theAction
*/
public void addActionToBuffer(final Action theAction)
{
// ok, better wrap the action first
final DebriefActionWrapper daw = new DebriefActionWrapper(theAction);
// now add it to the buffer (though we don't need to start with the activate
// bit)
try
{
_myUndo.execute(daw, null, null);
}
catch (final ExecutionException e)
{
CorePlugin.logError(Status.ERROR, "Executing newly added action", e);
}
}
/**
* @param name
* @return
*/
public String getProperty(final String name)
{
final String res = _myPrefs.getString(name);
return res;
}
/**
* @param pattern
* @return
*/
public Map<String, String> getPropertiesLike(final String pattern)
{
final Map<String, String> retMap = new HashMap<String, String>();
// SPECIAL PROCESSING. THE ONLY TIME WE USE CURRENTLY USE THIS IS FOR THE
// VPF PATHS
if (pattern.equals(CreateVPFLayers.VPF_DATABASE_PROPERTY))
{
for (int i = 1; i < 10; i++)
{
final String thisVPFPath = pattern + "." + i;
if (_myPrefs.contains(thisVPFPath))
{
// ok, has it been changed from the default?
if (!_myPrefs.isDefault(thisVPFPath))
retMap.put(thisVPFPath, _myPrefs.getString(thisVPFPath));
}
}
}
else
{
CorePlugin.logError(Status.ERROR,
"Should not be requesting patterned properties", null);
}
return retMap;
}
/**
* @param name
* @param value
*/
public void setProperty(final String name, final String value)
{
_myPrefs.putValue(name, value);
}
@Override
public void
logError(final int status, final String text, final Exception e, final boolean revealLog)
{
CorePlugin.logError(status, text, e);
// prompt Error Log view to user up on error report (if requested)
if (revealLog)
{
final Display current = Display.getDefault();
if (current != null)
{
final Runnable showLog = new Runnable()
{
@Override
public void run()
{
if (PlatformUI.getWorkbench() != null
&& PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null
&& PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage() != null)
{
try
{
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage()
.showView("org.eclipse.pde.runtime.LogView");
}
catch (PartInitException e1)
{
e1.printStackTrace();
}
}
}
};
current.asyncExec(showLog);
}
}
}
public void logError(final int status, final String text, final Exception e)
{
logError(status, text, e, false);
}
/**
* popup a dialog to let the user select the import mode
*
* @return selected mode, from ImportReplay
*/
@Override
public ImportSettings getSelectedImportMode(final String trackName)
{
_selectedImportSettings = null;
final Display current = Display.getDefault();
current.syncExec(new Runnable()
{
public void run()
{
final Shell active =
PlatformUI.getWorkbench().getWorkbenchWindows()[0].getShell();
// ok, popup our custom dialog, let user decide
final SelectImportModeDialog dialog =
new SelectImportModeDialog(active, trackName);
// store the value
_selectedImportSettings = dialog.open();
}
});
return _selectedImportSettings;
}
/**
* popup a dialog to let the user select the import mode
*
* @return selected mode, from ImportReplay
*/
@Override
public Long getSelectedImportFrequency(final String trackName)
{
_selectedImportSettings = null;
final Display current = Display.getDefault();
current.syncExec(new Runnable()
{
public void run()
{
final Shell active =
PlatformUI.getWorkbench().getWorkbenchWindows()[0].getShell();
// ok, popup our custom dialog, let user decide
final ImportRepFreqDialog dialog =
new ImportRepFreqDialog(active, trackName);
int sel = dialog.open();
if (sel != Dialog.CANCEL)
{
// store the value
long freq = dialog.getSampleFreq();
_selectedImportSettings =
new ImportSettings(ImportReplay.IMPORT_AS_OTG, freq);
}
}
});
Long res;
if (_selectedImportSettings != null)
{
res = _selectedImportSettings.sampleFrequency;
}
else
{
res = null;
}
return res;
}
@Override
public void logStack(int status, String text)
{
CorePlugin.logError(status, text, null, true);
}
} |
package com.lothrazar.powerinventory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import com.lothrazar.powerinventory.inventory.BigInventoryPlayer;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;
public class UtilInventory
{
public static ArrayList<BlockPos> findBlocks(EntityPlayer player, Block blockHunt, int RADIUS )
{
//function imported https://github.com/PrinceOfAmber/SamsPowerups/blob/master/Commands/src/main/java/com/lothrazar/samscommands/ModCommands.java#L193
ArrayList<BlockPos> found = new ArrayList<BlockPos>();
int xMin = (int) player.posX - RADIUS;
int xMax = (int) player.posX + RADIUS;
int yMin = (int) player.posY - RADIUS;
int yMax = (int) player.posY + RADIUS;
int zMin = (int) player.posZ - RADIUS;
int zMax = (int) player.posZ + RADIUS;
BlockPos posCurrent = null;
for (int xLoop = xMin; xLoop <= xMax; xLoop++)
{
for (int yLoop = yMin; yLoop <= yMax; yLoop++)
{
for (int zLoop = zMin; zLoop <= zMax; zLoop++)
{
posCurrent = new BlockPos(xLoop, yLoop, zLoop);
if(player.worldObj.getBlockState(posCurrent).getBlock().equals(blockHunt))
{
found.add(posCurrent);
}
}
}
}
return found;
}
public static ArrayList<IInventory> findTileEntityInventories(EntityPlayer player, int RADIUS )
{
//function imported https://github.com/PrinceOfAmber/SamsPowerups/blob/master/Commands/src/main/java/com/lothrazar/samscommands/ModCommands.java#L193
ArrayList<IInventory> found = new ArrayList<IInventory>();
int xMin = (int) player.posX - RADIUS;
int xMax = (int) player.posX + RADIUS;
int yMin = (int) player.posY - RADIUS;
int yMax = (int) player.posY + RADIUS;
int zMin = (int) player.posZ - RADIUS;
int zMax = (int) player.posZ + RADIUS;
BlockPos posCurrent = null;
for (int xLoop = xMin; xLoop <= xMax; xLoop++)
{
for (int yLoop = yMin; yLoop <= yMax; yLoop++)
{
for (int zLoop = zMin; zLoop <= zMax; zLoop++)
{
posCurrent = new BlockPos(xLoop, yLoop, zLoop);
if(player.worldObj.getTileEntity(posCurrent) instanceof IInventory)
{
found.add((IInventory)player.worldObj.getTileEntity(posCurrent));
}
}
}
}
return found;
}
/*
public static void moveallContainerToPlayer(EntityPlayer player,Container container) //W
{
ItemStack source,destination;
int cont = 0;
for(int ip = Const.hotbarSize; ip < player.inventory.getSizeInventory() - Const.armorSize; ip++)
{
for(int i = cont; i < container.getInventory().size(); i++)
{
if(container.getSlot(i).getHasStack() == false || container.getSlot(i).getStack() == null){continue;}
destination = player.inventory.getStackInSlot(ip);
source = container.getSlot(i).getStack();
if(destination == null)
{
player.inventory.setInventorySlotContents(ip, source);
player.inventoryContainer.getSlot(ip).putStack(source);
player.inventoryContainer.detectAndSendChanges();
container.getSlot(i).putStack(null);
// okay, now we are done with source
//start at the next one later
}
else
{
if(destination.stackSize == destination.getMaxStackSize()){break;}//if its full, we are done already, break inner loop only
if(source.isItemEqual(destination)) //do we match?
{
//tried to find a way to share code here between this and the opposite method
//but not there yet.. copy paste works though
int room = destination.getMaxStackSize() - destination.stackSize;
if(room > 0)
{
int toDeposit = Math.min(room, source.stackSize);
//so if they have room for 52, then room for 12, and we have 55,
//so toDeposit is only 12 and we take that off the 55 in player invo
destination.stackSize += toDeposit;
player.inventoryContainer.getSlot(ip).putStack(destination);
//now decrement source
if(source.stackSize - toDeposit == 0)
{
container.getSlot(i).putStack(null);
}
else
{
source.stackSize -= toDeposit;
container.getSlot(i).putStack(source);
}
}
}
}
}
}
}*/
//TODO: refactor above and below to share code, code reuse, find some generic bits ?
//they are /almost/ copy-pastes in reverse of each other
/*
public static void moveallPlayerToContainer(EntityPlayer player, Container container)//D
{
ItemStack source,destination;
for(int i = 0; i < container.getInventory().size(); i++)
{
for(int ip = Const.hotbarSize; ip < player.inventory.getSizeInventory() - Const.armorSize; ip++)
{
source = player.inventory.getStackInSlot(ip);
if(source == null){continue;}
if(container.getSlot(i).getHasStack() == false && //its empty, dump away
container.getSlot(i).isItemValid(source)) //intended to validate furnace/brewing slot rules
{
container.getSlot(i).putStack(source);
player.inventory.setInventorySlotContents(ip, null);//and remove it from player inventory
}
else
{
destination = container.getSlot(i).getStack();
if(destination.stackSize == destination.getMaxStackSize()) {continue;}
if(source.isItemEqual(destination))//here.getItem() == splayer.getItem() && here.getMetadata() == splayer.getMetadata())
{
//so i have a non-empty, non-full stack, and a matching stack in player inventory
int room = destination.getMaxStackSize() - destination.stackSize;
if(room > 0)
{
int toDeposit = Math.min(room, source.stackSize);
//so if they have room for 52, then room for 12, and we have 55,
//so toDeposit is only 12 and we take that off the 55 in player invo
destination.stackSize += toDeposit;
container.getSlot(i).putStack(destination);
//
if(source.stackSize - toDeposit == 0)
{
player.inventory.setInventorySlotContents(ip, null);
}
else
{
source.stackSize -= toDeposit;
player.inventory.setInventorySlotContents(ip, source);
}
}
}
}
}
}
}*/
public static void dumpFromPlayerToChestEntity(World world, TileEntityChest chest, EntityPlayer player)
{
ItemStack chestItem;
ItemStack invItem;
int START_CHEST = 0;
int END_CHEST = START_CHEST + 3*9;
//inventory and chest has 9 rows by 3 columns, never changes. same as 64 max stack size
for(int islotChest = START_CHEST; islotChest < END_CHEST; islotChest++)
{
chestItem = chest.getStackInSlot(islotChest);
if(chestItem != null) { continue; }// chest slot not empty, skip over it
for(int islotInv = Const.HOTBAR_SIZE; islotInv < getInvoEnd(player); islotInv++)
{
invItem = player.inventory.getStackInSlot(islotInv);
if(invItem == null) {continue;}//empty inventory slot
chest.setInventorySlotContents(islotChest, invItem);
player.inventory.setInventorySlotContents(islotInv,null);
break;
}//close loop on player inventory items
}//close loop on chest items
}
public static void dumpFromPlayerToIInventory(World world, IInventory inventory, EntityPlayer player)
{
ItemStack chestItem;
ItemStack invItem;
int start = 0;
//inventory and chest has 9 rows by 3 columns, never changes. same as 64 max stack size
for(int slot = start; slot < inventory.getSizeInventory(); slot++)
{
chestItem = inventory.getStackInSlot(slot);
if(chestItem != null) { continue; }// slot not empty, skip over it
for(int islotInv = Const.HOTBAR_SIZE; islotInv < getInvoEnd(player); islotInv++)
{
invItem = player.inventory.getStackInSlot(islotInv);
if(invItem == null) {continue;}//empty inventory slot
inventory.setInventorySlotContents(slot, invItem);
player.inventory.setInventorySlotContents(islotInv,null);
break;
}//close loop on player inventory items
}//close loop on chest items
}
public static void sortFromPlayerToInventory(World world, IInventory chest, EntityPlayer player)
{
//source: https://github.com/PrinceOfAmber/SamsPowerups/blob/master/Spells/src/main/java/com/lothrazar/samsmagic/spell/SpellChestDeposit.java#L84
ItemStack chestItem;
ItemStack invItem;
int room;
int toDeposit;
int chestMax;
//player inventory and the small chest have the same dimensions
int START_CHEST = 0;
int END_CHEST = chest.getSizeInventory();
//inventory and chest has 9 rows by 3 columns, never changes. same as 64 max stack size
for(int islotChest = START_CHEST; islotChest < END_CHEST; islotChest++)
{
chestItem = chest.getStackInSlot(islotChest);
if(chestItem == null) { continue; }// empty chest slot
for(int islotInv = Const.HOTBAR_SIZE; islotInv < getInvoEnd(player); islotInv++)
{
invItem = player.inventory.getStackInSlot(islotInv);
if(invItem == null) {continue;}//empty inventory slot
if( invItem.getItem().equals(chestItem.getItem()) && invItem.getItemDamage() == chestItem.getItemDamage() )
{
//same item, including damage (block state)
chestMax = chestItem.getItem().getItemStackLimit(chestItem);
room = chestMax - chestItem.stackSize;
if(room <= 0) {continue;} // no room, check the next spot
//so if i have 30 room, and 28 items, i deposit 28.
//or if i have 30 room and 38 items, i deposit 30
toDeposit = Math.min(invItem.stackSize,room);
chestItem.stackSize += toDeposit;
chest.setInventorySlotContents(islotChest, chestItem);
invItem.stackSize -= toDeposit;
if(invItem.stackSize <= 0)//because of calculations above, should not be below zero
{
//item stacks with zero count do not destroy themselves, they show up and have unexpected behavior in game so set to empty
player.inventory.setInventorySlotContents(islotInv,null);
}
else
{
//set to new quantity
player.inventory.setInventorySlotContents(islotInv, invItem);
}
}//end if items match
}//close loop on player inventory items
}//close loop on chest items
}
public static void shiftRightAll(InventoryPlayer invo)
{
Queue<Integer> empty = new LinkedList<Integer>();
ItemStack item;
for(int i = getInvoEnd(invo.player) - 1; i >= Const.HOTBAR_SIZE;i
{
item = invo.getStackInSlot(i);
if(item == null)
{
empty.add(i);
}
else
{
//find an empty spot for it
if(empty.size() > 0 && empty.peek() > i)
{
//poll remove it since its not empty anymore
moveFromTo(invo,i,empty.poll());
empty.add(i);
}
}
}
}
public static void shiftLeftAll(InventoryPlayer invo)
{
Queue<Integer> empty = new LinkedList<Integer>();
ItemStack item;
int max;
for(int i = Const.HOTBAR_SIZE; i < getInvoEnd(invo.player);i++)
{
item = invo.getStackInSlot(i);
if(item == null)
{
empty.add(i);
}
else //find an empty spot for it
{
if(empty.size() > 0 && empty.peek() < i)
{
//poll remove it since its not empty anymore
moveFromTo(invo,i,empty.poll());
empty.add(i);
}
}
}
}
/**
* WARNING: it assumes that 'to' is already empty, and overwrites it. sets 'from' to empty for you
* @param invo
* @param from
* @param to
*/
public static void moveFromTo(InventoryPlayer invo,int from, int to)
{
invo.setInventorySlotContents(to, invo.getStackInSlot(from));
invo.setInventorySlotContents(from, null);
}
/*
public static void shiftRightOne(InventoryPlayer invo)
{
int iEmpty = -1;
ItemStack item = null;
//0 to 8 is crafting
//armor is 384-387
for(int i = invo.getSizeInventory() - (Const.armorSize + 1); i >= Const.hotbarSize;i--)//388-4 384
{
item = invo.getStackInSlot(i);
if(item == null)
{
iEmpty = i;
}
else if(iEmpty > 0) //move i into iEmpty
{
moveFromTo(invo,i,iEmpty);
iEmpty = i;
}//else keep looking
}
}*/
public static void shiftRightOne(InventoryPlayer invo)
{
Map<Integer,ItemStack> newLocations = new HashMap<Integer,ItemStack>();
int iNew;
int END = getInvoEnd(invo.player);
for(int i = Const.HOTBAR_SIZE; i < END;i++)
{
if(i == END-1) iNew = Const.HOTBAR_SIZE;
else iNew = i + 1;
newLocations.put((Integer)iNew, invo.getStackInSlot(i));
}
for (Map.Entry<Integer,ItemStack> entry : newLocations.entrySet())
{
invo.setInventorySlotContents(entry.getKey().intValue(),entry.getValue());
}
}
public static void shiftLeftOne(InventoryPlayer invo)
{
//int iEmpty = -1;
//ItemStack item = null;
Map<Integer,ItemStack> newLocations = new HashMap<Integer,ItemStack>();
int iNew;
int END = getInvoEnd(invo.player);
for(int i = Const.HOTBAR_SIZE; i < END;i++)
{
if(i == Const.HOTBAR_SIZE) iNew = END-1;
else iNew = i - 1;
newLocations.put((Integer)iNew, invo.getStackInSlot(i));
//newLocations.set(iNew, invo.getStackInSlot(i));
/*
item = invo.getStackInSlot(i);
if(item == null)
{
iEmpty = i;
}
else if(iEmpty > 0)
{
moveFromTo(invo,i,iEmpty);
iEmpty = i;
}*/
}
for (Map.Entry<Integer,ItemStack> entry : newLocations.entrySet())
{
// System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
invo.setInventorySlotContents(entry.getKey().intValue(),entry.getValue());
}
}
final static String NBT_SORT = Const.MODID+"_sort";
final static int SORT_ALPH = 0;
final static int SORT_ALPHI = 1;
private static int getNextSort(EntityPlayer p)
{
int prev = p.getEntityData().getInteger(NBT_SORT);
int n = prev+1;
if(n>=2)n=0;
p.getEntityData().setInteger(NBT_SORT,n);
return n;
}
public static void sort(InventoryPlayer invo)
{
int sortType = getNextSort(invo.player);
int iSize = getInvoEnd(invo.player);
Map<String,SortGroup> unames = new HashMap<String,SortGroup>();
ItemStack item = null;
SortGroup temp;
String key = "";
for(int i = Const.HOTBAR_SIZE; i < iSize;i++)
{
item = invo.getStackInSlot(i);
if(item == null){continue;}
if(sortType == SORT_ALPH)
key = item.getUnlocalizedName() + item.getItemDamage();
else if(sortType == SORT_ALPHI)
key = item.getItem().getClass().getName() + item.getUnlocalizedName()+ item.getItemDamage();
//else if(sortType == SORT_CLASS)
// key = item.getItem().getClass().getName()+ item.getItemDamage();
temp = unames.get(key);
if(temp == null) {temp = new SortGroup(key);}
if(temp.stacks.size() > 0)
{
//try to merge with top
ItemStack top = temp.stacks.remove(temp.stacks.size()-1);
int room = top.getMaxStackSize() - top.stackSize;
if(room > 0)
{
int moveover = Math.min(item.stackSize,room);
top.stackSize += moveover;
item.stackSize -= moveover;
if(item.stackSize == 0)
{
item = null;
invo.setInventorySlotContents(i, item);
}
}
temp.stacks.add(top);
}
if(item != null)
temp.add(item);
unames.put(key,temp);
}
ArrayList<SortGroup> sorted = new ArrayList<SortGroup>(unames.values());
Collections.sort(sorted, new Comparator<SortGroup>()
{
public int compare(SortGroup o1, SortGroup o2)
{
return o1.key.compareTo(o2.key);
}
});
int k = Const.HOTBAR_SIZE;
for (SortGroup p : sorted)
{
//System.out.println(p.key+" "+p.stacks.size());
for(int i = 0; i < p.stacks.size(); i++)
{
invo.setInventorySlotContents(k, null);
invo.setInventorySlotContents(k, p.stacks.get(i));
k++;
}
}
for(int j = k; j < iSize; j++)
{
invo.setInventorySlotContents(j, null);
}
//alternately loop by rows
//so we start at k again, add Const.ALL_COLS to go down one row
}
private static int getInvoEnd(EntityPlayer p)
{
if(ModConfig.enableCompatMode)
return p.inventory.getSizeInventory() - Const.ARMOR_SIZE;
else //because of second hotbar
return p.inventory.getSizeInventory() - Const.ARMOR_SIZE - Const.HOTBAR_SIZE;
}
public static void doSort(EntityPlayer p,int sortType)
{
InventoryPlayer invo = p.inventory;
switch(sortType)
{
case Const.SORT_LEFT:
UtilInventory.shiftLeftOne(invo);
break;
case Const.SORT_RIGHT:
UtilInventory.shiftRightOne(invo);
break;
case Const.SORT_LEFTALL:
UtilInventory.shiftLeftAll(invo);
break;
case Const.SORT_RIGHTALL:
UtilInventory.shiftRightAll(invo);
break;
case Const.SORT_SMART:
UtilInventory.sort(invo);
break;
}
return ;
}
} |
package org.lightmare.entities;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.lightmare.annotations.UnitName;
import org.lightmare.jpa.hibernate.id.enhanced.TableGeneratorExt;
import org.lightmare.rest.providers.RestProvider;
@Entity
@Table(name = "PERSONS", schema = "PERSONS")
@UnitName("testUnit")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "org.lightmare.entities.Person")
@GenericGenerator(name = "org.lightmare.entities.Person", strategy = TableGeneratorExt.STRATEGY, parameters = {
@Parameter(name = "table_name", value = "ID_GENERATORS"),
@Parameter(name = "segment_column_name", value = "TABLE_NAME"),
@Parameter(name = "segment_value", value = "PERSONS"),
@Parameter(name = "value_column_name", value = "KEY_VALUE")
// ,@Parameter(name = "increment_size", value = "20")
})
// @TableGenerator(name = "ge.gov.mia.lightmare.entities.Person", table =
// "ID_GENERATORS", pkColumnName = "TABLE_NAME", pkColumnValue = "PERSONS",
// valueColumnName = "KEY_VALUE", allocationSize = 20)
@Column(name = "person_id", nullable = true)
private Integer personId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "address_line1")
private String addressLine1;
@Column(name = "address_line2")
private String addressLine2;
@Column(name = "birth_date")
private Date birthDate;
@Column(name = "total_salary")
private Integer totalSalary;
@Column(name = "gender")
private String gender;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = Email.class)
@JoinColumn(name = "PERSON_ID", referencedColumnName = "PERSON_ID")
private Set<Email> emails;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = PhoneNumber.class)
@JoinColumn(name = "PERSON_ID", referencedColumnName = "PERSON_ID")
private Set<PhoneNumber> phoneNumbers;
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public Date getBirthDate() {
return birthDate;
}
public Set<Email> getEmails() {
return emails;
}
public String getFirstName() {
return firstName;
}
public String getGender() {
return gender;
}
public String getLastName() {
return lastName;
}
public Integer getPersonId() {
return personId;
}
public Set<PhoneNumber> getPhoneNumbers() {
return phoneNumbers;
}
public Integer getTotalSalary() {
return totalSalary;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public void setEmails(Set<Email> emails) {
this.emails = emails;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPersonId(Integer personId) {
this.personId = personId;
}
public void setPhoneNumbers(Set<PhoneNumber> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public void setTotalSalary(Integer totalSalary) {
this.totalSalary = totalSalary;
}
public static Person valueOf(String json) {
Person person = null;
try {
person = RestProvider.convert(json, Person.class);
} catch (IOException ex) {
ex.printStackTrace();
}
return person;
}
} |
package bisq.network.p2p.storage;
import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.network.CloseConnectionReason;
import bisq.network.p2p.network.Connection;
import bisq.network.p2p.network.ConnectionListener;
import bisq.network.p2p.network.MessageListener;
import bisq.network.p2p.network.NetworkNode;
import bisq.network.p2p.peers.BroadcastHandler;
import bisq.network.p2p.peers.Broadcaster;
import bisq.network.p2p.storage.messages.AddDataMessage;
import bisq.network.p2p.storage.messages.AddOncePayload;
import bisq.network.p2p.storage.messages.AddPersistableNetworkPayloadMessage;
import bisq.network.p2p.storage.messages.BroadcastMessage;
import bisq.network.p2p.storage.messages.RefreshOfferMessage;
import bisq.network.p2p.storage.messages.RemoveDataMessage;
import bisq.network.p2p.storage.messages.RemoveMailboxDataMessage;
import bisq.network.p2p.storage.payload.DateTolerantPayload;
import bisq.network.p2p.storage.payload.ExpirablePayload;
import bisq.network.p2p.storage.payload.MailboxStoragePayload;
import bisq.network.p2p.storage.payload.PersistableNetworkPayload;
import bisq.network.p2p.storage.payload.ProtectedMailboxStorageEntry;
import bisq.network.p2p.storage.payload.ProtectedStorageEntry;
import bisq.network.p2p.storage.payload.ProtectedStoragePayload;
import bisq.network.p2p.storage.payload.RequiresOwnerIsOnlinePayload;
import bisq.network.p2p.storage.persistence.AppendOnlyDataStoreListener;
import bisq.network.p2p.storage.persistence.AppendOnlyDataStoreService;
import bisq.network.p2p.storage.persistence.ProtectedDataStoreListener;
import bisq.network.p2p.storage.persistence.ProtectedDataStoreService;
import bisq.network.p2p.storage.persistence.ResourceDataStoreService;
import bisq.network.p2p.storage.persistence.SequenceNumberMap;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.crypto.CryptoException;
import bisq.common.crypto.Hash;
import bisq.common.crypto.Sig;
import bisq.common.proto.network.NetworkEnvelope;
import bisq.common.proto.network.NetworkPayload;
import bisq.common.proto.persistable.PersistablePayload;
import bisq.common.proto.persistable.PersistedDataHost;
import bisq.common.storage.Storage;
import bisq.common.util.Hex;
import bisq.common.util.Tuple2;
import bisq.common.util.Utilities;
import com.google.protobuf.ByteString;
import javax.inject.Inject;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang3.StringUtils;
import java.security.KeyPair;
import java.security.PublicKey;
import java.time.Clock;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
@Slf4j
public class P2PDataStorage implements MessageListener, ConnectionListener, PersistedDataHost {
/**
* How many days to keep an entry before it is purged.
*/
private static final int PURGE_AGE_DAYS = 10;
@VisibleForTesting
public static int CHECK_TTL_INTERVAL_SEC = 60;
private final Broadcaster broadcaster;
private final AppendOnlyDataStoreService appendOnlyDataStoreService;
private final ProtectedDataStoreService protectedDataStoreService;
private final ResourceDataStoreService resourceDataStoreService;
@Getter
private final Map<ByteArray, ProtectedStorageEntry> map = new ConcurrentHashMap<>();
private final Set<ByteArray> removedAddOncePayloads = new HashSet<>();
private final Set<HashMapChangedListener> hashMapChangedListeners = new CopyOnWriteArraySet<>();
private Timer removeExpiredEntriesTimer;
private final Storage<SequenceNumberMap> sequenceNumberMapStorage;
private final SequenceNumberMap sequenceNumberMap = new SequenceNumberMap();
private final Set<AppendOnlyDataStoreListener> appendOnlyDataStoreListeners = new CopyOnWriteArraySet<>();
private final Set<ProtectedDataStoreListener> protectedDataStoreListeners = new CopyOnWriteArraySet<>();
private final Clock clock;
// Constructor
@Inject
public P2PDataStorage(NetworkNode networkNode,
Broadcaster broadcaster,
AppendOnlyDataStoreService appendOnlyDataStoreService,
ProtectedDataStoreService protectedDataStoreService,
ResourceDataStoreService resourceDataStoreService,
Storage<SequenceNumberMap> sequenceNumberMapStorage,
Clock clock) {
this.broadcaster = broadcaster;
this.appendOnlyDataStoreService = appendOnlyDataStoreService;
this.protectedDataStoreService = protectedDataStoreService;
this.resourceDataStoreService = resourceDataStoreService;
this.clock = clock;
networkNode.addMessageListener(this);
networkNode.addConnectionListener(this);
this.sequenceNumberMapStorage = sequenceNumberMapStorage;
sequenceNumberMapStorage.setNumMaxBackupFiles(5);
}
@Override
public void readPersisted() {
SequenceNumberMap persistedSequenceNumberMap = sequenceNumberMapStorage.initAndGetPersisted(sequenceNumberMap, 300);
if (persistedSequenceNumberMap != null)
sequenceNumberMap.setMap(getPurgedSequenceNumberMap(persistedSequenceNumberMap.getMap()));
}
// This method is called at startup in a non-user thread.
// We should not have any threading issues here as the p2p network is just initializing
public synchronized void readFromResources(String postFix) {
appendOnlyDataStoreService.readFromResources(postFix);
protectedDataStoreService.readFromResources(postFix);
resourceDataStoreService.readFromResources(postFix);
map.putAll(protectedDataStoreService.getMap());
}
// API
public void shutDown() {
if (removeExpiredEntriesTimer != null)
removeExpiredEntriesTimer.stop();
}
public void onBootstrapComplete() {
removeExpiredEntriesTimer = UserThread.runPeriodically(() -> {
log.trace("removeExpiredEntries");
// The moment when an object becomes expired will not be synchronous in the network and we could
// get add network_messages after the object has expired. To avoid repeated additions of already expired
// That way an ADD message for an already expired data will fail because the sequence number
// is equal and not larger as expected.
Map<ByteArray, ProtectedStorageEntry> temp = new HashMap<>(map);
Set<ProtectedStorageEntry> toRemoveSet = new HashSet<>();
temp.entrySet().stream()
.filter(entry -> entry.getValue().isExpired())
.forEach(entry -> {
ByteArray hashOfPayload = entry.getKey();
ProtectedStorageEntry protectedStorageEntry = map.get(hashOfPayload);
if (!(protectedStorageEntry.getProtectedStoragePayload() instanceof PersistableNetworkPayload)) {
toRemoveSet.add(protectedStorageEntry);
log.debug("We found an expired data entry. We remove the protectedData:\n\t" + Utilities.toTruncatedString(protectedStorageEntry));
map.remove(hashOfPayload);
}
});
// Batch processing can cause performance issues, so we give listeners a chance to deal with it by notifying
// about start and end of iteration.
hashMapChangedListeners.forEach(HashMapChangedListener::onBatchRemoveExpiredDataStarted);
toRemoveSet.forEach(protectedStorageEntry -> {
hashMapChangedListeners.forEach(l -> l.onRemoved(protectedStorageEntry));
removeFromProtectedDataStore(protectedStorageEntry);
});
hashMapChangedListeners.forEach(HashMapChangedListener::onBatchRemoveExpiredDataCompleted);
if (sequenceNumberMap.size() > 1000)
sequenceNumberMap.setMap(getPurgedSequenceNumberMap(sequenceNumberMap.getMap()));
}, CHECK_TTL_INTERVAL_SEC);
}
public Map<ByteArray, PersistableNetworkPayload> getAppendOnlyDataStoreMap() {
return appendOnlyDataStoreService.getMap();
}
public Map<P2PDataStorage.ByteArray, ProtectedStorageEntry> getProtectedDataStoreMap() {
return protectedDataStoreService.getMap();
}
// MessageListener implementation
@Override
public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) {
if (networkEnvelope instanceof BroadcastMessage) {
connection.getPeersNodeAddressOptional().ifPresent(peersNodeAddress -> {
if (networkEnvelope instanceof AddDataMessage) {
addProtectedStorageEntry(((AddDataMessage) networkEnvelope).getProtectedStorageEntry(), peersNodeAddress, null, false);
} else if (networkEnvelope instanceof RemoveDataMessage) {
remove(((RemoveDataMessage) networkEnvelope).getProtectedStorageEntry(), peersNodeAddress, false);
} else if (networkEnvelope instanceof RemoveMailboxDataMessage) {
removeMailboxData(((RemoveMailboxDataMessage) networkEnvelope).getProtectedMailboxStorageEntry(), peersNodeAddress, false);
} else if (networkEnvelope instanceof RefreshOfferMessage) {
refreshTTL((RefreshOfferMessage) networkEnvelope, peersNodeAddress, false);
} else if (networkEnvelope instanceof AddPersistableNetworkPayloadMessage) {
addPersistableNetworkPayload(((AddPersistableNetworkPayloadMessage) networkEnvelope).getPersistableNetworkPayload(),
peersNodeAddress, false, true, false, true);
}
});
}
}
// ConnectionListener implementation
@Override
public void onConnection(Connection connection) {
}
@Override
public void onDisconnect(CloseConnectionReason closeConnectionReason, Connection connection) {
if (connection.hasPeersNodeAddress() && !closeConnectionReason.isIntended) {
map.values()
.forEach(protectedStorageEntry -> {
NetworkPayload networkPayload = protectedStorageEntry.getProtectedStoragePayload();
if (networkPayload instanceof ExpirablePayload && networkPayload instanceof RequiresOwnerIsOnlinePayload) {
NodeAddress ownerNodeAddress = ((RequiresOwnerIsOnlinePayload) networkPayload).getOwnerNodeAddress();
if (connection.getPeersNodeAddressOptional().isPresent() &&
ownerNodeAddress.equals(connection.getPeersNodeAddressOptional().get())) {
// We have a RequiresLiveOwnerData data object with the node address of the
// disconnected peer. We remove that data from our map.
// Check if we have the data (e.g. OfferPayload)
ByteArray hashOfPayload = get32ByteHashAsByteArray(networkPayload);
boolean containsKey = map.containsKey(hashOfPayload);
if (containsKey) {
log.debug("We remove the data as the data owner got disconnected with " +
"closeConnectionReason=" + closeConnectionReason);
// We only set the data back by half of the TTL and remove the data only if is has
// expired after that back dating.
// We might get connection drops which are not caused by the node going offline, so
// we give more tolerance with that approach, giving the node the change to
// refresh the TTL with a refresh message.
// We observed those issues during stress tests, but it might have been caused by the
// test set up (many nodes/connections over 1 router)
// TODO investigate what causes the disconnections.
// Usually the are: SOCKET_TIMEOUT ,TERMINATED (EOFException)
protectedStorageEntry.backDate();
if (protectedStorageEntry.isExpired()) {
log.info("We found an expired data entry which we have already back dated. " +
"We remove the protectedStoragePayload:\n\t" + Utilities.toTruncatedString(protectedStorageEntry.getProtectedStoragePayload(), 100));
doRemoveProtectedExpirableData(protectedStorageEntry, hashOfPayload);
}
} else {
log.debug("Remove data ignored as we don't have an entry for that data.");
}
}
}
});
}
}
@Override
public void onError(Throwable throwable) {
}
// API
public boolean addPersistableNetworkPayload(PersistableNetworkPayload payload,
@Nullable NodeAddress sender,
boolean isDataOwner,
boolean allowBroadcast,
boolean reBroadcast,
boolean checkDate) {
log.trace("addPersistableNetworkPayload payload={}", payload);
byte[] hash = payload.getHash();
if (payload.verifyHashSize()) {
ByteArray hashAsByteArray = new ByteArray(hash);
boolean containsKey = getAppendOnlyDataStoreMap().containsKey(hashAsByteArray);
if (!containsKey || reBroadcast) {
if (!(payload instanceof DateTolerantPayload) || !checkDate || ((DateTolerantPayload) payload).isDateInTolerance(clock)) {
if (!containsKey) {
appendOnlyDataStoreService.put(hashAsByteArray, payload);
appendOnlyDataStoreListeners.forEach(e -> e.onAdded(payload));
}
if (allowBroadcast)
broadcaster.broadcast(new AddPersistableNetworkPayloadMessage(payload), sender, null, isDataOwner);
return true;
} else {
log.warn("Publish date of payload is not matching our current time and outside of our tolerance.\n" +
"Payload={}; now={}", payload.toString(), new Date());
return false;
}
} else {
log.trace("We have that payload already in our map.");
return false;
}
} else {
log.warn("We got a hash exceeding our permitted size");
return false;
}
}
// When we receive initial data we skip several checks to improve performance. We requested only missing entries so we
// do not need to check again if the item is contained in the map, which is a bit slow as the map can be very large.
// Overwriting an entry would be also no issue. We also skip notifying listeners as we get called before the domain
// is ready so no listeners are set anyway. We might get called twice from a redundant call later, so listeners
// might be added then but as we have the data already added calling them would be irrelevant as well.
// TODO find a way to avoid the second call...
public boolean addPersistableNetworkPayloadFromInitialRequest(PersistableNetworkPayload payload) {
byte[] hash = payload.getHash();
if (payload.verifyHashSize()) {
ByteArray hashAsByteArray = new ByteArray(hash);
appendOnlyDataStoreService.put(hashAsByteArray, payload);
return true;
} else {
log.warn("We got a hash exceeding our permitted size");
return false;
}
}
public boolean addProtectedStorageEntry(ProtectedStorageEntry protectedStorageEntry, @Nullable NodeAddress sender,
@Nullable BroadcastHandler.Listener listener, boolean isDataOwner) {
return addProtectedStorageEntry(protectedStorageEntry, sender, listener, isDataOwner, true);
}
public boolean addProtectedStorageEntry(ProtectedStorageEntry protectedStorageEntry,
@Nullable NodeAddress sender,
@Nullable BroadcastHandler.Listener listener,
boolean isDataOwner,
boolean allowBroadcast) {
ProtectedStoragePayload protectedStoragePayload = protectedStorageEntry.getProtectedStoragePayload();
ByteArray hashOfPayload = get32ByteHashAsByteArray(protectedStoragePayload);
if (protectedStoragePayload instanceof AddOncePayload &&
removedAddOncePayloads.contains(hashOfPayload)) {
log.warn("We have already removed that AddOncePayload by a previous removeDataMessage. " +
"We ignore that message. ProtectedStoragePayload: {}", protectedStoragePayload.toString());
return false;
}
boolean sequenceNrValid = isSequenceNrValid(protectedStorageEntry.getSequenceNumber(), hashOfPayload);
boolean result = sequenceNrValid &&
checkPublicKeys(protectedStorageEntry, true)
&& checkSignature(protectedStorageEntry);
boolean containsKey = map.containsKey(hashOfPayload);
if (containsKey) {
result = result && checkIfStoredDataPubKeyMatchesNewDataPubKey(protectedStorageEntry.getOwnerPubKey(), hashOfPayload);
}
// printData("before add");
if (result) {
boolean hasSequenceNrIncreased = hasSequenceNrIncreased(protectedStorageEntry.getSequenceNumber(), hashOfPayload);
if (!containsKey || hasSequenceNrIncreased) {
// At startup we don't have the item so we store it. At updates of the seq nr we store as well.
map.put(hashOfPayload, protectedStorageEntry);
hashMapChangedListeners.forEach(e -> e.onAdded(protectedStorageEntry));
// printData("after add");
} else {
log.trace("We got that version of the data already, so we don't store it.");
}
if (hasSequenceNrIncreased) {
sequenceNumberMap.put(hashOfPayload, new MapValue(protectedStorageEntry.getSequenceNumber(), System.currentTimeMillis()));
// We set the delay higher as we might receive a batch of items
sequenceNumberMapStorage.queueUpForSave(SequenceNumberMap.clone(sequenceNumberMap), 2000);
if (allowBroadcast)
broadcastProtectedStorageEntry(protectedStorageEntry, sender, listener, isDataOwner);
} else {
log.trace("We got that version of the data already, so we don't broadcast it.");
}
if (protectedStoragePayload instanceof PersistablePayload) {
ByteArray compactHash = getCompactHashAsByteArray(protectedStoragePayload);
ProtectedStorageEntry previous = protectedDataStoreService.putIfAbsent(compactHash, protectedStorageEntry);
if (previous == null)
protectedDataStoreListeners.forEach(e -> e.onAdded(protectedStorageEntry));
}
} else {
log.trace("add failed");
}
return result;
}
private void broadcastProtectedStorageEntry(ProtectedStorageEntry protectedStorageEntry,
@Nullable NodeAddress sender,
@Nullable BroadcastHandler.Listener broadcastListener,
boolean isDataOwner) {
broadcast(new AddDataMessage(protectedStorageEntry), sender, broadcastListener, isDataOwner);
}
public boolean refreshTTL(RefreshOfferMessage refreshTTLMessage,
@Nullable NodeAddress sender,
boolean isDataOwner) {
ByteArray hashOfPayload = new ByteArray(refreshTTLMessage.getHashOfPayload());
if (map.containsKey(hashOfPayload)) {
ProtectedStorageEntry storedData = map.get(hashOfPayload);
int sequenceNumber = refreshTTLMessage.getSequenceNumber();
if (sequenceNumberMap.containsKey(hashOfPayload) && sequenceNumberMap.get(hashOfPayload).sequenceNr == sequenceNumber) {
log.trace("We got that message with that seq nr already from another peer. We ignore that message.");
return true;
} else {
PublicKey ownerPubKey = storedData.getProtectedStoragePayload().getOwnerPubKey();
byte[] hashOfDataAndSeqNr = refreshTTLMessage.getHashOfDataAndSeqNr();
byte[] signature = refreshTTLMessage.getSignature();
// printData("before refreshTTL");
if (hasSequenceNrIncreased(sequenceNumber, hashOfPayload) &&
checkIfStoredDataPubKeyMatchesNewDataPubKey(ownerPubKey, hashOfPayload) &&
checkSignature(ownerPubKey, hashOfDataAndSeqNr, signature)) {
log.debug("refreshDate called for storedData:\n\t" + StringUtils.abbreviate(storedData.toString(), 100));
storedData.refreshTTL();
storedData.updateSequenceNumber(sequenceNumber);
storedData.updateSignature(signature);
printData("after refreshTTL");
sequenceNumberMap.put(hashOfPayload, new MapValue(sequenceNumber, System.currentTimeMillis()));
sequenceNumberMapStorage.queueUpForSave(SequenceNumberMap.clone(sequenceNumberMap), 1000);
broadcast(refreshTTLMessage, sender, null, isDataOwner);
return true;
}
return false;
}
} else {
log.debug("We don't have data for that refresh message in our map. That is expected if we missed the data publishing.");
return false;
}
}
public boolean remove(ProtectedStorageEntry protectedStorageEntry,
@Nullable NodeAddress sender,
boolean isDataOwner) {
ProtectedStoragePayload protectedStoragePayload = protectedStorageEntry.getProtectedStoragePayload();
ByteArray hashOfPayload = get32ByteHashAsByteArray(protectedStoragePayload);
boolean containsKey = map.containsKey(hashOfPayload);
if (!containsKey)
log.debug("Remove data ignored as we don't have an entry for that data.");
boolean result = containsKey
&& checkPublicKeys(protectedStorageEntry, false)
&& isSequenceNrValid(protectedStorageEntry.getSequenceNumber(), hashOfPayload)
&& checkSignature(protectedStorageEntry)
&& checkIfStoredDataPubKeyMatchesNewDataPubKey(protectedStorageEntry.getOwnerPubKey(), hashOfPayload);
// printData("before remove");
if (result) {
doRemoveProtectedExpirableData(protectedStorageEntry, hashOfPayload);
printData("after remove");
sequenceNumberMap.put(hashOfPayload, new MapValue(protectedStorageEntry.getSequenceNumber(), System.currentTimeMillis()));
sequenceNumberMapStorage.queueUpForSave(SequenceNumberMap.clone(sequenceNumberMap), 300);
maybeAddToRemoveAddOncePayloads(protectedStoragePayload, hashOfPayload);
broadcast(new RemoveDataMessage(protectedStorageEntry), sender, null, isDataOwner);
removeFromProtectedDataStore(protectedStorageEntry);
} else {
log.debug("remove failed");
}
return result;
}
private void removeFromProtectedDataStore(ProtectedStorageEntry protectedStorageEntry) {
ProtectedStoragePayload protectedStoragePayload = protectedStorageEntry.getProtectedStoragePayload();
if (protectedStoragePayload instanceof PersistablePayload) {
ByteArray compactHash = getCompactHashAsByteArray(protectedStoragePayload);
ProtectedStorageEntry previous = protectedDataStoreService.remove(compactHash, protectedStorageEntry);
if (previous != null) {
protectedDataStoreListeners.forEach(e -> e.onRemoved(protectedStorageEntry));
} else {
log.info("We cannot remove the protectedStorageEntry from the persistedEntryMap as it does not exist.");
}
}
}
@SuppressWarnings("UnusedReturnValue")
public boolean removeMailboxData(ProtectedMailboxStorageEntry protectedMailboxStorageEntry,
@Nullable NodeAddress sender,
boolean isDataOwner) {
ProtectedStoragePayload protectedStoragePayload = protectedMailboxStorageEntry.getProtectedStoragePayload();
ByteArray hashOfPayload = get32ByteHashAsByteArray(protectedStoragePayload);
boolean containsKey = map.containsKey(hashOfPayload);
if (!containsKey)
log.debug("Remove data ignored as we don't have an entry for that data.");
int sequenceNumber = protectedMailboxStorageEntry.getSequenceNumber();
PublicKey receiversPubKey = protectedMailboxStorageEntry.getReceiversPubKey();
boolean result = containsKey &&
isSequenceNrValid(sequenceNumber, hashOfPayload) &&
checkPublicKeys(protectedMailboxStorageEntry, false) &&
protectedMailboxStorageEntry.getMailboxStoragePayload().getOwnerPubKey().equals(receiversPubKey) && // at remove both keys are the same (only receiver is able to remove data)
checkSignature(protectedMailboxStorageEntry) &&
checkIfStoredMailboxDataMatchesNewMailboxData(receiversPubKey, hashOfPayload);
// printData("before removeMailboxData");
if (result) {
doRemoveProtectedExpirableData(protectedMailboxStorageEntry, hashOfPayload);
printData("after removeMailboxData");
sequenceNumberMap.put(hashOfPayload, new MapValue(sequenceNumber, System.currentTimeMillis()));
sequenceNumberMapStorage.queueUpForSave(SequenceNumberMap.clone(sequenceNumberMap), 300);
maybeAddToRemoveAddOncePayloads(protectedStoragePayload, hashOfPayload);
broadcast(new RemoveMailboxDataMessage(protectedMailboxStorageEntry), sender, null, isDataOwner);
} else {
log.debug("removeMailboxData failed");
}
return result;
}
private void maybeAddToRemoveAddOncePayloads(ProtectedStoragePayload protectedStoragePayload,
ByteArray hashOfData) {
if (protectedStoragePayload instanceof AddOncePayload) {
removedAddOncePayloads.add(hashOfData);
}
}
public ProtectedStorageEntry getProtectedStorageEntry(ProtectedStoragePayload protectedStoragePayload,
KeyPair ownerStoragePubKey)
throws CryptoException {
ByteArray hashOfData = get32ByteHashAsByteArray(protectedStoragePayload);
int sequenceNumber;
if (sequenceNumberMap.containsKey(hashOfData))
sequenceNumber = sequenceNumberMap.get(hashOfData).sequenceNr + 1;
else
sequenceNumber = 1;
byte[] hashOfDataAndSeqNr = P2PDataStorage.get32ByteHash(new DataAndSeqNrPair(protectedStoragePayload, sequenceNumber));
byte[] signature = Sig.sign(ownerStoragePubKey.getPrivate(), hashOfDataAndSeqNr);
return new ProtectedStorageEntry(protectedStoragePayload, ownerStoragePubKey.getPublic(), sequenceNumber, signature);
}
public RefreshOfferMessage getRefreshTTLMessage(ProtectedStoragePayload protectedStoragePayload,
KeyPair ownerStoragePubKey)
throws CryptoException {
ByteArray hashOfPayload = get32ByteHashAsByteArray(protectedStoragePayload);
int sequenceNumber;
if (sequenceNumberMap.containsKey(hashOfPayload))
sequenceNumber = sequenceNumberMap.get(hashOfPayload).sequenceNr + 1;
else
sequenceNumber = 1;
byte[] hashOfDataAndSeqNr = P2PDataStorage.get32ByteHash(new DataAndSeqNrPair(protectedStoragePayload, sequenceNumber));
byte[] signature = Sig.sign(ownerStoragePubKey.getPrivate(), hashOfDataAndSeqNr);
return new RefreshOfferMessage(hashOfDataAndSeqNr, signature, hashOfPayload.bytes, sequenceNumber);
}
public ProtectedMailboxStorageEntry getMailboxDataWithSignedSeqNr(MailboxStoragePayload expirableMailboxStoragePayload,
KeyPair storageSignaturePubKey,
PublicKey receiversPublicKey)
throws CryptoException {
ByteArray hashOfData = get32ByteHashAsByteArray(expirableMailboxStoragePayload);
int sequenceNumber;
if (sequenceNumberMap.containsKey(hashOfData))
sequenceNumber = sequenceNumberMap.get(hashOfData).sequenceNr + 1;
else
sequenceNumber = 1;
byte[] hashOfDataAndSeqNr = P2PDataStorage.get32ByteHash(new DataAndSeqNrPair(expirableMailboxStoragePayload, sequenceNumber));
byte[] signature = Sig.sign(storageSignaturePubKey.getPrivate(), hashOfDataAndSeqNr);
return new ProtectedMailboxStorageEntry(expirableMailboxStoragePayload,
storageSignaturePubKey.getPublic(), sequenceNumber, signature, receiversPublicKey);
}
public void addHashMapChangedListener(HashMapChangedListener hashMapChangedListener) {
hashMapChangedListeners.add(hashMapChangedListener);
}
public void removeHashMapChangedListener(HashMapChangedListener hashMapChangedListener) {
hashMapChangedListeners.remove(hashMapChangedListener);
}
public void addAppendOnlyDataStoreListener(AppendOnlyDataStoreListener listener) {
appendOnlyDataStoreListeners.add(listener);
}
@SuppressWarnings("unused")
public void removeAppendOnlyDataStoreListener(AppendOnlyDataStoreListener listener) {
appendOnlyDataStoreListeners.remove(listener);
}
@SuppressWarnings("unused")
public void addProtectedDataStoreListener(ProtectedDataStoreListener listener) {
protectedDataStoreListeners.add(listener);
}
@SuppressWarnings("unused")
public void removeProtectedDataStoreListener(ProtectedDataStoreListener listener) {
protectedDataStoreListeners.remove(listener);
}
// Private
private void doRemoveProtectedExpirableData(ProtectedStorageEntry protectedStorageEntry, ByteArray hashOfPayload) {
map.remove(hashOfPayload);
log.trace("Data removed from our map. We broadcast the message to our peers.");
hashMapChangedListeners.forEach(e -> e.onRemoved(protectedStorageEntry));
}
private boolean isSequenceNrValid(int newSequenceNumber, ByteArray hashOfData) {
if (sequenceNumberMap.containsKey(hashOfData)) {
int storedSequenceNumber = sequenceNumberMap.get(hashOfData).sequenceNr;
if (newSequenceNumber >= storedSequenceNumber) {
log.trace("Sequence number is valid (>=). sequenceNumber = "
+ newSequenceNumber + " / storedSequenceNumber=" + storedSequenceNumber);
return true;
} else {
log.debug("Sequence number is invalid. sequenceNumber = "
+ newSequenceNumber + " / storedSequenceNumber=" + storedSequenceNumber + "\n" +
"That can happen if the data owner gets an old delayed data storage message.");
return false;
}
} else {
return true;
}
}
private boolean hasSequenceNrIncreased(int newSequenceNumber, ByteArray hashOfData) {
if (sequenceNumberMap.containsKey(hashOfData)) {
int storedSequenceNumber = sequenceNumberMap.get(hashOfData).sequenceNr;
if (newSequenceNumber > storedSequenceNumber) {
log.trace("Sequence number has increased (>). sequenceNumber = "
+ newSequenceNumber + " / storedSequenceNumber=" + storedSequenceNumber + " / hashOfData=" + hashOfData.toString());
return true;
} else if (newSequenceNumber == storedSequenceNumber) {
String msg;
if (newSequenceNumber == 0) {
msg = "Sequence number is equal to the stored one and both are 0." +
"That is expected for network_messages which never got updated (mailbox msg).";
} else {
msg = "Sequence number is equal to the stored one. sequenceNumber = "
+ newSequenceNumber + " / storedSequenceNumber=" + storedSequenceNumber;
}
log.trace(msg);
return false;
} else {
log.debug("Sequence number is invalid. sequenceNumber = "
+ newSequenceNumber + " / storedSequenceNumber=" + storedSequenceNumber + "\n" +
"That can happen if the data owner gets an old delayed data storage message.");
return false;
}
} else {
return true;
}
}
private boolean checkSignature(PublicKey ownerPubKey, byte[] hashOfDataAndSeqNr, byte[] signature) {
try {
boolean result = Sig.verify(ownerPubKey, hashOfDataAndSeqNr, signature);
if (!result)
log.warn("Signature verification failed at checkSignature. " +
"That should not happen.");
return result;
} catch (CryptoException e) {
log.error("Signature verification failed at checkSignature");
return false;
}
}
private boolean checkSignature(ProtectedStorageEntry protectedStorageEntry) {
byte[] hashOfDataAndSeqNr = P2PDataStorage.get32ByteHash(new DataAndSeqNrPair(protectedStorageEntry.getProtectedStoragePayload(), protectedStorageEntry.getSequenceNumber()));
return checkSignature(protectedStorageEntry.getOwnerPubKey(), hashOfDataAndSeqNr, protectedStorageEntry.getSignature());
}
// Check that the pubkey of the storage entry matches the allowed pubkey for the addition or removal operation
// in the contained mailbox message, or the pubKey of other kinds of network_messages.
private boolean checkPublicKeys(ProtectedStorageEntry protectedStorageEntry, boolean isAddOperation) {
boolean result;
ProtectedStoragePayload protectedStoragePayload = protectedStorageEntry.getProtectedStoragePayload();
if (protectedStoragePayload instanceof MailboxStoragePayload) {
MailboxStoragePayload payload = (MailboxStoragePayload) protectedStoragePayload;
if (isAddOperation)
result = payload.getSenderPubKeyForAddOperation() != null &&
payload.getSenderPubKeyForAddOperation().equals(protectedStorageEntry.getOwnerPubKey());
else
result = payload.getOwnerPubKey() != null &&
payload.getOwnerPubKey().equals(protectedStorageEntry.getOwnerPubKey());
} else {
result = protectedStorageEntry.getOwnerPubKey() != null &&
protectedStoragePayload != null &&
protectedStorageEntry.getOwnerPubKey().equals(protectedStoragePayload.getOwnerPubKey());
}
if (!result) {
String res1 = protectedStorageEntry.toString();
String res2 = "null";
if (protectedStoragePayload != null &&
protectedStoragePayload.getOwnerPubKey() != null)
res2 = Utilities.encodeToHex(protectedStoragePayload.getOwnerPubKey().getEncoded(), true);
log.warn("PublicKey of payload data and ProtectedStorageEntry are not matching. protectedStorageEntry=" + res1 +
"protectedStorageEntry.getStoragePayload().getOwnerPubKey()=" + res2);
}
return result;
}
private boolean checkIfStoredDataPubKeyMatchesNewDataPubKey(PublicKey ownerPubKey, ByteArray hashOfData) {
ProtectedStorageEntry storedData = map.get(hashOfData);
boolean result = storedData.getOwnerPubKey() != null && storedData.getOwnerPubKey().equals(ownerPubKey);
if (!result)
log.warn("New data entry does not match our stored data. storedData.ownerPubKey=" +
(storedData.getOwnerPubKey() != null ? storedData.getOwnerPubKey().toString() : "null") +
", ownerPubKey=" + ownerPubKey);
return result;
}
private boolean checkIfStoredMailboxDataMatchesNewMailboxData(PublicKey receiversPubKey, ByteArray hashOfData) {
ProtectedStorageEntry storedData = map.get(hashOfData);
if (storedData instanceof ProtectedMailboxStorageEntry) {
ProtectedMailboxStorageEntry entry = (ProtectedMailboxStorageEntry) storedData;
// publicKey is not the same (stored: sender, new: receiver)
boolean result = entry.getReceiversPubKey().equals(receiversPubKey)
&& get32ByteHashAsByteArray(entry.getProtectedStoragePayload()).equals(hashOfData);
if (!result)
log.warn("New data entry does not match our stored data. entry.receiversPubKey=" + entry.getReceiversPubKey()
+ ", receiversPubKey=" + receiversPubKey);
return result;
} else {
log.error("We expected a MailboxData but got other type. That must never happen. storedData=" + storedData);
return false;
}
}
private void broadcast(BroadcastMessage message, @Nullable NodeAddress sender,
@Nullable BroadcastHandler.Listener listener, boolean isDataOwner) {
broadcaster.broadcast(message, sender, listener, isDataOwner);
}
private ByteArray get32ByteHashAsByteArray(NetworkPayload data) {
return new ByteArray(P2PDataStorage.get32ByteHash(data));
}
public static ByteArray getCompactHashAsByteArray(ProtectedStoragePayload protectedStoragePayload) {
return new ByteArray(getCompactHash(protectedStoragePayload));
}
private static byte[] getCompactHash(ProtectedStoragePayload protectedStoragePayload) {
return Hash.getSha256Ripemd160hash(protectedStoragePayload.toProtoMessage().toByteArray());
}
// Get a new map with entries older than PURGE_AGE_DAYS purged from the given map.
private Map<ByteArray, MapValue> getPurgedSequenceNumberMap(Map<ByteArray, MapValue> persisted) {
Map<ByteArray, MapValue> purged = new HashMap<>();
long maxAgeTs = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(PURGE_AGE_DAYS);
persisted.forEach((key, value) -> {
if (value.timeStamp > maxAgeTs)
purged.put(key, value);
});
return purged;
}
private void printData(String info) {
if (log.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("\n\n
sb.append("Data set ").append(info).append(" operation");
// We print the items sorted by hash with the payload class name and id
List<Tuple2<String, ProtectedStorageEntry>> tempList = map.values().stream()
.map(e -> new Tuple2<>(org.bitcoinj.core.Utils.HEX.encode(get32ByteHashAsByteArray(e.getProtectedStoragePayload()).bytes), e))
.sorted(Comparator.comparing(o -> o.first))
.collect(Collectors.toList());
tempList.forEach(e -> {
ProtectedStorageEntry storageEntry = e.second;
ProtectedStoragePayload protectedStoragePayload = storageEntry.getProtectedStoragePayload();
MapValue mapValue = sequenceNumberMap.get(get32ByteHashAsByteArray(protectedStoragePayload));
sb.append("\n")
.append("Hash=")
.append(e.first)
.append("; Class=")
.append(protectedStoragePayload.getClass().getSimpleName())
.append("; SequenceNumbers (Object/Stored)=")
.append(storageEntry.getSequenceNumber())
.append(" / ")
.append(mapValue != null ? mapValue.sequenceNr : "null")
.append("; TimeStamp (Object/Stored)=")
.append(storageEntry.getCreationTimeStamp())
.append(" / ")
.append(mapValue != null ? mapValue.timeStamp : "null")
.append("; Payload=")
.append(Utilities.toTruncatedString(protectedStoragePayload));
});
sb.append("\n
log.trace(sb.toString());
//log.debug("Data set " + info + " operation: size=" + map.values().size());
}
}
/**
* @param data Network payload
* @return Hash of data
*/
public static byte[] get32ByteHash(NetworkPayload data) {
return Hash.getSha256Hash(data.toProtoMessage().toByteArray());
}
// Static class
/**
* Used as container for calculating cryptographic hash of data and sequenceNumber.
*/
@EqualsAndHashCode
@ToString
public static final class DataAndSeqNrPair implements NetworkPayload {
// data are only used for calculating cryptographic hash from both values so they are kept private
private final ProtectedStoragePayload protectedStoragePayload;
private final int sequenceNumber;
public DataAndSeqNrPair(ProtectedStoragePayload protectedStoragePayload, int sequenceNumber) {
this.protectedStoragePayload = protectedStoragePayload;
this.sequenceNumber = sequenceNumber;
}
// Used only for calculating hash of byte array from PB object
@Override
public com.google.protobuf.Message toProtoMessage() {
return protobuf.DataAndSeqNrPair.newBuilder()
.setPayload((protobuf.StoragePayload) protectedStoragePayload.toProtoMessage())
.setSequenceNumber(sequenceNumber)
.build();
}
}
/**
* Used as key object in map for cryptographic hash of stored data as byte[] as primitive data type cannot be
* used as key
*/
@EqualsAndHashCode
public static final class ByteArray implements PersistablePayload {
// That object is saved to disc. We need to take care of changes to not break deserialization.
public final byte[] bytes;
@Override
public String toString() {
return "ByteArray{" +
"bytes as Hex=" + Hex.encode(bytes) +
'}';
}
public ByteArray(byte[] bytes) {
this.bytes = bytes;
}
// Protobuffer
@Override
public protobuf.ByteArray toProtoMessage() {
return protobuf.ByteArray.newBuilder().setBytes(ByteString.copyFrom(bytes)).build();
}
public static ByteArray fromProto(protobuf.ByteArray proto) {
return new ByteArray(proto.getBytes().toByteArray());
}
// Util
@SuppressWarnings("unused")
public String getHex() {
return Utilities.encodeToHex(bytes);
}
public static Set<P2PDataStorage.ByteArray> convertBytesSetToByteArraySet(Set<byte[]> set) {
return set != null ?
set.stream()
.map(P2PDataStorage.ByteArray::new)
.collect(Collectors.toSet())
: new HashSet<>();
}
}
/**
* Used as value in map
*/
@EqualsAndHashCode
@ToString
public static final class MapValue implements PersistablePayload {
// That object is saved to disc. We need to take care of changes to not break deserialization.
final public int sequenceNr;
final public long timeStamp;
MapValue(int sequenceNr, long timeStamp) {
this.sequenceNr = sequenceNr;
this.timeStamp = timeStamp;
}
@Override
public protobuf.MapValue toProtoMessage() {
return protobuf.MapValue.newBuilder().setSequenceNr(sequenceNr).setTimeStamp(timeStamp).build();
}
public static MapValue fromProto(protobuf.MapValue proto) {
return new MapValue(proto.getSequenceNr(), proto.getTimeStamp());
}
}
} |
package com.magnus.restbucks.web;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.siren4j.component.Entity;
import com.google.code.siren4j.component.Link;
import com.google.code.siren4j.component.builder.EntityBuilder;
import com.google.code.siren4j.component.builder.LinkBuilder;
@RestController
public class WelcomeController {
@RequestMapping(method = RequestMethod.GET, value = "/")
public ResponseEntity<Entity> returnRoot() {
Link selfLink =
LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_SELF).setHref("/").build();
Link nextLink =
LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_NEXT).setHref("/1").build();
List<Link> links = new ArrayList<Link>();
links.add(selfLink);
links.add(nextLink);
Entity result = EntityBuilder.newInstance().addLinks(links).build();
return new ResponseEntity<Entity>(result, HttpStatus.OK);
}
} |
package org.mariadb.jdbc;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.nio.charset.Charset;
import java.sql.*;
import static org.junit.Assert.*;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DatatypeTest extends BaseTest {
private ResultSet resultSet;
/**
* Initialisation.
* @throws SQLException exception
*/
@BeforeClass()
public static void initClass() throws SQLException {
createTable("Driverstreamtest", "id int not null primary key, strm text");
createTable("Driverstreamtest2", "id int primary key not null, strm text");
createTable("objecttest", "int_test int primary key not null, string_test varchar(30), "
+ "timestamp_test timestamp, serial_test blob");
createTable("bintest", "id int not null primary key auto_increment, bin1 varbinary(300), bin2 varbinary(300)");
createTable("bigdectest", "id int not null primary key auto_increment, bd decimal", "engine=innodb");
createTable("bytetest", "id int not null primary key auto_increment, a int", "engine=innodb");
createTable("shorttest", "id int not null primary key auto_increment,a int", "engine=innodb");
createTable("doubletest", "id int not null primary key auto_increment,a double", "engine=innodb");
createTable("bittest", "id int not null primary key auto_increment, b int");
createTable("emptytest", "id int");
createTable("test_setobjectconv", "id int not null primary key auto_increment, v1 varchar(40), v2 varchar(40)");
createTable("blabla", "valsue varchar(20)");
createTable("TestBigIntType", "t1 bigint(20), t2 bigint(20), t3 bigint(20), t4 bigint(20)");
createTable("time_period", "ID int unsigned NOT NULL, START time NOT NULL, END time NOT NULL, PRIMARY KEY (ID)");
}
@Before
public void checkSupported() throws Exception {
requireMinimumVersion(5, 0);
}
void checkClass(String column, Class<?> clazz, String mysqlType, int javaSqlType) throws Exception {
int index = resultSet.findColumn(column);
Object obj = resultSet.getObject(column);
if (obj != null) {
if (!clazz.equals(obj.getClass())) {
System.out.println("test");
}
assertEquals("Unexpected class for column " + column, clazz, resultSet.getObject(column).getClass());
}
assertEquals("Unexpected class name for column " + column, clazz.getName(),
resultSet.getMetaData().getColumnClassName(index));
assertEquals("Unexpected MySQL type for column " + column, mysqlType,
resultSet.getMetaData().getColumnTypeName(index));
assertEquals("Unexpected java sql type for column " + column, javaSqlType,
resultSet.getMetaData().getColumnType(index));
}
/**
* Testing different date parameters.
* @param connection current connection
* @param tinyInt1isBit tiny bit must be consider as boolean
* @param yearIsDateType year must be consider as Date or int
* @throws Exception exception
*/
public void datatypes(Connection connection, boolean tinyInt1isBit, boolean yearIsDateType) throws Exception {
createTable("datatypetest",
"bit1 BIT(1) default 0,"
+ "bit2 BIT(2) default 1,"
+ "tinyint1 TINYINT(1) default 0,"
+ "tinyint2 TINYINT(2) default 1,"
+ "bool0 BOOL default 0,"
+ "smallint0 SMALLINT default 1,"
+ "smallint_unsigned SMALLINT UNSIGNED default 0,"
+ "mediumint0 MEDIUMINT default 1,"
+ "mediumint_unsigned MEDIUMINT UNSIGNED default 0,"
+ "int0 INT default 1,"
+ "int_unsigned INT UNSIGNED default 0,"
+ "bigint0 BIGINT default 1,"
+ "bigint_unsigned BIGINT UNSIGNED default 0,"
+ "float0 FLOAT default 0,"
+ "double0 DOUBLE default 1,"
+ "decimal0 DECIMAL default 0,"
+ "date0 DATE default '2001-01-01',"
+ "datetime0 DATETIME default '2001-01-01 00:00:00',"
+ "timestamp0 TIMESTAMP default '2001-01-01 00:00:00',"
+ "time0 TIME default '22:11:00',"
+ ((minVersion(5, 6) && beforeVersion(10, 0)) ? "year2 YEAR(4) default 99," : "year2 YEAR(2) default 99,")
+ "year4 YEAR(4) default 2011,"
+ "char0 CHAR(1) default '0',"
+ "char_binary CHAR (1) binary default '0',"
+ "varchar0 VARCHAR(1) default '1',"
+ "varchar_binary VARCHAR(10) BINARY default 0x1,"
+ "binary0 BINARY(10) default 0x1,"
+ "varbinary0 VARBINARY(10) default 0x1,"
+ "tinyblob0 TINYBLOB,"
+ "tinytext0 TINYTEXT,"
+ "blob0 BLOB,"
+ "text0 TEXT,"
+ "mediumblob0 MEDIUMBLOB,"
+ "mediumtext0 MEDIUMTEXT,"
+ "longblob0 LONGBLOB,"
+ "longtext0 LONGTEXT,"
+ "enum0 ENUM('a','b') default 'a',"
+ "set0 SET('a','b') default 'a' ");
connection.createStatement().execute("insert into datatypetest (tinyblob0,mediumblob0,blob0,longblob0,"
+ "tinytext0,mediumtext0,text0, longtext0) values(0x1,0x1,0x1,0x1, 'a', 'a', 'a', 'a')");
resultSet = connection.createStatement().executeQuery("select * from datatypetest");
resultSet.next();
Class<?> byteArrayClass = (new byte[0]).getClass();
checkClass("bit1", Boolean.class, "BIT", Types.BIT);
checkClass("bit2", byteArrayClass, "BIT", Types.VARBINARY);
checkClass("tinyint1",
tinyInt1isBit ? Boolean.class : Integer.class, "TINYINT",
tinyInt1isBit ? Types.BIT : Types.TINYINT);
checkClass("tinyint2", Integer.class, "TINYINT", Types.TINYINT);
checkClass("bool0", tinyInt1isBit ? Boolean.class : Integer.class, "TINYINT",
tinyInt1isBit ? Types.BIT : Types.TINYINT);
checkClass("smallint0", Integer.class, "SMALLINT", Types.SMALLINT);
checkClass("smallint_unsigned", Integer.class, "SMALLINT UNSIGNED", Types.SMALLINT);
checkClass("mediumint0", Integer.class, "MEDIUMINT", Types.INTEGER);
checkClass("mediumint_unsigned", Integer.class, "MEDIUMINT UNSIGNED", Types.INTEGER);
checkClass("int0", Integer.class, "INTEGER", Types.INTEGER);
checkClass("int_unsigned", Long.class, "INTEGER UNSIGNED", Types.INTEGER);
checkClass("bigint0", Long.class, "BIGINT", Types.BIGINT);
checkClass("bigint_unsigned", BigInteger.class, "BIGINT UNSIGNED", Types.BIGINT);
checkClass("float0", Float.class, "FLOAT", Types.REAL);
checkClass("double0", Double.class, "DOUBLE", Types.DOUBLE);
checkClass("decimal0", BigDecimal.class, "DECIMAL", Types.DECIMAL);
checkClass("date0", Date.class, "DATE", Types.DATE);
checkClass("time0", Time.class, "TIME", Types.TIME);
checkClass("timestamp0", Timestamp.class, "TIMESTAMP", Types.TIMESTAMP);
if (minVersion(5, 6) && beforeVersion(10, 0)) {
//MySQL deprecated YEAR(2) since 5.6
checkClass("year2",
yearIsDateType ? Date.class : Short.class, "YEAR",
yearIsDateType ? Types.DATE : Types.SMALLINT);
}
checkClass("year4",
yearIsDateType ? Date.class : Short.class, "YEAR",
yearIsDateType ? Types.DATE : Types.SMALLINT);
checkClass("char0", String.class, "CHAR", Types.CHAR);
checkClass("char_binary", String.class, "CHAR", Types.CHAR);
checkClass("varchar0", String.class, "VARCHAR", Types.VARCHAR);
checkClass("varchar_binary", String.class, "VARCHAR", Types.VARCHAR);
checkClass("binary0", byteArrayClass, "BINARY", Types.BINARY);
checkClass("varbinary0", byteArrayClass, "VARBINARY", Types.VARBINARY);
checkClass("tinyblob0", byteArrayClass, "TINYBLOB", Types.VARBINARY);
checkClass("tinytext0", String.class, "VARCHAR", Types.VARCHAR);
checkClass("blob0", byteArrayClass, "BLOB", Types.VARBINARY);
checkClass("text0", String.class, "VARCHAR", Types.VARCHAR);
checkClass("mediumblob0", byteArrayClass, "MEDIUMBLOB", Types.VARBINARY);
checkClass("mediumtext0", String.class, "VARCHAR", Types.VARCHAR);
checkClass("longblob0", byteArrayClass, "LONGBLOB", Types.LONGVARBINARY);
checkClass("longtext0", String.class, "VARCHAR", Types.LONGVARCHAR);
checkClass("enum0", String.class, "CHAR", Types.CHAR);
checkClass("set0", String.class, "CHAR", Types.CHAR);
resultSet = connection.createStatement().executeQuery("select NULL as foo");
resultSet.next();
checkClass("foo", String.class, "NULL", Types.NULL);
}
@Test
public void datatypes1() throws Exception {
datatypes(sharedConnection, true, true);
}
@Test
public void datatypes2() throws Exception {
Connection connection = null;
try {
connection = setConnection("&tinyInt1isBit=0&yearIsDateType=0");
datatypes(connection, false, false);
} finally {
connection.close();
}
}
@Test
public void datatypes3() throws Exception {
Connection connection = null;
try {
connection = setConnection("&tinyInt1isBit=1&yearIsDateType=0");
datatypes(connection, true, false);
} finally {
connection.close();
}
}
@Test
public void datatypes4() throws Exception {
Connection connection = null;
try {
connection = setConnection("&tinyInt1isBit=0&yearIsDateType=1");
datatypes(connection, false, true);
} finally {
connection.close();
}
}
@SuppressWarnings("deprecation")
@Test
public void testCharacterStreams() throws SQLException, IOException {
PreparedStatement stmt = sharedConnection.prepareStatement(
"insert into Driverstreamtest (id, strm) values (?,?)");
stmt.setInt(1, 2);
String toInsert = "abcdefgh\njklmn\"";
Reader reader = new StringReader(toInsert);
stmt.setCharacterStream(2, reader);
stmt.execute();
ResultSet rs = sharedConnection.createStatement().executeQuery("select * from Driverstreamtest");
rs.next();
Reader rdr = rs.getCharacterStream("strm");
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = rdr.read()) != -1) {
sb.append((char) ch);
}
assertEquals(sb.toString(), (toInsert));
rdr = rs.getCharacterStream(2);
sb = new StringBuilder();
while ((ch = rdr.read()) != -1) {
sb.append((char) ch);
}
assertEquals(sb.toString(), (toInsert));
InputStream is = rs.getAsciiStream("strm");
sb = new StringBuilder();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
assertEquals(sb.toString(), (toInsert));
is = rs.getUnicodeStream("strm");
sb = new StringBuilder();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
assertEquals(sb.toString(), (toInsert));
assertEquals(sb.toString(), rs.getString("strm"));
}
@Test
public void testCharacterStreamWithLength() throws SQLException, IOException {
PreparedStatement stmt = sharedConnection.prepareStatement(
"insert into Driverstreamtest2 (id, strm) values (?,?)");
stmt.setInt(1, 2);
String toInsert = "abcdefgh\njklmn\"";
Reader reader = new StringReader(toInsert);
stmt.setCharacterStream(2, reader, 5);
stmt.execute();
testCharacterStreamWithLength(getResultSet("select * from Driverstreamtest2", false), toInsert);
testCharacterStreamWithLength(getResultSet("select * from Driverstreamtest2", true), toInsert);
}
private void testCharacterStreamWithLength(ResultSet rs, String toInsert) throws SQLException, IOException {
rs.next();
Reader rdr = rs.getCharacterStream("strm");
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = rdr.read()) != -1) {
sb.append((char) ch);
}
assertEquals(sb.toString(), toInsert.substring(0, 5));
assertEquals(rs.getString("strm"), toInsert.substring(0, 5));
}
/**
* Get a simple Statement or a PrepareStatement.
* @param query query
* @param prepared flag must be a prepare statement
* @return a statement
* @throws SQLException exception
*/
public static ResultSet getResultSet(String query, boolean prepared) throws SQLException {
return getResultSet(query, prepared, sharedConnection);
}
/**
* Get a simple Statement or a PrepareStatement.
* @param query query
* @param prepared flag must be a prepare statement
* @param connection the connection to use
* @return a statement
* @throws SQLException exception
*/
public static ResultSet getResultSet(String query, boolean prepared, Connection connection) throws SQLException {
if (prepared) {
PreparedStatement preparedStatement = connection.prepareStatement(query + " WHERE 1 = ?");
preparedStatement.setInt(1, 1);
return preparedStatement.executeQuery();
} else {
return connection.createStatement().executeQuery(query);
}
}
@Test
public void testEmptyResultSet() throws SQLException {
Statement stmt = sharedConnection.createStatement();
assertEquals(true, stmt.execute("SELECT * FROM emptytest"));
assertEquals(false, stmt.getResultSet().next());
}
@Test
public void testLongColName() throws SQLException {
DatabaseMetaData dbmd = sharedConnection.getMetaData();
String str = "";
for (int i = 0; i < dbmd.getMaxColumnNameLength(); i++) {
str += "x";
}
createTable("longcol", str + " int not null primary key");
sharedConnection.createStatement().execute("insert into longcol values (1)");
try (ResultSet rs = getResultSet("select * from longcol", false)) {
assertEquals(true, rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(1, rs.getInt(str));
assertEquals("1", rs.getString(1));
}
try (ResultSet rs = getResultSet("select * from longcol", true)) {
assertEquals(true, rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(1, rs.getInt(str));
assertEquals("1", rs.getString(1));
}
}
@Test(expected = SQLException.class)
public void testBadParamlist() throws SQLException {
PreparedStatement ps = null;
ps = sharedConnection.prepareStatement("insert into blah values (?)");
ps.execute();
}
@Test
public void setObjectTest() throws SQLException, IOException, ClassNotFoundException {
PreparedStatement ps = sharedConnection.prepareStatement("insert into objecttest values (?,?,?,?)");
ps.setObject(1, 5);
ps.setObject(2, "aaa");
ps.setObject(3, Timestamp.valueOf("2009-01-17 15:41:01"));
ps.setObject(4, new SerializableClass("testing", 8));
ps.execute();
try (ResultSet rs = getResultSet("select * from objecttest", false)) {
if (rs.next()) {
setObjectTestResult(rs);
} else {
fail();
}
}
try (ResultSet rs = getResultSet("select * from objecttest", true)) {
if (rs.next()) {
setObjectTestResult(rs);
} else {
fail();
}
}
}
private void setObjectTestResult(ResultSet rs) throws SQLException, IOException, ClassNotFoundException {
assertEquals("5", rs.getString(1));
assertEquals("aaa", rs.getString(2));
assertEquals("2009-01-17 15:41:01.0", rs.getString(3));
Object theInt = rs.getObject(1);
assertTrue(theInt instanceof Integer);
Object theInt2 = rs.getObject("int_test");
assertTrue(theInt2 instanceof Integer);
Object theString = rs.getObject(2);
assertTrue(theString instanceof String);
Object theTimestamp = rs.getObject(3);
assertTrue(theTimestamp instanceof Timestamp);
Object theBlob = rs.getObject(4);
assertNotNull(theBlob);
byte[] rawBytes = rs.getBytes(4);
ByteArrayInputStream bais = new ByteArrayInputStream(rawBytes);
ObjectInputStream ois = new ObjectInputStream(bais);
SerializableClass sc = (SerializableClass) ois.readObject();
assertEquals(sc.getVal(), "testing");
assertEquals(sc.getVal2(), 8);
rawBytes = rs.getBytes("serial_test");
bais = new ByteArrayInputStream(rawBytes);
ois = new ObjectInputStream(bais);
sc = (SerializableClass) ois.readObject();
assertEquals(sc.getVal(), "testing");
assertEquals(sc.getVal2(), 8);
}
@Test
public void setObjectBitInt() throws SQLException, IOException {
PreparedStatement preparedStatement = sharedConnection.prepareStatement("INSERT INTO TestBigIntType "
+ "(t1, t2, t3, t4) VALUES (?, ?, ?, ?)");
final long valueLong = System.currentTimeMillis();
final String maxValue = String.valueOf(Long.MAX_VALUE);
preparedStatement.setObject(1, valueLong, Types.BIGINT);
preparedStatement.setObject(2, maxValue, Types.BIGINT);
preparedStatement.setObject(3, valueLong);
preparedStatement.setObject(4, maxValue);
preparedStatement.executeUpdate();
try (ResultSet rs = getResultSet("select * from TestBigIntType", false)) {
validateResultBigIntType(valueLong, maxValue, rs);
}
try (ResultSet rs = getResultSet("select * from TestBigIntType", true)) {
validateResultBigIntType(valueLong, maxValue, rs);
}
}
private void validateResultBigIntType(long valueLong, String maxValue, ResultSet resultSet) throws SQLException {
if (resultSet.next()) {
assertEquals(resultSet.getLong(1), valueLong);
assertEquals(resultSet.getLong(2), Long.parseLong(maxValue));
assertEquals(resultSet.getLong(3), valueLong);
assertEquals(resultSet.getLong(4), Long.parseLong(maxValue));
assertEquals(resultSet.getString(1), String.valueOf(valueLong));
assertEquals(resultSet.getString(2), String.valueOf(Long.parseLong(maxValue)));
assertEquals(resultSet.getString(3), String.valueOf(valueLong));
assertEquals(resultSet.getString(4), String.valueOf(Long.parseLong(maxValue)));
} else {
fail();
}
}
@Test
public void binTest() throws SQLException, IOException {
byte[] allBytes = new byte[256];
for (int i = 0; i < 256; i++) {
allBytes[i] = (byte) (i & 0xff);
}
ByteArrayInputStream bais = new ByteArrayInputStream(allBytes);
PreparedStatement ps = sharedConnection.prepareStatement("insert into bintest (bin1,bin2) values (?,?)");
ps.setBytes(1, allBytes);
ps.setBinaryStream(2, bais);
ps.execute();
try (ResultSet rs = getResultSet("select bin1,bin2 from bintest", false)) {
binTestResult(rs, allBytes);
}
try (ResultSet rs = getResultSet("select bin1,bin2 from bintest", true)) {
binTestResult(rs, allBytes);
}
}
private void binTestResult(ResultSet rs, byte[] allBytes) throws SQLException, IOException {
if (rs.next()) {
rs.getBlob(1);
InputStream is = rs.getBinaryStream(1);
for (int i = 0; i < 256; i++) {
int read = is.read();
assertEquals(i, read);
}
assertEquals(rs.getString(1), new String(allBytes, "UTF-8"));
is = rs.getBinaryStream(2);
for (int i = 0; i < 256; i++) {
int read = is.read();
assertEquals(i, read);
}
assertEquals(rs.getString(2), new String(allBytes, "UTF-8"));
} else {
fail("Must have result !");
}
}
@Test
public void binTest2() throws SQLException, IOException {
if (sharedConnection.getMetaData().getDatabaseProductName().toLowerCase().equals("mysql")) {
createTable("bintest2", "bin1 longblob", "engine=innodb");
} else {
createTable("bintest2", "id int not null primary key auto_increment, bin1 blob");
}
byte[] buf = new byte[1000000];
for (int i = 0; i < 1000000; i++) {
buf[i] = (byte) i;
}
InputStream is = new ByteArrayInputStream(buf);
PreparedStatement ps = sharedConnection.prepareStatement("insert into bintest2 (bin1) values (?)");
ps.setBinaryStream(1, is);
ps.execute();
ps = sharedConnection.prepareStatement("insert into bintest2 (bin1) values (?)");
is = new ByteArrayInputStream(buf);
ps.setBinaryStream(1, is);
ps.execute();
try (ResultSet rs = getResultSet("select bin1 from bintest2", false)) {
binTest2Result(rs, buf);
}
try (ResultSet rs = getResultSet("select bin1 from bintest2", true)) {
binTest2Result(rs, buf);
}
}
private void binTest2Result(ResultSet rs, byte[] buf) throws SQLException, IOException {
if (rs.next()) {
byte[] buf2 = rs.getBytes(1);
for (int i = 0; i < 1000000; i++) {
assertEquals((byte) i, buf2[i]);
}
assertEquals(rs.getString(1), new String(buf, Charset.forName("UTF-8")));
if (rs.next()) {
buf2 = rs.getBytes(1);
for (int i = 0; i < 1000000; i++) {
assertEquals((byte) i, buf2[i]);
}
assertEquals(rs.getString(1), new String(buf, Charset.forName("UTF-8")));
if (rs.next()) {
fail();
}
} else {
fail();
}
} else {
fail();
}
}
@Test
public void bigDecimalTest() throws SQLException {
requireMinimumVersion(5, 0);
BigDecimal bd = BigDecimal.TEN;
PreparedStatement ps = sharedConnection.prepareStatement("insert into bigdectest (bd) values (?)");
ps.setBigDecimal(1, bd);
ps.execute();
try (ResultSet rs = getResultSet("select bd from bigdectest", false)) {
bigDecimalTestResult(rs, bd);
}
try (ResultSet rs = getResultSet("select bd from bigdectest", true)) {
bigDecimalTestResult(rs, bd);
}
}
private void bigDecimalTestResult(ResultSet rs, BigDecimal bd) throws SQLException {
if (rs.next()) {
Object bb = rs.getObject(1);
assertEquals(bd, bb);
BigDecimal bigD = rs.getBigDecimal(1);
BigDecimal bigD2 = rs.getBigDecimal("bd");
assertEquals(bd, bigD);
assertEquals(bd, bigD2);
assertEquals(rs.getString(1), "10");
bigD = rs.getBigDecimal("bd");
assertEquals(bd, bigD);
} else {
fail("Must have resultset");
}
}
@Test
public void byteTest() throws SQLException {
PreparedStatement ps = sharedConnection.prepareStatement("insert into bytetest (a) values (?)");
ps.setByte(1, Byte.MAX_VALUE);
ps.execute();
try (ResultSet rs = getResultSet("select a from bytetest", false)) {
byteTestResult(rs);
}
try (ResultSet rs = getResultSet("select a from bytetest", true)) {
byteTestResult(rs);
}
}
private void byteTestResult(ResultSet rs) throws SQLException {
if (rs.next()) {
Byte bc = rs.getByte(1);
Byte bc2 = rs.getByte("a");
assertTrue(Byte.MAX_VALUE == bc);
assertEquals(bc2, bc);
assertEquals(rs.getString(1), "127");
} else {
fail();
}
}
@Test
public void shortTest() throws SQLException {
PreparedStatement ps = sharedConnection.prepareStatement("insert into shorttest (a) values (?)");
ps.setShort(1, Short.MAX_VALUE);
ps.execute();
try (ResultSet rs = getResultSet("select a from shorttest", false)) {
shortTestResult(rs);
}
try (ResultSet rs = getResultSet("select a from shorttest", true)) {
shortTestResult(rs);
}
}
private void shortTestResult(ResultSet rs) throws SQLException {
if (rs.next()) {
Short bc = rs.getShort(1);
Short bc2 = rs.getShort("a");
assertTrue(Short.MAX_VALUE == bc);
assertEquals(bc2, bc);
assertEquals(rs.getString(1), "32767");
} else {
fail("must have result !");
}
}
@Test
public void doubleTest() throws SQLException {
PreparedStatement ps = sharedConnection.prepareStatement("insert into doubletest (a) values (?)");
double sendDoubleValue = 1.5;
ps.setDouble(1, sendDoubleValue);
ps.execute();
try (ResultSet rs = getResultSet("select a from doubletest", false)) {
doubleTestResult(rs, sendDoubleValue);
}
try (ResultSet rs = getResultSet("select a from doubletest", true)) {
doubleTestResult(rs, sendDoubleValue);
}
}
private void doubleTestResult(ResultSet rs, Double sendDoubleValue) throws SQLException {
if (rs.next()) {
Object returnObject = rs.getObject(1);
assertEquals(returnObject.getClass(), Double.class);
Double bc = rs.getDouble(1);
Double bc2 = rs.getDouble("a");
assertTrue(sendDoubleValue.doubleValue() == bc);
assertEquals(bc2, bc);
assertEquals(rs.getString(1), "1.5");
} else {
fail("must have result !");
}
}
@Test
public void getUrlTest() throws SQLException {
try (ResultSet rs = getResultSet("select 'http://mariadb.org' as url FROM dual", false)) {
getUrlTestResult(rs);
}
try (ResultSet rs = getResultSet("select 'http://mariadb.org' as url FROM dual", true)) {
getUrlTestResult(rs);
}
}
private void getUrlTestResult(ResultSet rs) throws SQLException {
if (rs.next()) {
URL url = rs.getURL(1);
assertEquals("http://mariadb.org", url.toString());
url = rs.getURL("url");
assertEquals("http://mariadb.org", url.toString());
assertEquals("http://mariadb.org", rs.getString(1));
} else {
fail("must have result");
}
}
@Test
public void getUrlFailTest() throws SQLException {
try (ResultSet rs = getResultSet("select 'asdf' as url FROM dual", false)) {
getUrlFailTestResult(rs);
}
try (ResultSet rs = getResultSet("select 'asdf' as url FROM dual", true)) {
getUrlFailTestResult(rs);
}
}
private void getUrlFailTestResult(ResultSet rs) throws SQLException {
if (rs.next()) {
try {
rs.getURL(1);
fail("must have thrown error");
} catch (SQLException e) {
}
try {
rs.getURL("url");
} catch (SQLException e) {
}
} else {
fail("must have result !");
}
}
@Test
public void setNull() throws SQLException {
PreparedStatement ps = sharedConnection.prepareStatement("insert blabla VALUE (?)");
ps.setString(1, null);
ps.executeQuery();
try (ResultSet rs = getResultSet("select * from blabla", false)) {
setNullResult(rs);
}
try (ResultSet rs = getResultSet("select * from blabla", true)) {
setNullResult(rs);
}
}
private void setNullResult(ResultSet rs) throws SQLException {
if (rs.next()) {
assertNull(rs.getString(1));
assertNull(rs.getObject(1));
} else {
fail("must have result !");
}
}
@Test
public void testSetObject() throws SQLException {
PreparedStatement ps = sharedConnection.prepareStatement("insert into test_setobjectconv values (null, ?, ?)");
ps.setObject(1, "2009-01-01 00:00:00", Types.TIMESTAMP);
ps.setObject(2, "33", Types.DOUBLE);
ps.execute();
}
@Test
public void testBit() throws SQLException {
PreparedStatement stmt = sharedConnection.prepareStatement("insert into bittest values(null, ?)");
stmt.setBoolean(1, true);
stmt.execute();
stmt.setBoolean(1, false);
stmt.execute();
try (ResultSet rs = getResultSet("select * from bittest", false)) {
testBitResult(rs);
}
try (ResultSet rs = getResultSet("select * from bittest", true)) {
testBitResult(rs);
}
}
private void testBitResult(ResultSet rs) throws SQLException {
if (rs.next()) {
Assert.assertTrue(rs.getBoolean("b"));
Assert.assertEquals(rs.getString("b"), "1");
if (rs.next()) {
Assert.assertFalse(rs.getBoolean("b"));
Assert.assertEquals(rs.getString("b"), "0");
} else {
fail("must have result");
}
} else {
fail("must have result");
}
}
@Test
@SuppressWarnings("deprecation")
public void testNullTimePreparedStatement() throws Exception {
sharedConnection.createStatement().execute("insert into time_period(id, start, end) values(1, '00:00:00', '08:00:00');");
final String sql = "SELECT id, start, end FROM time_period WHERE id=?";
PreparedStatement preparedStatement = sharedConnection.prepareStatement(sql);
preparedStatement.setInt(1, 1);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
Time timeStart = resultSet.getTime(2);
Time timeEnd = resultSet.getTime(3);
assertEquals(timeStart, new Time(0, 0, 0));
assertEquals(timeEnd, new Time(8, 0, 0));
}
}
}
} |
package com.minorityhobbies.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class IntrospectionUtil {
private final Class<?> type;
private final Map<String, PropertyDescriptor> pds = new HashMap<String, PropertyDescriptor>();
public IntrospectionUtil(Class<?> type) throws IntrospectionException {
super();
this.type = type;
Class<?> currentType = type;
while (currentType != Object.class) {
BeanInfo descriptor = Introspector.getBeanInfo(currentType);
for (PropertyDescriptor pd : descriptor.getPropertyDescriptors()) {
if (!"class".equals(pd.getName())) {
pds.put(pd.getName(), pd);
}
}
currentType = currentType.getSuperclass();
}
}
public List<String> getPropertyNames() {
return new ArrayList<String>(pds.keySet());
}
PropertyDescriptor getPropertyDescriptor(String name) {
PropertyDescriptor pd = pds.get(name);
if (pd == null) {
// try underscores -> camelcase
pd = pds.get(StringUtils.convertSnakeCaseToCamelCase(name));
}
if (pd != null) {
return pd;
} else {
throw new IllegalArgumentException(String.format(
"Property '%s' not found on instance of type '%s'", name,
type.getName()));
}
}
public Object getNamedProperty(String name, Object target) {
if (target == null) {
throw new NullPointerException();
}
Method getter = getPropertyDescriptor(name).getReadMethod();
try {
return getter.invoke(target);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public void setNamedProperty(String name, Object value, Object target) {
if (target == null) {
throw new NullPointerException();
}
Method setter = getPropertyDescriptor(name).getWriteMethod();
try {
setter.invoke(
target,
convertValueIfNecessary(value,
setter.getParameterTypes()[0]));
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private Object convertValueIfNecessary(Object value, Class<? extends Object> targetType) {
if (value == null) {
return null;
}
if (value instanceof String) {
String v = (String) value;
if (v.trim().length() == 0) {
return null;
}
if (String.class == targetType) {
return value;
}
if (Boolean.class == targetType || boolean.class == targetType) {
String b = v.trim();
if ("0".equals(b) || "no".equals(b.toLowerCase())) {
return false;
} else if ("1".equals(b) || "yes".equals(b.toLowerCase())) {
return true;
} else {
return Boolean.parseBoolean(b);
}
}
if (Byte.class == targetType || byte.class == targetType) {
return Byte.parseByte(v);
}
if (Short.class == targetType || short.class == targetType) {
return Short.parseShort(v);
}
if (Integer.class == targetType || int.class == targetType) {
return Integer.parseInt(v);
}
if (Long.class == targetType || long.class == targetType) {
return Long.parseLong(v);
}
if (Float.class == targetType || float.class == targetType) {
return Float.parseFloat(v);
}
if (Double.class == targetType || double.class == targetType) {
return Double.parseDouble(v);
}
if (Date.class == targetType) {
return new Date(Long.parseLong(v));
}
if (Enum.class.isAssignableFrom(targetType)) {
Class<? extends Enum> e = (Class<? extends Enum>) targetType;
return Enum.valueOf(e, v);
}
}
return value;
}
public Map<String, Object> propertiesToMap(Object obj) {
Map<String, Object> row = new LinkedHashMap<String, Object>();
for (String name : getPropertyNames()) {
if (!"class".equals(name)) {
row.put(name, getNamedProperty(name, obj));
}
}
return row;
}
public void mapToProperties(Object obj, Map<String, Object> properties) {
for (Map.Entry<String, Object> property : properties.entrySet()) {
String propertyName = property.getKey();
Object propertyValue = property.getValue();
setNamedProperty(propertyName, propertyValue, obj);
}
}
public Class<?> getType() {
return type;
}
} |
package ru.stq.pft.rest;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.testng.SkipException;
import java.io.IOException;
public class TestBase {
// protected static final ApplicationManager app = new ApplicationManager(System.getProperty("browser", BrowserType.FIREFOX));
/* @BeforeSuite
public void setUp() throws Exception {
app.init();
app.ftp().upload(new File("src/test/resources/config_inc.php"), "config_inc.php", "config_inc.php.bak");
}
@AfterSuite(alwaysRun = true)
public void tearDown() throws IOException {
app.ftp().restore("config_inc.php.bak", "config_inc.php");
app.stop();
}
*/
public boolean isIssueOpen(int issueId) throws IOException {
String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues/" + issueId + ".json")).returnContent().asString();
JsonElement parsed = new JsonParser().parse(json);
JsonElement issues = parsed.getAsJsonObject().get("issues");
JsonElement issue = issues.getAsJsonArray().get(0);
JsonElement state = issue.getAsJsonObject().get("state_name");
String stateName = state.toString();
if (stateName.equals("Resolved") && stateName.equals("Closed")) {
return true;
} else {
return false;
}
}
private Executor getExecutor() {
return Executor.newInstance().auth("LSGjeU4yP1X493ud1hNniA==", "");
}
public void skipIfNotFixed(int issueId) throws IOException {
if (isIssueOpen(issueId)) {
throw new SkipException("Ignored because of issue " + issueId);
}
}
} |
package seedu.taskitty.model;
import seedu.taskitty.commons.exceptions.IllegalValueException;
import seedu.taskitty.model.task.TaskDate;
import seedu.taskitty.model.task.TaskPeriod;
import seedu.taskitty.model.task.TaskTime;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
//@@author A0139930B
public class TaskTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void invalidDateFormat_exceptionThrown() throws Exception {
thrown.expect(IllegalValueException.class);
TaskDate date = new TaskDate("25-12-2016");
}
@Test
public void invalidDate_exceptionThrown() throws Exception {
thrown.expect(IllegalValueException.class);
TaskDate date = new TaskDate("29/2/2015");
}
@Test
public void invalidTimeFormat_exceptionThrown() throws Exception {
thrown.expect(IllegalValueException.class);
TaskTime date = new TaskTime("3pm");
}
@Test
public void invalidTime_exceptionThrown() throws Exception {
thrown.expect(IllegalValueException.class);
TaskDate date = new TaskDate("25:00");
}
@Test
public void invalidPeriod_startDateAfterEndDate_exceptionThrown() throws Exception {
thrown.expect(IllegalValueException.class);
TaskPeriod period = new TaskPeriod(new TaskDate("25/12/2016"), new TaskTime("10:00"),
new TaskDate("24/12/2016"), new TaskTime("12:00"));
}
@Test
public void invalidPeriod_startTimeAfterEndTime_exceptionThrown() throws Exception {
thrown.expect(IllegalValueException.class);
TaskDate date = new TaskDate("25/12/2016");
TaskPeriod period = new TaskPeriod(date, new TaskTime("10:00"),
date, new TaskTime("9:00"));
}
} |
package edu.umd.cs.findbugs.ba;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.ExceptionTable;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ArrayType;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.ch.Subtypes2;
import edu.umd.cs.findbugs.ba.type.TypeFrame;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.Global;
/**
* Facade for class hierarchy queries.
* These typically access the class hierarchy using
* the {@link org.apache.bcel.Repository} class. Callers should generally
* expect to handle ClassNotFoundException for when referenced
* classes can't be found.
*
* @author David Hovemeyer
*/
public class Hierarchy {
private static final boolean DEBUG_METHOD_LOOKUP =
SystemProperties.getBoolean("hier.lookup.debug");
/**
* Type of java.lang.Exception.
*/
public static final ObjectType EXCEPTION_TYPE = ObjectTypeFactory.getInstance("java.lang.Exception");
/**
* Type of java.lang.Error.
*/
public static final ObjectType ERROR_TYPE = ObjectTypeFactory.getInstance("java.lang.Error");
/**
* Type of java.lang.RuntimeException.
*/
public static final ObjectType RUNTIME_EXCEPTION_TYPE = ObjectTypeFactory.getInstance("java.lang.RuntimeException");
/**
* Determine whether one class (or reference type) is a subtype
* of another.
*
* @param clsName the name of the class or reference type
* @param possibleSupertypeClassName the name of the possible superclass
* @return true if clsName is a subtype of possibleSupertypeClassName,
* false if not
*/
public static boolean isSubtype(String clsName, String possibleSupertypeClassName) throws ClassNotFoundException {
ObjectType cls = ObjectTypeFactory.getInstance(clsName);
ObjectType superCls = ObjectTypeFactory.getInstance(possibleSupertypeClassName);
return isSubtype(cls, superCls);
}
/**
* Determine if one reference type is a subtype of another.
*
* @param t a reference type
* @param possibleSupertype the possible supertype
* @return true if t is a subtype of possibleSupertype,
* false if not
*/
public static boolean isSubtype(ReferenceType t, ReferenceType possibleSupertype) throws ClassNotFoundException {
if (Subtypes2.ENABLE_SUBTYPES2) {
try {
Subtypes2 subtypes2 = Global.getAnalysisCache().getDatabase(Subtypes2.class);
return subtypes2.isSubtype(t, possibleSupertype);
} catch (CheckedAnalysisException e) {
// Should not happen
IllegalStateException ise = new IllegalStateException("Should not happen");
ise.initCause(e);
throw ise;
}
} else {
Map<ReferenceType, Boolean> subtypes = subtypeCache.get(possibleSupertype);
if (subtypes == null) {
subtypes = new HashMap<ReferenceType, Boolean>();
subtypeCache.put(possibleSupertype, subtypes);
}
Boolean result = subtypes.get(t);
if (result == null) {
result = Boolean.valueOf(t.isAssignmentCompatibleWith(possibleSupertype));
subtypes.put(t, result);
}
return result;
}
}
static Map<ReferenceType, Map<ReferenceType, Boolean>> subtypeCache = new HashMap<ReferenceType, Map<ReferenceType, Boolean>> ();
/**
* Determine if the given ObjectType reference represents
* a <em>universal</em> exception handler. That is,
* one that will catch any kind of exception.
*
* @param catchType the ObjectType of the exception handler
* @return true if catchType is null, or if catchType is
* java.lang.Throwable
*/
public static boolean isUniversalExceptionHandler(ObjectType catchType) {
return catchType == null || catchType.equals(Type.THROWABLE);
}
/**
* Determine if the given ObjectType refers to an unchecked
* exception (RuntimeException or Error).
*/
public static boolean isUncheckedException(ObjectType type) throws ClassNotFoundException {
return isSubtype(type, RUNTIME_EXCEPTION_TYPE) || isSubtype(type, ERROR_TYPE);
}
/**
* Determine if method whose name and signature is specified
* is a monitor wait operation.
*
* @param methodName name of the method
* @param methodSig signature of the method
* @return true if the method is a monitor wait, false if not
*/
public static boolean isMonitorWait(String methodName, String methodSig) {
return methodName.equals("wait") &&
(methodSig.equals("()V") || methodSig.equals("(J)V") || methodSig.equals("(JI)V"));
}
/**
* Determine if given Instruction is a monitor wait.
*
* @param ins the Instruction
* @param cpg the ConstantPoolGen for the Instruction
*
* @return true if the instruction is a monitor wait, false if not
*/
public static boolean isMonitorWait(Instruction ins, ConstantPoolGen cpg) {
if (!(ins instanceof InvokeInstruction))
return false;
if (ins.getOpcode() == Constants.INVOKESTATIC)
return false;
InvokeInstruction inv = (InvokeInstruction) ins;
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
return isMonitorWait(methodName, methodSig);
}
/**
* Determine if method whose name and signature is specified
* is a monitor notify operation.
*
* @param methodName name of the method
* @param methodSig signature of the method
* @return true if the method is a monitor notify, false if not
*/
public static boolean isMonitorNotify(String methodName, String methodSig) {
return (methodName.equals("notify") || methodName.equals("notifyAll")) &&
methodSig.equals("()V");
}
/**
* Determine if given Instruction is a monitor wait.
*
* @param ins the Instruction
* @param cpg the ConstantPoolGen for the Instruction
*
* @return true if the instruction is a monitor wait, false if not
*/
public static boolean isMonitorNotify(Instruction ins, ConstantPoolGen cpg) {
if (!(ins instanceof InvokeInstruction))
return false;
if (ins.getOpcode() == Constants.INVOKESTATIC)
return false;
InvokeInstruction inv = (InvokeInstruction) ins;
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
return isMonitorNotify(methodName, methodSig);
}
/**
* Look up the method referenced by given InvokeInstruction.
* This method does <em>not</em> look for implementations in
* super or subclasses according to the virtual dispatch rules.
*
* @param inv the InvokeInstruction
* @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to
* @return the JavaClassAndMethod, or null if no such method is defined in the class
*/
public static JavaClassAndMethod findExactMethod(InvokeInstruction inv, ConstantPoolGen cpg) throws ClassNotFoundException {
return findExactMethod(inv, cpg, ANY_METHOD);
}
/**
* Look up the method referenced by given InvokeInstruction.
* This method does <em>not</em> look for implementations in
* super or subclasses according to the virtual dispatch rules.
*
* @param inv the InvokeInstruction
* @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to
* @param chooser JavaClassAndMethodChooser to use to pick the method from among the candidates
* @return the JavaClassAndMethod, or null if no such method is defined in the class
*/
public static JavaClassAndMethod findExactMethod(
InvokeInstruction inv,
ConstantPoolGen cpg,
JavaClassAndMethodChooser chooser) throws ClassNotFoundException {
String className = inv.getClassName(cpg);
String methodName = inv.getName(cpg);
String methodSig = inv.getSignature(cpg);
JavaClass jclass = Repository.lookupClass(className);
return findMethod(jclass, methodName, methodSig, chooser);
}
/**
* Visit all superclass methods which the given method overrides.
*
* @param method the method
* @param chooser chooser which visits each superclass method
* @return the chosen method, or null if no method is chosen
* @throws ClassNotFoundException
*/
public static JavaClassAndMethod visitSuperClassMethods(
JavaClassAndMethod method, JavaClassAndMethodChooser chooser) throws ClassNotFoundException {
return findMethod(
method.getJavaClass().getSuperClasses(),
method.getMethod().getName(),
method.getMethod().getSignature(),
chooser);
}
/**
* Visit all superinterface methods which the given method implements.
*
* @param method the method
* @param chooser chooser which visits each superinterface method
* @return the chosen method, or null if no method is chosen
* @throws ClassNotFoundException
*/
public static JavaClassAndMethod visitSuperInterfaceMethods(
JavaClassAndMethod method, JavaClassAndMethodChooser chooser) throws ClassNotFoundException {
return findMethod(
method.getJavaClass().getAllInterfaces(),
method.getMethod().getName(),
method.getMethod().getSignature(),
chooser);
}
/**
* Find the least upper bound method in the class hierarchy
* which could be called by the given InvokeInstruction.
* One reason this method is useful is that it indicates
* which declared exceptions are thrown by the called methods.
*
* <p/>
* <ul>
* <li> For invokespecial, this is simply an
* exact lookup.
* <li> For invokestatic and invokevirtual, the named class is searched,
* followed by superclasses up to the root of the object
* hierarchy (java.lang.Object). Yes, invokestatic really is declared
* to check superclasses. See VMSpec, 2nd ed, sec. 5.4.3.3.
* <li> For invokeinterface, the named class is searched,
* followed by all interfaces transitively declared by the class.
* (Question: is the order important here? Maybe the VM spec
* requires that the actual interface desired is given,
* so the extended lookup will not be required. Should check.)
* </ul>
*
* @param inv the InvokeInstruction
* @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to
* @return the JavaClassAndMethod, or null if no matching method can be found
*/
public static JavaClassAndMethod findInvocationLeastUpperBound(
InvokeInstruction inv, ConstantPoolGen cpg)
throws ClassNotFoundException {
return findInvocationLeastUpperBound(inv, cpg, ANY_METHOD);
}
public static JavaClassAndMethod findInvocationLeastUpperBound(
InvokeInstruction inv, ConstantPoolGen cpg, JavaClassAndMethodChooser methodChooser)
throws ClassNotFoundException {
JavaClassAndMethod result;
if (DEBUG_METHOD_LOOKUP) {
System.out.println("Find prototype method for " +
SignatureConverter.convertMethodSignature(inv,cpg));
}
short opcode = inv.getOpcode();
if (methodChooser != ANY_METHOD) {
methodChooser = new CompoundMethodChooser(new JavaClassAndMethodChooser[]{
methodChooser, opcode == Constants.INVOKESTATIC ? STATIC_METHOD : INSTANCE_METHOD
});
}
// Find the method
if (opcode == Constants.INVOKESPECIAL) {
// Non-virtual dispatch
result = findExactMethod(inv, cpg, methodChooser);
} else {
String className = inv.getClassName(cpg);
String methodName = inv.getName(cpg);
String methodSig = inv.getSignature(cpg);
if (DEBUG_METHOD_LOOKUP) {
System.out.println("[Class name is " + className + "]");
System.out.println("[Method name is " + methodName + "]");
System.out.println("[Method signature is " + methodSig + "]");
}
if (className.startsWith("[")) {
// Java 1.5 allows array classes to appear as the class name
className= "java.lang.Object";
}
if (opcode == Constants.INVOKEVIRTUAL || opcode == Constants.INVOKESTATIC) {
if (DEBUG_METHOD_LOOKUP) {
System.out.println("[invokevirtual or invokestatic]");
}
// Dispatch where the class hierarchy is searched
// Check superclasses
result = findMethod(Repository.lookupClass(className), methodName, methodSig, methodChooser);
if (result == null) {
if (DEBUG_METHOD_LOOKUP) {
System.out.println("[not in class, checking superclasses...]");
}
JavaClass[] superClassList = Repository.getSuperClasses(className);
result = findMethod(superClassList, methodName, methodSig, methodChooser);
}
} else {
// Check superinterfaces
result = findMethod(Repository.lookupClass(className), methodName, methodSig, methodChooser);
if (result == null) {
JavaClass[] interfaceList = Repository.getInterfaces(className);
result = findMethod(interfaceList, methodName, methodSig, methodChooser);
}
}
}
return result;
}
/**
* Find the declared exceptions for the method called
* by given instruction.
*
* @param inv the InvokeInstruction
* @param cpg the ConstantPoolGen used by the class the InvokeInstruction belongs to
* @return array of ObjectTypes of thrown exceptions, or null
* if we can't find the list of declared exceptions
*/
public static ObjectType[] findDeclaredExceptions(InvokeInstruction inv, ConstantPoolGen cpg)
throws ClassNotFoundException {
JavaClassAndMethod method = findInvocationLeastUpperBound(inv, cpg);
if (method == null)
return null;
ExceptionTable exTable = method.getMethod().getExceptionTable();
if (exTable == null)
return new ObjectType[0];
String[] exNameList = exTable.getExceptionNames();
ObjectType[] result = new ObjectType[exNameList.length];
for (int i = 0; i < exNameList.length; ++i) {
result[i] = ObjectTypeFactory.getInstance(exNameList[i]);
}
return result;
}
/**
* Find a method in given class.
*
* @param javaClass the class
* @param methodName the name of the method
* @param methodSig the signature of the method
* @return the JavaClassAndMethod, or null if no such method exists in the class
*/
public static @CheckForNull JavaClassAndMethod findMethod(JavaClass javaClass, String methodName, String methodSig) {
return findMethod(javaClass, methodName, methodSig, ANY_METHOD);
}
/**
* Find a method in given class.
*
* @param javaClass the class
* @param methodName the name of the method
* @param methodSig the signature of the method
* @param chooser JavaClassAndMethodChooser to use to select a matching method
* (assuming class, name, and signature already match)
* @return the JavaClassAndMethod, or null if no such method exists in the class
*/
public static @CheckForNull JavaClassAndMethod findMethod(
JavaClass javaClass,
String methodName,
String methodSig,
JavaClassAndMethodChooser chooser) {
if (DEBUG_METHOD_LOOKUP) {
System.out.println("Check " + javaClass.getClassName());
}
Method[] methodList = javaClass.getMethods();
for (Method method : methodList) if (method.getName().equals(methodName)
&& method.getSignature().equals(methodSig)) {
JavaClassAndMethod m = new JavaClassAndMethod(javaClass, method);
if (chooser.choose(m)) {
if (DEBUG_METHOD_LOOKUP) {
System.out.println("\t==> FOUND: " + method);
}
return m;
}
}
if (DEBUG_METHOD_LOOKUP) {
System.out.println("\t==> NOT FOUND");
}
return null;
}
/**
* Find a method in given class.
*
* @param javaClass the class
* @param methodName the name of the method
* @param methodSig the signature of the method
* @return the JavaClassAndMethod, or null if no such method exists in the class
*/
@Deprecated
public static @CheckForNull JavaClassAndMethod findConcreteMethod(
JavaClass javaClass,
String methodName,
String methodSig) {
if (DEBUG_METHOD_LOOKUP) {
System.out.println("Check " + javaClass.getClassName());
}
Method[] methodList = javaClass.getMethods();
for (Method method : methodList) if (method.getName().equals(methodName)
&& method.getSignature().equals(methodSig)
&& accessFlagsAreConcrete(method.getAccessFlags())) {
JavaClassAndMethod m = new JavaClassAndMethod(javaClass, method);
return m;
}
if (DEBUG_METHOD_LOOKUP) {
System.out.println("\t==> NOT FOUND");
}
return null;
}
/**
* Find a method in given class.
*
* @param javaClass the class
* @param methodName the name of the method
* @param methodSig the signature of the method
* @param chooser the JavaClassAndMethodChooser to use to screen possible candidates
* @return the XMethod, or null if no such method exists in the class
*/
@Deprecated
public static @CheckForNull XMethod findXMethod(JavaClass javaClass, String methodName, String methodSig,
JavaClassAndMethodChooser chooser) {
JavaClassAndMethod result = findMethod(javaClass, methodName, methodSig, chooser);
return result == null ? null : XFactory.createXMethod(result.getJavaClass(), result.getMethod());
}
/**
* JavaClassAndMethodChooser which accepts any method.
*/
public static final JavaClassAndMethodChooser ANY_METHOD = new JavaClassAndMethodChooser() {
public boolean choose(JavaClassAndMethod javaClassAndMethod) {
return true;
}
};
// FIXME: perhaps native methods should be concrete.
public static boolean accessFlagsAreConcrete(int accessFlags) {
return (accessFlags & Constants.ACC_ABSTRACT) == 0
&& (accessFlags & Constants.ACC_NATIVE) == 0;
}
/**
* JavaClassAndMethodChooser which accepts only concrete (not abstract or native) methods.
*/
public static final JavaClassAndMethodChooser CONCRETE_METHOD = new JavaClassAndMethodChooser() {
public boolean choose(JavaClassAndMethod javaClassAndMethod) {
Method method = javaClassAndMethod.getMethod();
int accessFlags = method.getAccessFlags();
return accessFlagsAreConcrete(accessFlags);
}
};
/**
* JavaClassAndMethodChooser which accepts only static methods.
*/
public static final JavaClassAndMethodChooser STATIC_METHOD = new JavaClassAndMethodChooser() {
public boolean choose(JavaClassAndMethod javaClassAndMethod) {
return javaClassAndMethod.getMethod().isStatic();
}
};
/**
* JavaClassAndMethodChooser which accepts only instance methods.
*/
public static final JavaClassAndMethodChooser INSTANCE_METHOD = new JavaClassAndMethodChooser() {
public boolean choose(JavaClassAndMethod javaClassAndMethod) {
return !javaClassAndMethod.getMethod().isStatic();
}
};
/**
* Find a method in given list of classes,
* searching the classes in order.
*
* @param classList list of classes in which to search
* @param methodName the name of the method
* @param methodSig the signature of the method
* @return the JavaClassAndMethod, or null if no such method exists in the class
*/
@Deprecated
public static JavaClassAndMethod findMethod(JavaClass[] classList, String methodName, String methodSig) {
return findMethod(classList, methodName, methodSig, ANY_METHOD);
}
/**
* Find a method in given list of classes,
* searching the classes in order.
*
* @param classList list of classes in which to search
* @param methodName the name of the method
* @param methodSig the signature of the method
* @param chooser JavaClassAndMethodChooser to select which methods are considered;
* it must return true for a method to be returned
* @return the JavaClassAndMethod, or null if no such method exists in the class
*/
public static JavaClassAndMethod findMethod(JavaClass[] classList, String methodName, String methodSig,
JavaClassAndMethodChooser chooser) {
JavaClassAndMethod m = null;
for (JavaClass cls : classList) {
if ((m = findMethod(cls, methodName, methodSig, chooser)) != null)
break;
}
return m;
}
/**
* Find XMethod for method in given list of classes,
* searching the classes in order.
*
* @param classList list of classes in which to search
* @param methodName the name of the method
* @param methodSig the signature of the method
* @return the XMethod, or null if no such method exists in the class
*/
@Deprecated
public static XMethod findXMethod(JavaClass[] classList, String methodName, String methodSig) {
return findXMethod(classList, methodName, methodSig, ANY_METHOD);
}
/**
* Find XMethod for method in given list of classes,
* searching the classes in order.
*
* @param classList list of classes in which to search
* @param methodName the name of the method
* @param methodSig the signature of the method
* @param chooser JavaClassAndMethodChooser to select which methods are considered;
* it must return true for a method to be returned
* @return the XMethod, or null if no such method exists in the class
*/
@Deprecated
public static XMethod findXMethod(JavaClass[] classList, String methodName, String methodSig,
JavaClassAndMethodChooser chooser) {
for (JavaClass cls : classList) {
JavaClassAndMethod m;
if ((m = findMethod(cls, methodName, methodSig)) != null && chooser.choose(m)) {
return XFactory.createXMethod(cls, m.getMethod());
}
}
return null;
}
/**
* Resolve possible method call targets.
* This works for both static and instance method calls.
*
* @param invokeInstruction the InvokeInstruction
* @param typeFrame the TypeFrame containing the types of stack values
* @param cpg the ConstantPoolGen
* @return Set of methods which might be called
* @throws DataflowAnalysisException
* @throws ClassNotFoundException
*/
public static Set<JavaClassAndMethod> resolveMethodCallTargets(
InvokeInstruction invokeInstruction,
TypeFrame typeFrame,
ConstantPoolGen cpg) throws DataflowAnalysisException, ClassNotFoundException {
short opcode = invokeInstruction.getOpcode();
if (opcode == Constants.INVOKESTATIC) {
HashSet<JavaClassAndMethod> result = new HashSet<JavaClassAndMethod>();
JavaClassAndMethod targetMethod = findInvocationLeastUpperBound(invokeInstruction, cpg, CONCRETE_METHOD);
if (targetMethod != null) {
result.add(targetMethod);
}
return result;
}
if (!typeFrame.isValid()) {
return new HashSet<JavaClassAndMethod>();
}
Type receiverType;
boolean receiverTypeIsExact;
if (opcode == Constants.INVOKESPECIAL) {
// invokespecial instructions are dispatched to EXACTLY
// the class specified by the instruction
receiverType = ObjectTypeFactory.getInstance(invokeInstruction.getClassName(cpg));
receiverTypeIsExact = false; // Doesn't actually matter
} else {
// For invokevirtual and invokeinterface instructions, we have
// virtual dispatch. By taking the receiver type (which may be a
// subtype of the class specified by the instruction),
// we may get a more precise set of call targets.
int instanceStackLocation = typeFrame.getInstanceStackLocation(invokeInstruction, cpg);
receiverType = typeFrame.getStackValue(instanceStackLocation);
if (!(receiverType instanceof ReferenceType)) {
return new HashSet<JavaClassAndMethod>();
}
receiverTypeIsExact = typeFrame.isExact(instanceStackLocation);
}
if (DEBUG_METHOD_LOOKUP) {
System.out.println("[receiver type is " + receiverType + ", " +
(receiverTypeIsExact ? "exact]" : " not exact]"));
}
return resolveMethodCallTargets((ReferenceType) receiverType, invokeInstruction, cpg, receiverTypeIsExact);
}
/**
* Resolve possible instance method call targets.
* Assumes that invokevirtual and invokeinterface methods may
* call any subtype of the receiver class.
*
* @param receiverType type of the receiver object
* @param invokeInstruction the InvokeInstruction
* @param cpg the ConstantPoolGen
* @return Set of methods which might be called
* @throws ClassNotFoundException
*/
public static Set<JavaClassAndMethod> resolveMethodCallTargets(
ReferenceType receiverType,
InvokeInstruction invokeInstruction,
ConstantPoolGen cpg
) throws ClassNotFoundException {
return resolveMethodCallTargets(receiverType, invokeInstruction, cpg, false);
}
/**
* Resolve possible instance method call targets.
*
* @param receiverType type of the receiver object
* @param invokeInstruction the InvokeInstruction
* @param cpg the ConstantPoolGen
* @param receiverTypeIsExact if true, the receiver type is known exactly,
* which should allow a precise result
* @return Set of methods which might be called
* @throws ClassNotFoundException
*/
public static Set<JavaClassAndMethod> resolveMethodCallTargets(
ReferenceType receiverType,
InvokeInstruction invokeInstruction,
ConstantPoolGen cpg,
boolean receiverTypeIsExact
) throws ClassNotFoundException {
HashSet<JavaClassAndMethod> result = new HashSet<JavaClassAndMethod>();
if (invokeInstruction.getOpcode() == Constants.INVOKESTATIC)
throw new IllegalArgumentException();
String methodName = invokeInstruction.getName(cpg);
String methodSig = invokeInstruction.getSignature(cpg);
// Array method calls aren't virtual.
// They should just resolve to Object methods.
if (receiverType instanceof ArrayType) {
JavaClass javaLangObject = AnalysisContext.currentAnalysisContext().lookupClass("java.lang.Object");
JavaClassAndMethod classAndMethod = findMethod(javaLangObject, methodName, methodSig, INSTANCE_METHOD);
if (classAndMethod != null)
result.add(classAndMethod);
return result;
}
AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
// Get the receiver class.
String receiverClassName = ((ObjectType) receiverType).getClassName();
JavaClass receiverClass = analysisContext.lookupClass(
receiverClassName);
// Figure out the upper bound for the method.
// This is what will be called if this is not a virtual call site.
JavaClassAndMethod upperBound = findMethod(receiverClass, methodName, methodSig, CONCRETE_METHOD);
if (upperBound == null) {
// Try superclasses
JavaClass[] superClassList = receiverClass.getSuperClasses();
upperBound = findMethod(superClassList, methodName, methodSig, CONCRETE_METHOD);
}
if (upperBound != null) {
if (DEBUG_METHOD_LOOKUP) {
System.out.println("Adding upper bound: " +
SignatureConverter.convertMethodSignature(upperBound.getJavaClass(), upperBound.getMethod()));
}
result.add(upperBound);
}
// Is this a virtual call site?
boolean virtualCall =
invokeInstruction.getOpcode() != Constants.INVOKESPECIAL
&& !receiverTypeIsExact;
if (virtualCall && !receiverClassName.equals("java.lang.Object")) {
// This is a true virtual call: assume that any concrete
// subtype method may be called.
Set<JavaClass> subTypeSet = analysisContext.getSubtypes().getTransitiveSubtypes(receiverClass);
for (JavaClass subtype : subTypeSet) {
JavaClassAndMethod concreteSubtypeMethod = findMethod(subtype, methodName, methodSig, CONCRETE_METHOD);
if (concreteSubtypeMethod != null) {
result.add(concreteSubtypeMethod);
}
}
}
return result;
}
/**
* Return whether or not the given method is concrete.
*
* @param xmethod the method
* @return true if the method is concrete, false otherwise
*/
@Deprecated
public static boolean isConcrete(XMethod xmethod) {
int accessFlags = xmethod.getAccessFlags();
return (accessFlags & Constants.ACC_ABSTRACT) == 0
&& (accessFlags & Constants.ACC_NATIVE) == 0;
}
/**
* Find a field with given name defined in given class.
*
* @param className the name of the class
* @param fieldName the name of the field
* @return the Field, or null if no such field could be found
*/
public static Field findField(String className, String fieldName) throws ClassNotFoundException {
JavaClass jclass = Repository.lookupClass(className);
while (jclass != null) {
Field[] fieldList = jclass.getFields();
for (Field field : fieldList) {
if (field.getName().equals(fieldName)) {
return field;
}
}
jclass = jclass.getSuperClass();
}
return null;
}
/*
public static JavaClass findClassDefiningField(String className, String fieldName, String fieldSig)
throws ClassNotFoundException {
JavaClass jclass = Repository.lookupClass(className);
while (jclass != null) {
Field[] fieldList = jclass.getFields();
for (int i = 0; i < fieldList.length; ++i) {
Field field = fieldList[i];
if (field.getName().equals(fieldName) && field.getSignature().equals(fieldSig)) {
return jclass;
}
}
jclass = jclass.getSuperClass();
}
return null;
}
*/
/**
* Look up a field with given name and signature in given class,
* returning it as an {@link XField XField} object.
* If a field can't be found in the immediate class,
* its superclass is search, and so forth.
*
* @param className name of the class through which the field
* is referenced
* @param fieldName name of the field
* @param fieldSig signature of the field
* @param isStatic true if field is static, false otherwise
* @return an XField object representing the field, or null if no such field could be found
*/
public static XField findXField(String className, String fieldName, String fieldSig, boolean isStatic)
throws ClassNotFoundException {
// JavaClass classDefiningField = Repository.lookupClass(className);
// Field field = null;
// loop:
// while (classDefiningField != null) {
// Field[] fieldList = classDefiningField.getFields();
// for (Field aFieldList : fieldList) {
// field = aFieldList;
// if (field.getName().equals(fieldName) && field.getSignature().equals(fieldSig)) {
// break loop;
// classDefiningField = classDefiningField.getSuperClass();
// if (classDefiningField == null || field == null)
// return null;
// else {
// String realClassName = classDefiningField.getClassName();
// int accessFlags = field.getAccessFlags();
// return field.isStatic()
// ? (XField) new StaticField(realClassName, fieldName, fieldSig, accessFlags)
// : (XField) new InstanceField(realClassName, fieldName, fieldSig, accessFlags);
return XFactory.createXField(className, fieldName, fieldSig, isStatic);
}
/**
* Look up the field referenced by given FieldInstruction,
* returning it as an {@link XField XField} object.
*
* @param fins the FieldInstruction
* @param cpg the ConstantPoolGen used by the class containing the instruction
* @return an XField object representing the field, or null
* if no such field could be found
*/
public static XField findXField(FieldInstruction fins, @NonNull ConstantPoolGen cpg)
throws ClassNotFoundException {
String className = fins.getClassName(cpg);
String fieldName = fins.getFieldName(cpg);
String fieldSig = fins.getSignature(cpg);
boolean isStatic = (fins.getOpcode() == Constants.GETSTATIC || fins.getOpcode() == Constants.PUTSTATIC);
XField xfield = findXField(className, fieldName, fieldSig, isStatic);
short opcode = fins.getOpcode();
if (xfield != null &&
xfield.isStatic() == (opcode == Constants.GETSTATIC || opcode == Constants.PUTSTATIC))
return xfield;
else
return null;
}
/**
* Determine whether the given INVOKESTATIC instruction
* is an inner-class field accessor method.
* @param inv the INVOKESTATIC instruction
* @param cpg the ConstantPoolGen for the method
* @return true if the instruction is an inner-class field accessor, false if not
*/
public static boolean isInnerClassAccess(INVOKESTATIC inv, ConstantPoolGen cpg) {
String methodName = inv.getName(cpg);
return methodName.startsWith("access$");
}
/**
* Get the InnerClassAccess for access method called
* by given INVOKESTATIC.
* @param inv the INVOKESTATIC instruction
* @param cpg the ConstantPoolGen for the method
* @return the InnerClassAccess, or null if the instruction is not
* an inner-class access
*/
public static InnerClassAccess getInnerClassAccess(INVOKESTATIC inv, ConstantPoolGen cpg)
throws ClassNotFoundException {
String className = inv.getClassName(cpg);
String methodName = inv.getName(cpg);
String methodSig = inv.getSignature(cpg);
InnerClassAccess access = AnalysisContext.currentAnalysisContext()
.getInnerClassAccessMap().getInnerClassAccess(className, methodName);
return (access != null && access.getMethodSignature().equals(methodSig))
? access
: null;
}
}
// vim:ts=4 |
package com.sdgas.action;
import com.opensymphony.xwork2.ModelDriven;
import com.sdgas.VO.PRVO;
import com.sdgas.base.PageView;
import com.sdgas.model.*;
import com.sdgas.service.*;
import com.sdgas.util.ChangeTime;
import com.sdgas.util.Mail;
import com.sdgas.util.UserUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@Component("purchaseRequisition")
@Scope("prototype")
public class PurchaseRequisitionAction extends MyActionSupport implements ModelDriven<PRVO> {
private PRVO prVo = new PRVO();
private UserService userService;
private DemandPlansService demandPlansService;
private PurchaseMaterialService purchaseMaterialService;
private SupplierService supplierService;
private PurchaseRequisitionService purchaseRequisitionService;
private static final Logger logger = LogManager.getLogger(PurchaseRequisitionAction.class);
HttpSession session = ServletActionContext.getRequest().getSession();
User user = (User) session.getAttribute("person");
String ip = (String) session.getAttribute("ip");
@Override
public String execute() throws Exception {
DemandPlans demandPlans = demandPlansService.find(DemandPlans.class, prVo.getDpId());
List<PurchaseMaterial> purchaseMaterials = purchaseMaterialService.findMaterialByPlan(demandPlans);
prVo.setPurchaseMaterials(purchaseMaterials);
prVo.setDemandPlans(demandPlans);
view = "/page/pr/createPR.jsp";
return VIEW;
}
public String addPR() {
DemandPlans demandPlans = demandPlansService.find(DemandPlans.class, prVo.getDpId());
List<PurchaseMaterial> purchaseMaterials = purchaseMaterialService.findMaterialByPlan(demandPlans);
demandPlans.setStatus(DemandStatus.PR);
demandPlansService.update(demandPlans);
demandPlansService.clear();
PurchaseRequisition pr = purchaseMaterials.get(0).getRequisition();
pr.setApplyUser(user);
pr.setPrId(prVo.getPrId());
pr.setStatus(PRStatus.PR);
pr.setRemarks(prVo.getRemarks());
pr.setApplyDate(ChangeTime.parseDate(ChangeTime.getCurrentDate()));
purchaseRequisitionService.update(pr);
logger.info(user.getPosition().getPositionName() + " " + user.getUserName() + "," + pr.getPrId() + " IP:" + ip);
String[] materialIds = prVo.getMaterialId().split(",");
String[] suppliers = prVo.getSupplier().split(",");
String[] price = prVo.getPrice().split(",");
for (int i = 0; i < materialIds.length; i++) {
PurchaseMaterial pm = purchaseMaterialService.findMaterial(demandPlans, materialIds[i].trim());
pm.setRequisition(pr);
pm.setStatus(FormStatus.REQUISITION);
Supplier supplier = supplierService.findSupplierByName(suppliers[i].trim());
pm.setSupplier(supplier);
pm.setPrice(Double.valueOf(price[i].trim()));
pm.setTotalPay(pm.getAmount() * pm.getPrice());
purchaseMaterialService.update(pm);
purchaseMaterialService.clear();
}
//TODO:MAIL
User person = userService.findNextUser("DP", user, null);
String msg = "" + pr.getProject() + "";
Mail.sendMail(person.getEmail(), "", msg, "html");
prVo.setResultMessage("<script>alert('');location.href='PurchaseRequisition!findAll.action';</script>");
return SUCCESS;
}
public String findAll() {
if (UserUtil.checkUserLogIn(user)) {
prVo.setResultMessage("<script>alert('');location.href='login.jsp';</script>");
return ERROR;
}
int maxResult = 10;
PageView<PurchaseRequisition> pageView = new PageView<PurchaseRequisition>(maxResult,
prVo.getPage());
int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
.getMaxResult());
LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
orderBy.put("prDate", "DESC");
StringBuffer jpql = new StringBuffer("");
if (prVo.getFlag() == 2)
jpql.append("status IS NOT NULL");
else
jpql.append("status=" + PRStatus.DEMAND.getStatus());
List<Object> params = new ArrayList<Object>();
pageView.setQueryResult(purchaseRequisitionService.getScrollData(PurchaseRequisition.class, firstIndex, maxResult, jpql.toString(),
params.toArray(), orderBy));
prVo.setPageView(pageView);
view = "/page/pr/findAllPR.jsp";
return VIEW;
}
public String search() {
if (UserUtil.checkUserLogIn(user)) {
prVo.setResultMessage("<script>alert('');location.href='login.jsp';</script>");
return ERROR;
}
int maxResult = 10;
PageView<PurchaseRequisition> pageView = new PageView<PurchaseRequisition>(maxResult,
prVo.getPage());
int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
.getMaxResult());
LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
orderBy.put("prDate", "DESC");
StringBuffer jpql = new StringBuffer("status IS NOT NULL");
if (!prVo.getProject().isEmpty())
jpql.append(" and project like '%" + prVo.getProject()).append("%' or prId like '%" + prVo.getProject()).append("%'");
if (!prVo.getPrDate().isEmpty())
jpql.append(" and prDate <= '" + prVo.getPrDate()).append("'");
List<Object> params = new ArrayList<Object>();
pageView.setQueryResult(purchaseRequisitionService.getScrollData(PurchaseRequisition.class, firstIndex, maxResult, jpql.toString(),
params.toArray(), orderBy));
prVo.setPageView(pageView);
if (pageView.getRecords().isEmpty()) {
if (prVo.getFlag() == 9)
prVo.setResultMessage("<script>alert('');location.href='PurchaseRequisition!findOrder.action';</script>");
else
prVo.setResultMessage("<script>alert('');location.href='PurchaseRequisition!findAll.action?flag=2';</script>");
return ERROR;
}
if (prVo.getFlag() == 9)
view = "/page/order/findAll.jsp";
else
view = "/page/pr/findAllPR.jsp";
return VIEW;
}
public String showOne() {
PurchaseRequisition pr = purchaseRequisitionService.findPRByPrId(prVo.getPrId());
List<PurchaseMaterial> purchaseMaterials = purchaseMaterialService.findMaterialByPR(pr);
prVo.setPurchaseMaterials(purchaseMaterials);
prVo.setPr(pr);
view = "/page/pr/showOne.jsp";
return VIEW;
}
public String check() {
if (UserUtil.checkUserLogIn(user)) {
prVo.setResultMessage("<script>alert('');location.href='login.jsp';</script>");
return ERROR;
}
PurchaseRequisition pr = purchaseRequisitionService.findPRByPrId(prVo.getPrId());
List<PurchaseMaterial> purchaseMaterials = purchaseMaterialService.findMaterialByPR(pr);
if (prVo.getStatus().equals("true")) {
switch (pr.getStatus()) {
case PR:
pr.setStatus(PRStatus.HEAD);
break;
case HEAD:
pr.setStatus(PRStatus.LEADER);
pr = checkGoToGM(pr, purchaseMaterials);
break;
case LEADER:
pr.setStatus(PRStatus.GM);
break;
case GM:
pr.setStatus(PRStatus.PU);
break;
}
} else {
pr.setStatus(PRStatus.CANCEL);
for (PurchaseMaterial purchaseMaterial : purchaseMaterials) {
purchaseMaterial.setStatus(FormStatus.CANCEL);
purchaseMaterialService.update(purchaseMaterial);
}
}
if (pr.getComment() != null)
pr.setComment(pr.getComment() + "<br/>" + prVo.getRemarks());
else
pr.setComment(prVo.getRemarks());
purchaseRequisitionService.update(pr);
//TODO:MAIL
if (pr.getStatus() == PRStatus.CANCEL) {
User person = pr.getApplyUser();
String msg = "" + pr.getProject() + "";
Mail.sendMail(person.getEmail(), "", msg, "html");
} else {
User person = userService.findNextUser("DP", user, null);
String msg = "" + pr.getProject() + "";
Mail.sendMail(person.getEmail(), "", msg, "html");
}
prVo.setResultMessage("<script>alert('');location.href='PurchaseRequisition!findAll.action?flag=2';</script>");
return SUCCESS;
}
public String findOrder() {
if (UserUtil.checkUserLogIn(user)) {
prVo.setResultMessage("<script>alert('');location.href='login.jsp';</script>");
return ERROR;
}
int maxResult = 10;
PageView<PurchaseRequisition> pageView = new PageView<PurchaseRequisition>(maxResult,
prVo.getPage());
int firstIndex = ((pageView.getCurrentPage() - 1) * pageView
.getMaxResult());
LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
orderBy.put("prDate", "DESC");
StringBuffer jpql = new StringBuffer("");
jpql.append("status=" + PRStatus.GM.getStatus());
List<Object> params = new ArrayList<Object>();
pageView.setQueryResult(purchaseRequisitionService.getScrollData(PurchaseRequisition.class, firstIndex, maxResult, jpql.toString(),
params.toArray(), orderBy));
prVo.setPageView(pageView);
view = "/page/order/findAll.jsp";
return VIEW;
}
private PurchaseRequisition checkGoToGM(PurchaseRequisition pr, List<PurchaseMaterial> purchaseMaterials) {
if ("".equals(pr.getDemandType())) {
double total = 0.0d;
for (PurchaseMaterial pm : purchaseMaterials) {
if (pm.getPrice() >= 50000)
return pr;
total += pm.getTotalPay();
}
if (total >= 300000)
return pr;
} else if ("".equals(pr.getDemandType())) {
double total = 0.0d;
for (PurchaseMaterial pm : purchaseMaterials) {
if (pm.getPrice() >= 50000)
return pr;
total += pm.getTotalPay();
}
if (total >= 100000)
return pr;
} else {
double total = 0.0d;
for (PurchaseMaterial pm : purchaseMaterials) {
if (pm.getPrice() >= 50000)
return pr;
total += pm.getTotalPay();
}
if (total >= 500000)
return pr;
}
pr.setStatus(PRStatus.GM);
return pr;
}
@Override
public PRVO getModel() {
return prVo;
}
@Resource(name = "demandPlansServiceImpl")
public void setDemandPlansService(DemandPlansService demandPlansService) {
this.demandPlansService = demandPlansService;
}
@Resource(name = "purchaseMaterialServiceImpl")
public void setPurchaseMaterialService(PurchaseMaterialService purchaseMaterialService) {
this.purchaseMaterialService = purchaseMaterialService;
}
@Resource(name = "supplierServiceImpl")
public void setSupplierService(SupplierService supplierService) {
this.supplierService = supplierService;
}
@Resource(name = "purchaseRequisitionServiceImpl")
public void setPurchaseRequisitionService(PurchaseRequisitionService purchaseRequisitionService) {
this.purchaseRequisitionService = purchaseRequisitionService;
}
@Resource(name = "userServiceImpl")
public void setUserService(UserService userService) {
this.userService = userService;
}
} |
package net.sf.cglib.reflect;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import junit.framework.*;
import net.sf.cglib.core.ClassGenerator;
import net.sf.cglib.core.DefaultGeneratorStrategy;
import net.sf.cglib.transform.ClassTransformerTee;
import net.sf.cglib.transform.NullClassVisitor;
import net.sf.cglib.transform.TransformingClassGenerator;
import org.objectweb.asm.util.DumpClassVisitor;
public class TestFastClass extends net.sf.cglib.CodeGenTestCase {
public static class Simple {
}
public static class ThrowsSomething {
public void foo() throws IOException {
throw new IOException("hello");
}
}
public void testSimple() throws Throwable {
FastClass.create(Simple.class).newInstance();
}
public void testException() throws Throwable {
FastClass fc = FastClass.create(ThrowsSomething.class);
ThrowsSomething ts = new ThrowsSomething();
try {
fc.invoke("foo", new Class[0], ts, new Object[0]);
fail("expected exception");
} catch (InvocationTargetException e) {
assertTrue(e.getTargetException() instanceof IOException);
}
}
public void testTypeMismatch() throws Throwable {
FastClass fc = FastClass.create(ThrowsSomething.class);
ThrowsSomething ts = new ThrowsSomething();
try {
fc.invoke("foo", new Class[]{ Integer.TYPE }, ts, new Object[0]);
fail("expected exception");
} catch (IllegalArgumentException ignore) { }
}
public void testComplex() throws Throwable {
FastClass fc = FastClass.create(MemberSwitchBean.class);
MemberSwitchBean bean = (MemberSwitchBean)fc.newInstance();
assertTrue(bean.init == 0);
assertTrue(fc.getName().equals("net.sf.cglib.reflect.MemberSwitchBean"));
assertTrue(fc.getJavaClass() == MemberSwitchBean.class);
assertTrue(fc.getMaxIndex() == 18);
Constructor c1 = MemberSwitchBean.class.getConstructor(new Class[0]);
FastConstructor fc1 = fc.getConstructor(c1);
assertTrue(((MemberSwitchBean)fc1.newInstance()).init == 0);
assertTrue(fc1.toString().equals("public net.sf.cglib.reflect.MemberSwitchBean()"));
Method m1 = MemberSwitchBean.class.getMethod("foo", new Class[]{ Integer.TYPE, String.class });
assertTrue(fc.getMethod(m1).invoke(bean, new Object[]{ new Integer(0), "" }).equals(new Integer(6)));
// TODO: should null be allowed here?
Method m2 = MemberSwitchBean.class.getDeclaredMethod("pkg", null);
assertTrue(fc.getMethod(m2).invoke(bean, null).equals(new Integer(9)));
}
private static abstract class ReallyBigClass {
public ReallyBigClass() {
}
abstract public void method1(int i, short s, float f);
abstract public void method1(int i, byte d, float f);
abstract public void method2(int i, short s, float f);
abstract public void method2(int i, byte d, float f);
abstract public void method3(int i, short s, float f);
abstract public void method3(int i, byte d, float f);
abstract public void method4(int i, short s, float f);
abstract public void method4(int i, byte d, float f);
abstract public void method5(int i, short s, float f);
abstract public void method5(int i, byte d, float f);
abstract public void method6(int i, short s, float f);
abstract public void method6(int i, byte d, float f);
abstract public void method7(int i, short s, float f);
abstract public void method7(int i, byte d, float f);
abstract public void method8(int i, short s, float f);
abstract public void method8(int i, byte d, float f);
abstract public void method9(int i, short s, float f);
abstract public void method9(int i, byte d, float f);
abstract public void method10(int i, short s, float f);
abstract public void method10(int i, byte d, float f);
abstract public void method11(int i, short s, float f);
abstract public void method11(int i, byte d, float f);
abstract public void method12(int i, short s, float f);
abstract public void method12(int i, byte d, float f);
abstract public void method13(int i, short s, float f);
abstract public void method13(int i, byte d, float f);
abstract public void method14(int i, short s, float f);
abstract public void method14(int i, byte d, float f);
abstract public void method15(int i, short s, float f);
abstract public void method15(int i, byte d, float f);
abstract public void method16(int i, short s, float f);
abstract public void method16(int i, byte d, float f);
abstract public void method17(int i, short s, float f);
abstract public void method17(int i, byte d, float f);
abstract public void method18(int i, short s, float f);
abstract public void method18(int i, byte d, float f);
abstract public void method19(int i, short s, float f);
abstract public void method19(int i, byte d, float f);
abstract public void method20(int i, short s, float f);
abstract public void method20(int i, byte d, float f);
abstract public void method21(int i, short s, float f);
abstract public void method21(int i, byte d, float f);
abstract public void method22(int i, short s, float f);
abstract public void method22(int i, byte d, float f);
abstract public void method23(int i, short s, float f);
abstract public void method23(int i, byte d, float f);
abstract public void method24(int i, short s, float f);
abstract public void method24(int i, byte d, float f);
abstract public void method25(int i, short s, float f);
abstract public void method25(int i, byte d, float f);
abstract public void method26(int i, short s, float f);
abstract public void method26(int i, byte d, float f);
abstract public void method27(int i, short s, float f);
abstract public void method27(int i, byte d, float f);
abstract public void method28(int i, short s, float f);
abstract public void method28(int i, byte d, float f);
abstract public void method29(int i, short s, float f);
abstract public void method29(int i, byte d, float f);
abstract public void method30(int i, short s, float f);
abstract public void method30(int i, byte d, float f);
abstract public void method31(int i, short s, float f);
abstract public void method31(int i, byte d, float f);
abstract public void method32(int i, short s, float f);
abstract public void method32(int i, byte d, float f);
abstract public void method33(int i, short s, float f);
abstract public void method33(int i, byte d, float f);
abstract public void method34(int i, short s, float f);
abstract public void method34(int i, byte d, float f);
abstract public void method35(int i, short s, float f);
abstract public void method35(int i, byte d, float f);
abstract public void method36(int i, short s, float f);
abstract public void method36(int i, byte d, float f);
abstract public void method37(int i, short s, float f);
abstract public void method37(int i, byte d, float f);
abstract public void method38(int i, short s, float f);
abstract public void method38(int i, byte d, float f);
abstract public void method39(int i, short s, float f);
abstract public void method39(int i, byte d, float f);
abstract public void method40(int i, short s, float f);
abstract public void method40(int i, byte d, float f);
abstract public void method41(int i, short s, float f);
abstract public void method41(int i, byte d, float f);
abstract public void method42(int i, short s, float f);
abstract public void method42(int i, byte d, float f);
abstract public void method43(int i, short s, float f);
abstract public void method43(int i, byte d, float f);
abstract public void method44(int i, short s, float f);
abstract public void method44(int i, byte d, float f);
abstract public void method45(int i, short s, float f);
abstract public void method45(int i, byte d, float f);
abstract public void method46(int i, short s, float f);
abstract public void method46(int i, byte d, float f);
abstract public void method47(int i, short s, float f);
abstract public void method47(int i, byte d, float f);
abstract public void method48(int i, short s, float f);
abstract public void method48(int i, byte d, float f);
abstract public void method49(int i, short s, float f);
abstract public void method49(int i, byte d, float f);
abstract public void method50(int i, short s, float f);
abstract public void method50(int i, byte d, float f);
abstract public void method51(int i, short s, float f);
abstract public void method51(int i, byte d, float f);
abstract public void method52(int i, short s, float f);
abstract public void method52(int i, byte d, float f);
abstract public void method53(int i, short s, float f);
abstract public void method53(int i, byte d, float f);
abstract public void method54(int i, short s, float f);
abstract public void method54(int i, byte d, float f);
abstract public void method55(int i, short s, float f);
abstract public void method55(int i, byte d, float f);
abstract public void method56(int i, short s, float f);
abstract public void method56(int i, byte d, float f);
abstract public void method57(int i, short s, float f);
abstract public void method57(int i, byte d, float f);
abstract public void method58(int i, short s, float f);
abstract public void method58(int i, byte d, float f);
abstract public void method59(int i, short s, float f);
abstract public void method59(int i, byte d, float f);
abstract public void method60(int i, short s, float f);
abstract public void method60(int i, byte d, float f);
abstract public void method61(int i, short s, float f);
abstract public void method61(int i, byte d, float f);
abstract public void method62(int i, short s, float f);
abstract public void method62(int i, byte d, float f);
abstract public void method63(int i, short s, float f);
abstract public void method63(int i, byte d, float f);
abstract public void method64(int i, short s, float f);
abstract public void method64(int i, byte d, float f);
abstract public void method65(int i, short s, float f);
abstract public void method65(int i, byte d, float f);
abstract public void method66(int i, short s, float f);
abstract public void method66(int i, byte d, float f);
abstract public void method67(int i, short s, float f);
abstract public void method67(int i, byte d, float f);
abstract public void method68(int i, short s, float f);
abstract public void method68(int i, byte d, float f);
abstract public void method69(int i, short s, float f);
abstract public void method69(int i, byte d, float f);
abstract public void method70(int i, short s, float f);
abstract public void method70(int i, byte d, float f);
abstract public void method71(int i, short s, float f);
abstract public void method71(int i, byte d, float f);
abstract public void method72(int i, short s, float f);
abstract public void method72(int i, byte d, float f);
abstract public void method73(int i, short s, float f);
abstract public void method73(int i, byte d, float f);
abstract public void method74(int i, short s, float f);
abstract public void method74(int i, byte d, float f);
abstract public void method75(int i, short s, float f);
abstract public void method75(int i, byte d, float f);
abstract public void method76(int i, short s, float f);
abstract public void method76(int i, byte d, float f);
abstract public void method77(int i, short s, float f);
abstract public void method77(int i, byte d, float f);
abstract public void method78(int i, short s, float f);
abstract public void method78(int i, byte d, float f);
abstract public void method79(int i, short s, float f);
abstract public void method79(int i, byte d, float f);
abstract public void method80(int i, short s, float f);
abstract public void method80(int i, byte d, float f);
abstract public void method81(int i, short s, float f);
abstract public void method81(int i, byte d, float f);
abstract public void method82(int i, short s, float f);
abstract public void method82(int i, byte d, float f);
abstract public void method83(int i, short s, float f);
abstract public void method83(int i, byte d, float f);
abstract public void method84(int i, short s, float f);
abstract public void method84(int i, byte d, float f);
abstract public void method85(int i, short s, float f);
abstract public void method85(int i, byte d, float f);
abstract public void method86(int i, short s, float f);
abstract public void method86(int i, byte d, float f);
abstract public void method87(int i, short s, float f);
abstract public void method87(int i, byte d, float f);
abstract public void method88(int i, short s, float f);
abstract public void method88(int i, byte d, float f);
abstract public void method89(int i, short s, float f);
abstract public void method89(int i, byte d, float f);
abstract public void method90(int i, short s, float f);
abstract public void method90(int i, byte d, float f);
abstract public void method91(int i, short s, float f);
abstract public void method91(int i, byte d, float f);
abstract public void method92(int i, short s, float f);
abstract public void method92(int i, byte d, float f);
abstract public void method93(int i, short s, float f);
abstract public void method93(int i, byte d, float f);
abstract public void method94(int i, short s, float f);
abstract public void method94(int i, byte d, float f);
abstract public void method95(int i, short s, float f);
abstract public void method95(int i, byte d, float f);
abstract public void method96(int i, short s, float f);
abstract public void method96(int i, byte d, float f);
abstract public void method97(int i, short s, float f);
abstract public void method97(int i, byte d, float f);
abstract public void method98(int i, short s, float f);
abstract public void method98(int i, byte d, float f);
abstract public void method99(int i, short s, float f);
abstract public void method99(int i, byte d, float f);
abstract public void method100(int i, short s, float f);
abstract public void method100(int i, byte d, float f);
abstract public void method101(int i, short s, float f);
abstract public void method101(int i, byte d, float f);
abstract public void method102(int i, short s, float f);
abstract public void method102(int i, byte d, float f);
abstract public void method103(int i, short s, float f);
abstract public void method103(int i, byte d, float f);
abstract public void method104(int i, short s, float f);
abstract public void method104(int i, byte d, float f);
abstract public void method105(int i, short s, float f);
abstract public void method105(int i, byte d, float f);
abstract public void method106(int i, short s, float f);
abstract public void method106(int i, byte d, float f);
abstract public void method107(int i, short s, float f);
abstract public void method107(int i, byte d, float f);
abstract public void method108(int i, short s, float f);
abstract public void method108(int i, byte d, float f);
abstract public void method109(int i, short s, float f);
abstract public void method109(int i, byte d, float f);
abstract public void method110(int i, short s, float f);
abstract public void method110(int i, byte d, float f);
abstract public void method111(int i, short s, float f);
abstract public void method111(int i, byte d, float f);
abstract public void method112(int i, short s, float f);
abstract public void method112(int i, byte d, float f);
abstract public void method113(int i, short s, float f);
abstract public void method113(int i, byte d, float f);
abstract public void method114(int i, short s, float f);
abstract public void method114(int i, byte d, float f);
abstract public void method115(int i, short s, float f);
abstract public void method115(int i, byte d, float f);
abstract public void method116(int i, short s, float f);
abstract public void method116(int i, byte d, float f);
abstract public void method117(int i, short s, float f);
abstract public void method117(int i, byte d, float f);
abstract public void method118(int i, short s, float f);
abstract public void method118(int i, byte d, float f);
abstract public void method119(int i, short s, float f);
abstract public void method119(int i, byte d, float f);
abstract public void method120(int i, short s, float f);
abstract public void method120(int i, byte d, float f);
abstract public void methodB1(int i, short s, float f);
abstract public void methodB1(int i, byte d, float f);
abstract public void methodB2(int i, short s, float f);
abstract public void methodB2(int i, byte d, float f);
abstract public void methodB3(int i, short s, float f);
abstract public void methodB3(int i, byte d, float f);
abstract public void methodB4(int i, short s, float f);
abstract public void methodB4(int i, byte d, float f);
abstract public void methodB5(int i, short s, float f);
abstract public void methodB5(int i, byte d, float f);
abstract public void methodB6(int i, short s, float f);
abstract public void methodB6(int i, byte d, float f);
abstract public void methodB7(int i, short s, float f);
abstract public void methodB7(int i, byte d, float f);
abstract public void methodB8(int i, short s, float f);
abstract public void methodB8(int i, byte d, float f);
abstract public void methodB9(int i, short s, float f);
abstract public void methodB9(int i, byte d, float f);
abstract public void methodB10(int i, short s, float f);
abstract public void methodB10(int i, byte d, float f);
abstract public void methodB11(int i, short s, float f);
abstract public void methodB11(int i, byte d, float f);
abstract public void methodB12(int i, short s, float f);
abstract public void methodB12(int i, byte d, float f);
abstract public void methodB13(int i, short s, float f);
abstract public void methodB13(int i, byte d, float f);
abstract public void methodB14(int i, short s, float f);
abstract public void methodB14(int i, byte d, float f);
abstract public void methodB15(int i, short s, float f);
abstract public void methodB15(int i, byte d, float f);
abstract public void methodB16(int i, short s, float f);
abstract public void methodB16(int i, byte d, float f);
abstract public void methodB17(int i, short s, float f);
abstract public void methodB17(int i, byte d, float f);
abstract public void methodB18(int i, short s, float f);
abstract public void methodB18(int i, byte d, float f);
abstract public void methodB19(int i, short s, float f);
abstract public void methodB19(int i, byte d, float f);
abstract public void methodB20(int i, short s, float f);
abstract public void methodB20(int i, byte d, float f);
abstract public void methodB21(int i, short s, float f);
abstract public void methodB21(int i, byte d, float f);
abstract public void methodB22(int i, short s, float f);
abstract public void methodB22(int i, byte d, float f);
abstract public void methodB23(int i, short s, float f);
abstract public void methodB23(int i, byte d, float f);
abstract public void methodB24(int i, short s, float f);
abstract public void methodB24(int i, byte d, float f);
abstract public void methodB25(int i, short s, float f);
abstract public void methodB25(int i, byte d, float f);
abstract public void methodB26(int i, short s, float f);
abstract public void methodB26(int i, byte d, float f);
abstract public void methodB27(int i, short s, float f);
abstract public void methodB27(int i, byte d, float f);
abstract public void methodB28(int i, short s, float f);
abstract public void methodB28(int i, byte d, float f);
abstract public void methodB29(int i, short s, float f);
abstract public void methodB29(int i, byte d, float f);
abstract public void methodB30(int i, short s, float f);
abstract public void methodB30(int i, byte d, float f);
abstract public void methodB31(int i, short s, float f);
abstract public void methodB31(int i, byte d, float f);
abstract public void methodB32(int i, short s, float f);
abstract public void methodB32(int i, byte d, float f);
abstract public void methodB33(int i, short s, float f);
abstract public void methodB33(int i, byte d, float f);
abstract public void methodB34(int i, short s, float f);
abstract public void methodB34(int i, byte d, float f);
abstract public void methodB35(int i, short s, float f);
abstract public void methodB35(int i, byte d, float f);
abstract public void methodB36(int i, short s, float f);
abstract public void methodB36(int i, byte d, float f);
abstract public void methodB37(int i, short s, float f);
abstract public void methodB37(int i, byte d, float f);
abstract public void methodB38(int i, short s, float f);
abstract public void methodB38(int i, byte d, float f);
abstract public void methodB39(int i, short s, float f);
abstract public void methodB39(int i, byte d, float f);
abstract public void methodB40(int i, short s, float f);
abstract public void methodB40(int i, byte d, float f);
abstract public void methodB41(int i, short s, float f);
abstract public void methodB41(int i, byte d, float f);
abstract public void methodB42(int i, short s, float f);
abstract public void methodB42(int i, byte d, float f);
abstract public void methodB43(int i, short s, float f);
abstract public void methodB43(int i, byte d, float f);
abstract public void methodB44(int i, short s, float f);
abstract public void methodB44(int i, byte d, float f);
abstract public void methodB45(int i, short s, float f);
abstract public void methodB45(int i, byte d, float f);
abstract public void methodB46(int i, short s, float f);
abstract public void methodB46(int i, byte d, float f);
abstract public void methodB47(int i, short s, float f);
abstract public void methodB47(int i, byte d, float f);
abstract public void methodB48(int i, short s, float f);
abstract public void methodB48(int i, byte d, float f);
abstract public void methodB49(int i, short s, float f);
abstract public void methodB49(int i, byte d, float f);
abstract public void methodB50(int i, short s, float f);
abstract public void methodB50(int i, byte d, float f);
abstract public void methodB51(int i, short s, float f);
abstract public void methodB51(int i, byte d, float f);
abstract public void methodB52(int i, short s, float f);
abstract public void methodB52(int i, byte d, float f);
abstract public void methodB53(int i, short s, float f);
abstract public void methodB53(int i, byte d, float f);
abstract public void methodB54(int i, short s, float f);
abstract public void methodB54(int i, byte d, float f);
abstract public void methodB55(int i, short s, float f);
abstract public void methodB55(int i, byte d, float f);
abstract public void methodB56(int i, short s, float f);
abstract public void methodB56(int i, byte d, float f);
abstract public void methodB57(int i, short s, float f);
abstract public void methodB57(int i, byte d, float f);
abstract public void methodB58(int i, short s, float f);
abstract public void methodB58(int i, byte d, float f);
abstract public void methodB59(int i, short s, float f);
abstract public void methodB59(int i, byte d, float f);
abstract public void methodB60(int i, short s, float f);
abstract public void methodB60(int i, byte d, float f);
abstract public void methodB61(int i, short s, float f);
abstract public void methodB61(int i, byte d, float f);
abstract public void methodB62(int i, short s, float f);
abstract public void methodB62(int i, byte d, float f);
abstract public void methodB63(int i, short s, float f);
abstract public void methodB63(int i, byte d, float f);
abstract public void methodB64(int i, short s, float f);
abstract public void methodB64(int i, byte d, float f);
abstract public void methodB65(int i, short s, float f);
abstract public void methodB65(int i, byte d, float f);
abstract public void methodB66(int i, short s, float f);
abstract public void methodB66(int i, byte d, float f);
abstract public void methodB67(int i, short s, float f);
abstract public void methodB67(int i, byte d, float f);
abstract public void methodB68(int i, short s, float f);
abstract public void methodB68(int i, byte d, float f);
abstract public void methodB69(int i, short s, float f);
abstract public void methodB69(int i, byte d, float f);
abstract public void methodB70(int i, short s, float f);
abstract public void methodB70(int i, byte d, float f);
abstract public void methodB71(int i, short s, float f);
abstract public void methodB71(int i, byte d, float f);
abstract public void methodB72(int i, short s, float f);
abstract public void methodB72(int i, byte d, float f);
abstract public void methodB73(int i, short s, float f);
abstract public void methodB73(int i, byte d, float f);
abstract public void methodB74(int i, short s, float f);
abstract public void methodB74(int i, byte d, float f);
abstract public void methodB75(int i, short s, float f);
abstract public void methodB75(int i, byte d, float f);
abstract public void methodB76(int i, short s, float f);
abstract public void methodB76(int i, byte d, float f);
abstract public void methodB77(int i, short s, float f);
abstract public void methodB77(int i, byte d, float f);
abstract public void methodB78(int i, short s, float f);
abstract public void methodB78(int i, byte d, float f);
abstract public void methodB79(int i, short s, float f);
abstract public void methodB79(int i, byte d, float f);
abstract public void methodB80(int i, short s, float f);
abstract public void methodB80(int i, byte d, float f);
abstract public void methodB81(int i, short s, float f);
abstract public void methodB81(int i, byte d, float f);
abstract public void methodB82(int i, short s, float f);
abstract public void methodB82(int i, byte d, float f);
abstract public void methodB83(int i, short s, float f);
abstract public void methodB83(int i, byte d, float f);
abstract public void methodB84(int i, short s, float f);
abstract public void methodB84(int i, byte d, float f);
abstract public void methodB85(int i, short s, float f);
abstract public void methodB85(int i, byte d, float f);
abstract public void methodB86(int i, short s, float f);
abstract public void methodB86(int i, byte d, float f);
abstract public void methodB87(int i, short s, float f);
abstract public void methodB87(int i, byte d, float f);
abstract public void methodB88(int i, short s, float f);
abstract public void methodB88(int i, byte d, float f);
abstract public void methodB89(int i, short s, float f);
abstract public void methodB89(int i, byte d, float f);
abstract public void methodB90(int i, short s, float f);
abstract public void methodB90(int i, byte d, float f);
abstract public void methodB91(int i, short s, float f);
abstract public void methodB91(int i, byte d, float f);
abstract public void methodB92(int i, short s, float f);
abstract public void methodB92(int i, byte d, float f);
abstract public void methodB93(int i, short s, float f);
abstract public void methodB93(int i, byte d, float f);
abstract public void methodB94(int i, short s, float f);
abstract public void methodB94(int i, byte d, float f);
abstract public void methodB95(int i, short s, float f);
abstract public void methodB95(int i, byte d, float f);
abstract public void methodB96(int i, short s, float f);
abstract public void methodB96(int i, byte d, float f);
abstract public void methodB97(int i, short s, float f);
abstract public void methodB97(int i, byte d, float f);
abstract public void methodB98(int i, short s, float f);
abstract public void methodB98(int i, byte d, float f);
abstract public void methodB99(int i, short s, float f);
abstract public void methodB99(int i, byte d, float f);
abstract public void methodB100(int i, short s, float f);
abstract public void methodB100(int i, byte d, float f);
abstract public void methodB101(int i, short s, float f);
abstract public void methodB101(int i, byte d, float f);
abstract public void methodB102(int i, short s, float f);
abstract public void methodB102(int i, byte d, float f);
abstract public void methodB103(int i, short s, float f);
abstract public void methodB103(int i, byte d, float f);
abstract public void methodB104(int i, short s, float f);
abstract public void methodB104(int i, byte d, float f);
abstract public void methodB105(int i, short s, float f);
abstract public void methodB105(int i, byte d, float f);
abstract public void methodB106(int i, short s, float f);
abstract public void methodB106(int i, byte d, float f);
abstract public void methodB107(int i, short s, float f);
abstract public void methodB107(int i, byte d, float f);
abstract public void methodB108(int i, short s, float f);
abstract public void methodB108(int i, byte d, float f);
abstract public void methodB109(int i, short s, float f);
abstract public void methodB109(int i, byte d, float f);
abstract public void methodB110(int i, short s, float f);
abstract public void methodB110(int i, byte d, float f);
abstract public void methodB111(int i, short s, float f);
abstract public void methodB111(int i, byte d, float f);
abstract public void methodB112(int i, short s, float f);
abstract public void methodB112(int i, byte d, float f);
abstract public void methodB113(int i, short s, float f);
abstract public void methodB113(int i, byte d, float f);
abstract public void methodB114(int i, short s, float f);
abstract public void methodB114(int i, byte d, float f);
abstract public void methodB115(int i, short s, float f);
abstract public void methodB115(int i, byte d, float f);
abstract public void methodB116(int i, short s, float f);
abstract public void methodB116(int i, byte d, float f);
abstract public void methodB117(int i, short s, float f);
abstract public void methodB117(int i, byte d, float f);
abstract public void methodB118(int i, short s, float f);
abstract public void methodB118(int i, byte d, float f);
abstract public void methodB119(int i, short s, float f);
abstract public void methodB119(int i, byte d, float f);
abstract public void methodB120(int i, short s, float f);
abstract public void methodB120(int i, byte d, float f);
}
public void testReallyBigClass() throws IOException {
FastClass.Generator gen = new FastClass.Generator();
gen.setType(ReallyBigClass.class);
FastClass fc = gen.create();
}
public TestFastClass(String testName) {
super(testName);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(TestFastClass.class);
}
} |
package edu.umd.cs.findbugs.log;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Stack;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import edu.umd.cs.findbugs.FindBugs2;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.xml.XMLOutput;
import edu.umd.cs.findbugs.xml.XMLWriteable;
/**
* @author pugh
*/
public class Profiler implements XMLWriteable {
final static boolean REPORT = SystemProperties.getBoolean("profiler.report");
public Profiler() {
startTimes = new Stack<Clock>();
profile = new ConcurrentHashMap<Class<?>, Profile>();
if (REPORT)
System.err.println("Profiling activated");
}
public static interface Filter {
public boolean accepts(Profile p);
}
public static class FilterByTime implements Filter {
private final long minNanoSeconds;
public FilterByTime(long minNanoSeconds) {
this.minNanoSeconds = minNanoSeconds;
}
public boolean accepts(Profile p) {
long time = p.totalTime.get();
if (time < minNanoSeconds) {
return false;
}
return true;
}
}
public static class FilterByTimePerCall implements Filter {
private final long minNanoSeconds;
public FilterByTimePerCall(long minNanoSeconds) {
this.minNanoSeconds = minNanoSeconds;
}
public boolean accepts(Profile p) {
int totalCalls = p.totalCalls.get();
long time = p.totalTime.get();
if (time/totalCalls < minNanoSeconds) {
return false;
}
return true;
}
}
public static class FilterByCalls implements Filter {
private final int minCalls;
public FilterByCalls(int minCalls) {
this.minCalls = minCalls;
}
public boolean accepts(Profile p) {
int totalCalls = p.totalCalls.get();
if (totalCalls < minCalls) {
return false;
}
return true;
}
}
public static class Profile implements XMLWriteable {
/** time in nanoseconds */
final AtomicLong totalTime = new AtomicLong();
final AtomicInteger totalCalls = new AtomicInteger();
/** time in nanoseconds */
final AtomicLong maxTime = new AtomicLong();
final AtomicLong totalSquareMicroseconds = new AtomicLong();
private final String className;
/**
* @param className non null full qualified class name
*/
public Profile(String className) {
this.className = className;
}
public void handleCall(long nanoTime) {
totalCalls.incrementAndGet();
totalTime.addAndGet(nanoTime);
long oldMax = maxTime.get();
if (nanoTime > oldMax)
maxTime.compareAndSet(oldMax, nanoTime);
long microseconds = TimeUnit.MICROSECONDS.convert(nanoTime, TimeUnit.NANOSECONDS);
totalSquareMicroseconds.addAndGet(microseconds * microseconds);
}
/**
* @param xmlOutput
* @throws IOException
*/
public void writeXML(XMLOutput xmlOutput) throws IOException {
long time = totalTime.get();
int callCount = totalCalls.get();
long maxTimeMicros = TimeUnit.MICROSECONDS.convert(maxTime.get(), TimeUnit.NANOSECONDS);
long timeMillis = TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS);
long timeMicros = TimeUnit.MICROSECONDS.convert(time, TimeUnit.NANOSECONDS);
long averageTimeMicros = timeMicros / callCount;
long totalSquareMicros = totalSquareMicroseconds.get();
long averageSquareMicros = totalSquareMicros / callCount;
long timeVariance = averageSquareMicros - averageTimeMicros * averageTimeMicros;
long timeStandardDeviation = (long) Math.sqrt(timeVariance);
if (timeMillis > 10) {
xmlOutput.startTag("ClassProfile");
xmlOutput.addAttribute("name", className);
xmlOutput.addAttribute("totalMilliseconds", String.valueOf(timeMillis));
xmlOutput.addAttribute("invocations", String.valueOf(callCount));
xmlOutput.addAttribute("avgMicrosecondsPerInvocation", String.valueOf(averageTimeMicros));
xmlOutput.addAttribute("maxMicrosecondsPerInvocation", String.valueOf(maxTimeMicros));
xmlOutput.addAttribute("standardDeviationMircosecondsPerInvocation", String.valueOf(timeStandardDeviation));
xmlOutput.stopTag(true);
}
}
}
static class Clock {
final Class<?> clazz;
long startTimeNanos;
long accumulatedTime;
Clock(Class<?> clazz, long currentNanoTime) {
this.clazz = clazz;
startTimeNanos = currentNanoTime;
}
void accumulateTime(long currentNanoTime) {
accumulatedTime += currentNanoTime - startTimeNanos;
}
void restartClock(long currentNanoTime) {
startTimeNanos = currentNanoTime;
}
}
final Stack<Clock> startTimes;
final ConcurrentHashMap<Class<?>, Profile> profile;
public void start(Class<?> c) {
long currentNanoTime = System.nanoTime();
Stack<Clock> stack = startTimes;
if (!stack.isEmpty()) {
stack.peek().accumulateTime(currentNanoTime);
}
stack.push(new Clock(c, currentNanoTime));
// System.err.println("push " + c.getSimpleName());
}
public void end(Class<?> c) {
// System.err.println("pop " + c.getSimpleName());
long currentNanoTime = System.nanoTime();
Stack<Clock> stack = startTimes;
Clock ending = stack.pop();
if (ending.clazz != c) {
throw new AssertionError("Asked to end timing for " + c + " but top of stack is " + ending.clazz
+ ", remaining stack is " + stack);
}
ending.accumulateTime(currentNanoTime);
if (!stack.isEmpty()) {
Clock restarting = stack.peek();
restarting.restartClock(currentNanoTime);
}
long accumulatedTime = ending.accumulatedTime;
if (accumulatedTime == 0) {
return;
}
Profile counter = profile.get(c);
if (counter == null) {
counter = new Profile(c.getName());
Profile counter2 = profile.putIfAbsent(c, counter);
if (counter2 != null) {
counter = counter2;
}
}
counter.handleCall(accumulatedTime);
}
public static class ClassNameComparator implements Comparator<Class<?>>, Serializable {
final protected Profiler profiler;
public ClassNameComparator(Profiler p) {
this.profiler = p;
}
public int compare(Class<?> c1, Class<?> c2) {
return c1.getSimpleName().compareTo(c2.getSimpleName());
}
}
public static class TotalTimeComparator extends ClassNameComparator {
public TotalTimeComparator(Profiler p) {
super(p);
}
@Override
public int compare(Class<?> c1, Class<?> c2) {
long v1 = profiler.getProfile(c1).totalTime.get();
long v2 = profiler.getProfile(c2).totalTime.get();
if (v1 < v2) {
return 1;
}
if (v1 > v2) {
return -1;
}
return super.compare(c1, c2);
}
}
public static class TimePerCallComparator extends ClassNameComparator {
public TimePerCallComparator(Profiler p) {
super(p);
}
@Override
public int compare(Class<?> c1, Class<?> c2) {
Profile profile1 = profiler.getProfile(c1);
Profile profile2 = profiler.getProfile(c2);
long time1 = profile1.totalTime.get() / profile1.totalCalls.get();
long time2 = profile2.totalTime.get() / profile2.totalCalls.get();
if (time1 < time2) {
return 1;
}
if (time1 > time2) {
return -1;
}
return super.compare(c1, c2);
}
}
public static class TotalCallsComparator extends ClassNameComparator {
public TotalCallsComparator(Profiler p) {
super(p);
}
@Override
public int compare(Class<?> c1, Class<?> c2) {
Profile profile1 = profiler.getProfile(c1);
Profile profile2 = profiler.getProfile(c2);
int calls1 = profile1.totalCalls.get();
int calls2 = profile2.totalCalls.get();
if (calls1 < calls2) {
return 1;
}
if (calls1 > calls2) {
return -1;
}
return super.compare(c1, c2);
}
}
/**
* Default implementation uses {@link TotalTimeComparator} and prints out
* class statistics based on total time spent fot a class
*/
public void report() {
if (!REPORT) {
return;
}
report(new TotalTimeComparator(this), new FilterByTime(10000000), System.err);
}
/**
* @param reportComparator non null comparator instance which will be used to sort
* the report statistics
*/
public void report(Comparator<Class<?>> reportComparator, Filter filter, PrintStream stream) {
stream.println("PROFILE REPORT");
try {
TreeSet<Class<?>> treeSet = new TreeSet<Class<?>>(reportComparator);
treeSet.addAll(profile.keySet());
stream.printf("%8s %8s %9s %s%n", "msecs", "#calls", "usecs/call", "Class");
for (Class<?> c : treeSet) {
Profile p = getProfile(c);
long time = p.totalTime.get();
int callCount = p.totalCalls.get();
if (filter.accepts(p)) {
stream.printf("%8d %8d %8d %s%n",
Long.valueOf(TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS)),
Integer.valueOf(callCount),
Long.valueOf(TimeUnit.MICROSECONDS.convert(time / callCount, TimeUnit.NANOSECONDS)),
c.getSimpleName());
}
}
stream.flush();
} catch (RuntimeException e) {
System.err.println(e);
}
}
/**
* Clears the previously accumulated data. This method is public because it
* can be accessed explicitely from clients (like Eclipse).
* <p>
* There is no need to clear profiler data after each run, because a new
* profiler instance is used for each analysis run (see {@link FindBugs2#execute()}).
*/
public void clear() {
profile.clear();
startTimes.clear();
}
Profile getProfile(Class<?> c) {
Profile result = profile.get(c);
if (result == null) {
AnalysisContext.logError("Unexpected null profile for " + c.getName(), new NullPointerException());
result = new Profile(c.getName());
Profile tmp = profile.putIfAbsent(c, result);
if (tmp != null)
return tmp;
}
return result;
}
/*
* (non-Javadoc)
*
* @see
* edu.umd.cs.findbugs.xml.XMLWriteable#writeXML(edu.umd.cs.findbugs.xml
* .XMLOutput)
*/
public void writeXML(XMLOutput xmlOutput) throws IOException {
xmlOutput.startTag("FindBugsProfile");
xmlOutput.stopTag(false);
TreeSet<Class<?>> treeSet = new TreeSet<Class<?>>(new TotalTimeComparator(this));
treeSet.addAll(profile.keySet());
long totalTime = 0;
for(Profile p : profile.values())
totalTime += p.totalTime.get();
long accumulatedTime = 0;
for (Class<?> c : treeSet) {
Profile p = getProfile(c);
if (p == null)
continue;
p.writeXML(xmlOutput);
accumulatedTime += p.totalTime.get();
if (accumulatedTime > totalTime/2)
break;
}
xmlOutput.closeTag("FindBugsProfile");
}
} |
package com.shc.silenceengine.graphics;
import com.shc.silenceengine.core.SilenceEngine;
import com.shc.silenceengine.core.SilenceException;
import com.shc.silenceengine.graphics.opengl.Primitive;
import com.shc.silenceengine.graphics.opengl.Texture;
import com.shc.silenceengine.math.Vector2;
import java.util.ArrayList;
import java.util.List;
/**
* @author Sri Harsha Chilakapati
*/
public class SpriteBatch
{
private List<Sprite> sprites;
private List<Integer> indices;
private List<Vector2> positions;
private boolean active;
public SpriteBatch()
{
sprites = new ArrayList<>();
indices = new ArrayList<>();
positions = new ArrayList<>();
active = false;
}
public void begin()
{
if (active)
throw new SilenceException("SpriteBatch already active");
sprites.clear();
indices.clear();
positions.forEach(Vector2.REUSABLE_STACK::push);
positions.clear();
active = true;
}
public void flush()
{
if (sprites.size() == 0)
return;
sortSprites();
Batcher batcher = SilenceEngine.graphics.getBatcher();
Texture originalTexture = Texture.CURRENT;
Texture texture = sprites.get(indices.get(0)).getTexture();
texture.bind();
Vector2 temp = Vector2.REUSABLE_STACK.pop();
batcher.begin(Primitive.TRIANGLES);
{
for (int i : indices)
{
Sprite sprite = sprites.get(i);
Vector2 position = positions.get(i);
Texture t = sprite.getTexture();
if (t.getID() != texture.getID())
{
batcher.end();
texture = t;
t.bind();
batcher.begin(Primitive.TRIANGLES);
}
// Triangle 1
batcher.vertex(temp.set(-t.getWidth() / 2, -t.getHeight() / 2) // Top-left
.rotateSelf(sprite.getRotation())
.scaleSelf(sprite.getScaleX(), sprite.getScaleY())
.addSelf(position).addSelf(t.getWidth() / 2, t.getHeight() / 2));
batcher.texCoord(t.getMinU(), t.getMinV());
batcher.vertex(temp.set(t.getWidth() / 2, -t.getHeight() / 2) // Top-right
.rotateSelf(sprite.getRotation())
.scaleSelf(sprite.getScaleX(), sprite.getScaleY())
.addSelf(position).addSelf(t.getWidth() / 2, t.getHeight() / 2));
batcher.texCoord(t.getMaxU(), t.getMinV());
batcher.vertex(temp.set(-t.getWidth() / 2, t.getHeight() / 2) // Bottom-left
.rotateSelf(sprite.getRotation())
.scaleSelf(sprite.getScaleX(), sprite.getScaleY())
.addSelf(position).addSelf(t.getWidth() / 2, t.getHeight() / 2));
batcher.texCoord(t.getMinU(), t.getMaxV());
// Triangle 2
batcher.vertex(temp.set(t.getWidth() / 2, -t.getHeight() / 2) // Top-right
.rotateSelf(sprite.getRotation())
.scaleSelf(sprite.getScaleX(), sprite.getScaleY())
.addSelf(position).addSelf(t.getWidth() / 2, t.getHeight() / 2));
batcher.texCoord(t.getMaxU(), t.getMinV());
batcher.vertex(temp.set(t.getWidth() / 2, t.getHeight() / 2) // Bottom-right
.rotateSelf(sprite.getRotation())
.scaleSelf(sprite.getScaleX(), sprite.getScaleY())
.addSelf(position).addSelf(t.getWidth() / 2, t.getHeight() / 2));
batcher.texCoord(t.getMaxU(), t.getMaxV());
batcher.vertex(temp.set(-t.getWidth() / 2, t.getHeight() / 2) // Bottom-left
.rotateSelf(sprite.getRotation())
.scaleSelf(sprite.getScaleX(), sprite.getScaleY())
.addSelf(position).addSelf(t.getWidth() / 2, t.getHeight() / 2));
batcher.texCoord(t.getMinU(), t.getMaxV());
}
}
batcher.end();
Vector2.REUSABLE_STACK.push(temp);
sprites.clear();
indices.clear();
positions.forEach(Vector2.REUSABLE_STACK::push);
positions.clear();
originalTexture.bind();
}
public void end()
{
if (!active)
throw new SilenceException("SpriteBatch is not active");
flush();
active = false;
}
private void sortSprites()
{
// Only sort the indices
indices.sort((i, j) -> sprites.get(i).getTexture().getID() - sprites.get(j).getTexture().getID());
}
public void addSprite(Sprite sprite, Vector2 position)
{
sprites.add(sprite);
positions.add(Vector2.REUSABLE_STACK.pop().set(position));
indices.add(sprites.size() - 1);
}
} |
package com.themike10452.purityu2d;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.widget.Toast;
import java.io.File;
import eu.chainfire.libsuperuser.Shell;
public class DownloadService extends Service {
public static boolean download_in_progress;
public DownloadManager downloadManager;
public long queueID;
private String zip_name, http_url, OPTIONS, NOTIFICATION_TAG = "U2D";
private int NOTIFICATION_ID = 10452;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
OPTIONS = "";
if (intent != null && intent.getExtras().containsKey("0x0")) {
zip_name = intent.getExtras().getString("0x0").trim();
}
if (intent != null && intent.getExtras().containsKey("0x1")) {
http_url = intent.getExtras().getString("0x1");
}
if (intent != null && intent.getExtras().containsKey("0x2")) {
//maintain kernel
if (intent.getExtras().getBoolean("0x2"))
OPTIONS += lib.ACTION_MAINTAIN_KERNEL;
}
if (intent != null && intent.getExtras().containsKey("0x3")) {
//wipe cache and dalvik
if (intent.getExtras().getBoolean("0x3"))
OPTIONS += lib.ACTION_CLEAR_CACHE;
}
if (zip_name != null && http_url != null) {
Receiver receiver = new Receiver();
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
registerReceiver(receiver, new IntentFilter(lib.FLAG_ACTION_REBOOT));
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(http_url.trim()));
request.setTitle(getString(R.string.title_notification))
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
.setDescription(zip_name.trim())
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, zip_name.trim());
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + zip_name.trim());
if (file.isFile())
file.delete();
queueID = downloadManager.enqueue(request);
download_in_progress = true;
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), R.string.message_failure_URL, Toast.LENGTH_LONG).show();
DownloadActivity activity = DownloadActivity.THIS;
activity.updateMessage(R.string.message_failure_URL);
}
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
downloadManager.remove(queueID);
download_in_progress = false;
}
public class Receiver extends BroadcastReceiver {
private NotificationManager manager;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
download_in_progress = false;
boolean md5_matches = true;
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + zip_name.trim());
String md5check, md5sum;
try {
String device = Shell.SU.run(String.format("cat %s | grep %s", lib.buildProp, lib.devicePropTag)).get(0).split("=")[1].trim();
md5check = Shell.SH.run(String.format("cat %s | grep %s", getFilesDir() + "/host", device + "_md5=")).get(0).split("=")[1].trim();
md5sum = Shell.SH.run("md5sum " + file.toString()).get(0).split(" ")[0].trim();
if (!md5sum.equals(md5check))
md5_matches = false;
} catch (Exception ignored) {
md5sum = "";
}
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(queueID);
Cursor c = downloadManager.query(query);
if (c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
Intent notify = new Intent(lib.FLAG_ACTION_REBOOT);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, notify, 0);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(getApplicationContext());
if (md5_matches) {
builder.setContentTitle(getString(R.string.message_downloadComplete))
.setSmallIcon(R.drawable.purity)
.setContentText(getString(R.string.message_clickInstall))
.setContentIntent(pendingIntent);
} else {
builder.setContentTitle(getString(R.string.messgae_failure_badDownload))
.setSmallIcon(R.drawable.purity)
.setContentText(getString(R.string.messgae_failure_badMD5) + String.format(" %s", md5sum));
}
manager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, builder.build());
try {
DownloadActivity activity = DownloadActivity.THIS;
activity.updateMessage(R.string.message_downloadComplete);
} catch (Exception ignored) {
}
} else {
try {
DownloadActivity activity = DownloadActivity.THIS;
activity.updateMessage(R.string.message_downloadAborted);
} catch (Exception ignored) {
}
}
} else {
try {
DownloadActivity activity = DownloadActivity.THIS;
activity.updateMessage(R.string.message_downloadAborted);
} catch (Exception ignored) {
}
}
} else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
Intent i = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} else if (action.equals(lib.FLAG_ACTION_REBOOT)) {
if (manager != null)
manager.cancel(NOTIFICATION_TAG, NOTIFICATION_ID);
new Scripter() {
@Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(getApplicationContext(), R.string.message_rebooting, Toast.LENGTH_LONG).show();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
Shell.SU.run("reboot recovery");
return null;
}
}.execute();
}
}.execute(zip_name, OPTIONS);
}
}
}
} |
package com.virjar.sipsoup.parse;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.virjar.sipsoup.exception.NoSuchAxisException;
import com.virjar.sipsoup.exception.XpathSyntaxErrorException;
import com.virjar.sipsoup.function.FunctionEnv;
import com.virjar.sipsoup.function.axis.AxisFunction;
import com.virjar.sipsoup.model.Predicate;
import com.virjar.sipsoup.model.XpathChain;
import com.virjar.sipsoup.model.XpathEvaluator;
import com.virjar.sipsoup.model.XpathNode;
import com.virjar.sipsoup.parse.expression.ExpressionParser;
import com.virjar.sipsoup.parse.expression.SyntaxNode;
import lombok.Getter;
public class XpathStateMachine {
private static Map<String, XpathNode.ScopeEm> scopeEmMap = Maps.newHashMap();
static {
scopeEmMap.put("/", XpathNode.ScopeEm.INCHILREN);
scopeEmMap.put("//", XpathNode.ScopeEm.RECURSIVE);
scopeEmMap.put("./", XpathNode.ScopeEm.CUR);
scopeEmMap.put(".//", XpathNode.ScopeEm.CURREC);
}
private static List<String> scopeList = Lists.newArrayList("
@Getter
private BuilderState state = BuilderState.SCOPE;
private TokenQueue tokenQueue;
@Getter
private XpathEvaluator evaluator = new XpathEvaluator.AnanyseStartEvaluator();
private XpathChain xpathChain = new XpathChain();
XpathStateMachine(TokenQueue tokenQueue) {
this.tokenQueue = tokenQueue;
}
enum BuilderState {
SCOPE {
@Override
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
stateMachine.tokenQueue.consumeWhitespace();
char xpathFlag = '`';
if (stateMachine.tokenQueue.matchesAny(xpathFlag, '(')) {
String subXpath;
if (stateMachine.tokenQueue.matchesAny(xpathFlag)) {
subXpath = stateMachine.tokenQueue.chompBalanced(xpathFlag, xpathFlag);
} else {
subXpath = stateMachine.tokenQueue.chompBalanced('(', ')');
}
if(StringUtils.isBlank(subXpath)){
throw new XpathSyntaxErrorException(0,"\"()\" empty sub xpath fond");
}
// subXpath = TokenQueue.unescape(subXpath);
// TODO
XpathEvaluator subTree = new XpathParser(subXpath).parse();
stateMachine.evaluator = stateMachine.evaluator.wrap(subTree);
return;
}
if (stateMachine.tokenQueue.matchesAny("and", "&")) {
if (stateMachine.tokenQueue.matches("&")) {
stateMachine.tokenQueue.consume("&");
} else {
stateMachine.tokenQueue.advance("and".length());
}
XpathEvaluator tempEvaluator = stateMachine.evaluator;
if (!(tempEvaluator instanceof XpathEvaluator.AndEvaluator)) {
XpathEvaluator newEvaluator = new XpathEvaluator.AndEvaluator();
stateMachine.evaluator = tempEvaluator.wrap(newEvaluator);
}
stateMachine.evaluator = stateMachine.evaluator
.wrap(new XpathEvaluator.ChainEvaluator(stateMachine.xpathChain.getXpathNodeList()));
stateMachine.xpathChain = new XpathChain();
return;
}
if (stateMachine.tokenQueue.matchesAny("or", "|")) {
if (stateMachine.tokenQueue.matches("|")) {
stateMachine.tokenQueue.consume("|");
} else {
stateMachine.tokenQueue.advance("or".length());
}
XpathEvaluator tempEvaluator = stateMachine.evaluator;
if (!(tempEvaluator instanceof XpathEvaluator.OrEvaluator)) {
XpathEvaluator newEvaluator = new XpathEvaluator.OrEvaluator();
stateMachine.evaluator = tempEvaluator.wrap(newEvaluator);
}
stateMachine.evaluator = stateMachine.evaluator
.wrap(new XpathEvaluator.ChainEvaluator(stateMachine.xpathChain.getXpathNodeList()));
stateMachine.xpathChain = new XpathChain();
return;
}
for (String scope : scopeList) {
if (stateMachine.tokenQueue.matches(scope)) {
stateMachine.tokenQueue.consume(scope);
XpathNode xpathNode = new XpathNode();
xpathNode.setScopeEm(scopeEmMap.get(scope));
stateMachine.xpathChain.getXpathNodeList().add(xpathNode);
stateMachine.state = AXIS;
return;
}
}
throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
"can not recognize token:" + stateMachine.tokenQueue.remainder());
}
},
AXIS {
@Override
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
if (!stateMachine.tokenQueue.hasAxis()) {
stateMachine.state = TAG;
return;
}
String axisFunctionStr = stateMachine.tokenQueue.consumeTo("::");
stateMachine.tokenQueue.consume("::");
TokenQueue functionTokenQueue = new TokenQueue(axisFunctionStr);
String functionName = functionTokenQueue.consumeCssIdentifier().trim();
functionTokenQueue.consumeWhitespace();
AxisFunction axisFunction = FunctionEnv.getAxisFunction(functionName);
if (axisFunction == null) {
throw new NoSuchAxisException(stateMachine.tokenQueue.nowPosition(),
"not such axis " + functionName);
}
stateMachine.xpathChain.getXpathNodeList().getLast().setAxis(axisFunction);
if (functionTokenQueue.isEmpty()) {
stateMachine.state = TAG;
return;
}
if (!functionTokenQueue.matches("(")) {
throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
"expression is not a function:\"" + axisFunctionStr + "\"");
}
String paramList = StringUtils.trimToEmpty(functionTokenQueue.chompBalanced('(', ')'));
functionTokenQueue.consumeWhitespace();
if (!functionTokenQueue.isEmpty()) {
throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
"expression is not a function: \"" + axisFunctionStr + "\" can not recognize token:"
+ functionTokenQueue.remainder());
}
TokenQueue paramTokenQueue = new TokenQueue(paramList);
LinkedList<String> params = Lists.newLinkedList();
while (!paramTokenQueue.isEmpty()) {
paramTokenQueue.consumeWhitespace();
if (!paramTokenQueue.isEmpty() && paramTokenQueue.peek() == ',') {
paramTokenQueue.advance();
paramTokenQueue.consumeWhitespace();
}
String param;
if (paramTokenQueue.matches("\"")) {
param = paramTokenQueue.chompBalanced('\"', '\"');
if (paramTokenQueue.peek() == ',') {
paramTokenQueue.consume();
}
} else if (paramTokenQueue.matches("\'")) {
param = paramTokenQueue.chompBalanced('\'', '\'');
if (paramTokenQueue.peek() == ',') {
paramTokenQueue.consume();
}
} else {
param = paramTokenQueue.consumeTo(",");
if (StringUtils.isEmpty(param)) {
continue;
}
}
params.add(TokenQueue.unescape(StringUtils.trimToEmpty(param)));
}
stateMachine.xpathChain.getXpathNodeList().getLast().setAxisParams(params);
stateMachine.state = TAG;
}
},
TAG {
@Override
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
stateMachine.tokenQueue.consumeWhitespace();
if (stateMachine.tokenQueue.peek() == '*') {
stateMachine.tokenQueue.advance();
stateMachine.tokenQueue.consumeWhitespace();
stateMachine.xpathChain.getXpathNodeList().getLast()
.setSelectFunction(FunctionEnv.getSelectFunction("tag"));
stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(Lists.newArrayList("*"));
stateMachine.state = PREDICATE;
return;
}
if (stateMachine.tokenQueue.matchesFunction()) {
String function = stateMachine.tokenQueue.consumeFunction();
TokenQueue functionTokenQueue = new TokenQueue(function);
String functionName = functionTokenQueue.consumeTo("(");
LinkedList<String> params = Lists.newLinkedList();
TokenQueue paramTokenQueue = new TokenQueue(StringUtils.trimToEmpty(functionTokenQueue.chompBalanced('(', ')')));
while ((paramTokenQueue.consumeWhitespace() && !paramTokenQueue.consumeWhitespace())
|| !paramTokenQueue.isEmpty()) {
String param;
if (paramTokenQueue.matches("\"")) {
param = paramTokenQueue.chompBalanced('\"', '\"');
if (paramTokenQueue.peek() == ',') {
paramTokenQueue.advance();
}
} else if (paramTokenQueue.matches("\'")) {
param = paramTokenQueue.chompBalanced('\'', '\'');
if (paramTokenQueue.peek() == ',') {
paramTokenQueue.advance();
}
} else {
param = paramTokenQueue.consumeTo(",");
}
params.add(TokenQueue.unescape(StringUtils.trimToEmpty(param)));
}
stateMachine.xpathChain.getXpathNodeList().getLast()
.setSelectFunction(FunctionEnv.getSelectFunction(functionName));
stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(params);
stateMachine.state = PREDICATE;// TODO ,,
return;
}
if (stateMachine.tokenQueue.matches("@")) {
stateMachine.tokenQueue.advance();
stateMachine.tokenQueue.consumeWhitespace();
stateMachine.xpathChain.getXpathNodeList().getLast()
.setSelectFunction(FunctionEnv.getSelectFunction("@"));
if (stateMachine.tokenQueue.peek() == '*') {
stateMachine.tokenQueue.advance();
stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(Lists.newArrayList("*"));
} else {
String attributeKey = stateMachine.tokenQueue.consumeAttributeKey();
stateMachine.xpathChain.getXpathNodeList().getLast()
.setSelectParams(Lists.newArrayList(attributeKey));
}
stateMachine.state = PREDICATE;
stateMachine.tokenQueue.consumeWhitespace();
return;
}
String tagName = stateMachine.tokenQueue.consumeTagName();
if (StringUtils.isEmpty(tagName)) {
throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
"can not recognize token,expected start with a tagName,actually is:"
+ stateMachine.tokenQueue.remainder());
}
stateMachine.xpathChain.getXpathNodeList().getLast()
.setSelectFunction(FunctionEnv.getSelectFunction("tag"));
stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(Lists.newArrayList(tagName));
stateMachine.state = PREDICATE;
}
},
PREDICATE {
@Override
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
stateMachine.tokenQueue.consumeWhitespace();
if (stateMachine.tokenQueue.matches("[")) {
String predicate = stateMachine.tokenQueue.chompBalanced('[', ']');
SyntaxNode predicateTree = new ExpressionParser(new TokenQueue(predicate)).parse();
stateMachine.xpathChain.getXpathNodeList().getLast()
.setPredicate(new Predicate(StringUtils.trimToEmpty(predicate), predicateTree));
}
// check
stateMachine.tokenQueue.consumeWhitespace();
// if (!stateMachine.tokenQueue.isEmpty() && !stateMachine.tokenQueue.matches("/")) {
// throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
if (stateMachine.tokenQueue.isEmpty()) {
stateMachine.state = END;
stateMachine.evaluator = stateMachine.evaluator
.wrap(new XpathEvaluator.ChainEvaluator(stateMachine.xpathChain.getXpathNodeList()));
stateMachine.xpathChain = new XpathChain();
} else {
stateMachine.state = SCOPE;
}
}
},
END {
@Override
public void parse(XpathStateMachine stateMachine) {
}
};
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
}
}
} |
package com.wasteofplastic.beaconz;
import java.util.Random;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.generator.BlockPopulator;
import com.wasteofplastic.include.it.unimi.dsi.util.XorShift;
/**
* BeaconPopulator class
* @author TastyBento
*
* This is called every time a chunk is (re)generated in the world
* The idea is to place a single beacon on a chunk if a XorShift
* generates a random number below the Settings.distribution threshold
* If Settings.distribution were 1, every chunk would get a single beacon;
* the lower it is, the fewer chunks get a beacon and the beacons
* are more spread out in the world.
*
*
*/
public class BeaconPopulator extends BlockPopulator {
private final Beaconz plugin;
public BeaconPopulator(Beaconz plugin) {
this.plugin = plugin;
}
@Override
public void populate(World world, Random unused, Chunk source) {
//Bukkit.getLogger().info("DEBUG: populator called. ");
// If we're regenerating this chunk from within the game (e.g. a "reset" command), don't do anything
/*
boolean regen = false;
if (Settings.populate.contains(new Pair(source.getX(),source.getZ()))) {
plugin.getLogger().info("DEBUG: POPULATING chunk: " + source.getX() + ":" + source.getZ());
regen = true;
}
regen = true;*/
// Don't bother to make anything if it is outside the border. Make it just a bit smaller than the border
// THERE IS NO BORDER ANYMORE, THIS MAY BE REMOVED
if (Settings.borderSize > 0) {
int minX = (Settings.xCenter - Settings.borderSize/2) / 16 + 1;
int minZ = (Settings.zCenter - Settings.borderSize/2) / 16 + 1;
int maxX = (Settings.xCenter + Settings.borderSize/2) / 16 - 1;
int maxZ = (Settings.zCenter + Settings.borderSize/2) / 16 - 1;
if (source.getX() < minX || source.getX() > maxX || source.getZ() < minZ || source.getZ() > maxZ) {
return;
}
}
// Make sure we're within the boundaries of a game
if (plugin.getGameMgr() != null) {
if (plugin.getGameMgr().getLobby() == null) {
// No lobby yet
return;
}
// Don't do anything in the lobby
if (plugin.getGameMgr().getLobby().containsPoint(source.getX() * 16, source.getZ() * 16)) {
return;
}
// Don't do anything unless inside a region
// Check min coords
Region region = plugin.getGameMgr().getRegion(source.getX() * 16, source.getZ() * 16);
if (region == null) {
return;
}
// Check max coords of this chunk
region = plugin.getGameMgr().getRegion(source.getX() * 16 + 15, source.getZ() * 16 + 15);
if (region == null) {
return;
}
}
//plugin.getLogger().info("DEBUG: Populating chunk: " + source.getX() + ":" + source.getZ());
// pseudo-randomly place a beacon
XorShift gen=new XorShift(new long[] {
source.getX(),
source.getZ(),
world.getSeed(),
Settings.seedAdjustment
});
double nd = gen.nextDouble();
//plugin.getLogger().info("DEBUG: next double = " + nd);
if (nd < Settings.distribution) {
int x = gen.nextInt(16);
int z = gen.nextInt(16);
// Check if there is already a beacon here, if so, don't make it again
if (plugin.getRegister().getBeaconAt((source.getX() * 16 + x), (source.getZ()*16 + z)) != null) {
plugin.getLogger().info("DEBUG: Beacon already at " + (source.getX() * 16 + x) + "," + (source.getZ()*16 + z));
return;
}
plugin.getLogger().info("DEBUG: Creating beacon at " + (source.getX() * 16 + x) + "," + (source.getZ()*16 + z));
int y = source.getChunkSnapshot().getHighestBlockYAt(x, z);
Block b = source.getBlock(x, y, z);
// Don't make in the ocean or deep ocean because they are too easy to find.
// Frozen ocean okay for now.
if (b.getBiome().equals(Biome.OCEAN) || b.getBiome().equals(Biome.DEEP_OCEAN)) {
return;
}
while (b.getType().equals(Material.AIR) || b.getType().equals(Material.LEAVES) || b.getType().equals(Material.LEAVES_2)
|| b.getType().equals(Material.HUGE_MUSHROOM_1) || b.getType().equals(Material.HUGE_MUSHROOM_2)) {
y
if (y == 0) {
// Oops, nothing here
return;
}
b = source.getBlock(x, y, z);
}
// Else make it into a beacon
//beacons.add(new Vector(x,y,z));
//Bukkit.getLogger().info("DEBUG: made beacon at " + (source.getX() * 16 + x) + " " + y + " " + (source.getZ()*16 + z) );
b.setType(Material.BEACON);
// Add the capstone
b.getRelative(BlockFace.UP).setType(Material.OBSIDIAN);
// Create the pyramid
b = b.getRelative(BlockFace.DOWN);
// All diamond blocks for now
b.setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.SOUTH).setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.SOUTH_EAST).setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.SOUTH_WEST).setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.EAST).setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.WEST).setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.NORTH).setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.NORTH_EAST).setType(Material.DIAMOND_BLOCK);
b.getRelative(BlockFace.NORTH_WEST).setType(Material.DIAMOND_BLOCK);
// Register the beacon
plugin.getRegister().addBeacon(null, (source.getX() * 16 + x), y, (source.getZ()*16 + z));
}
}
} |
package comp3500.abn.emitters.odlconfig;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.ripe.db.whois.common.rpsl.AttributeType;
import net.ripe.db.whois.common.rpsl.ObjectType;
import net.ripe.db.whois.common.rpsl.RpslAttribute;
import net.ripe.db.whois.common.rpsl.RpslObject;
import net.ripe.db.whois.common.rpsl.attrs.AttributeParseException;
import net.ripe.db.whois.common.rpsl.attrs.AutNum;
import org.apache.commons.lang3.tuple.Pair;
import comp3500.abn.rpsl.AttributeLexerWrapper;
/**
* Represents the speakers of the OpenDaylight configuration file.
* @author Benjamin George Roberts
*/
public class BGPSpeaker {
//List of route attribtue types parsed
private static final AttributeType[] ROUTE_TYPES = {AttributeType.IMPORT, AttributeType.EXPORT, AttributeType.DEFAULT};
private static final String DEFAULT_SPEAKER_ADDRESS = "0.0.0.0";
/*
* Template values
*/
String name,
speakerAddress = DEFAULT_SPEAKER_ADDRESS, //By default, bi
peerRegistry,
asn;
AutNum serverASN = null;
private RpslObject autnumObject = null;
private Map<AutNum, BGPPeer> bgpPeers = null;
/**
* Create a new {@link BGPSpeaker} object. Initialises the template fields.
* @param object an AUT_NUM {@link RpslObject}
*/
public BGPSpeaker(RpslObject object) {
//Sanity check the object type
if(object.getType() != ObjectType.AUT_NUM)
throw new IllegalArgumentException("Tried to instantiate BGPServer with " + object.getType().getName().toString());
else
autnumObject = object;
//This parse method can throw an error. We can't really recover so we won't catch it
asn = "AS" + AutNum.parse(autnumObject.getTypeAttribute().getCleanValue()).getValue();
name = autnumObject.getValueForAttribute(AttributeType.AS_NAME).toString();
peerRegistry = name + "-registry";
}
/**
* Using the {@link RpslObject} the speaker was initialised with, this method will create the required
* {@link BGPPeer} instances. This is done by extracting the ASN's from each Import, Export or Default
* attribute, creating or retrieving the {@link BGPPeer} and passing the attribute (with routing information)
* to the {@link BGPPeer}. If the table of {@link BGPPeer}s has already been built, the method will return it.
* @return The BGPPeers associated with this speaker
*/
public Collection<BGPPeer> getPeers() {
//TODO Doesn't take IP addresses into account
//TODO Doesn't pass actions to the BGPPeers
//short circuit if already run
if(bgpPeers != null)
return bgpPeers.values();
else
bgpPeers = new HashMap<AutNum, BGPPeer>();
//Run for each of the attribute types
for(AttributeType attrType : ROUTE_TYPES) {
AttributeLexerWrapper lexer = null;
//Try get the lexer for this attribute type
try {
lexer = new AttributeLexerWrapper(attrType.toString());
} catch (ClassNotFoundException e) {
System.err.println("Class not found for LexerWrapper while adding peers: " + attrType.toString());
continue;
}
//Find attributes of current route type
for(RpslAttribute attr : autnumObject.findAttributes(attrType)) {
List<BGPPeer> currentRoutePeers = new LinkedList<BGPPeer>();
List<Pair<String, List<String>>> parsedAttribute;
//Parse the current attribute
try {
parsedAttribute = lexer.parse(new StringReader(attr.toString()));
} catch (IOException e) {
System.err.println("IO error parsing attributes: " + attr.toString());
continue;
}
//Look for peer entries, these follow from (import) or to
for(Pair<String, List<String>> tokenPair : parsedAttribute) {
//Check for tokens containing the speaker address
if(tokenPair.getLeft().equals("at")) {
addSpeakerAddress(tokenPair.getRight());
continue;
}
//Skip tokens which don't have peers in them
if(!tokenPair.getLeft().equals((attrType == AttributeType.IMPORT) ? "from" : "to")
|| tokenPair.getRight().size() < 1)
continue;
//Add BGPPeer to the list we will add the route to. Create if non existant
try {
AutNum asn = AutNum.parse(tokenPair.getRight().get(0));
if(!bgpPeers.containsKey(asn))
bgpPeers.put(asn, new BGPPeer(this, asn));
currentRoutePeers.add(bgpPeers.get(asn));
} catch (AttributeParseException e) {
System.err.println("Failed to parse ASN: " + tokenPair.getRight().get(0));
continue;
}
}
//Add the route attribute to the peers
for(BGPPeer peer : currentRoutePeers)
peer.addRoutes(parsedAttribute, attrType);
}
}
//Return the list of peers
return bgpPeers.values();
}
/**
* Attempts to set the address of the {@link BGPSpeaker}. Currently, the address can only
* be changed once from DEFAULT_SPEAKER_ADDRESS; other changes are ignored and report warnings.
* @param addressList
*/
private void addSpeakerAddress(List<String> addressList) {
//TODO doesnt handle multiple addresses for the same speaker
if(addressList.size() < 1) {
return;
} else {
if(addressList.size() > 1)
System.err.println("Warning: Multiple speaker addresses in same attribute are not supported.");
//Check if we are setting a 2nd, non default address
if(!(addressList.get(0).equals(speakerAddress) || speakerAddress.equals(DEFAULT_SPEAKER_ADDRESS)))
System.err.println("Warning: Speakers with multiple addresses are not supported");
else
speakerAddress = addressList.get(0);
}
}
} |
package de.flux.playground.deckcompare;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import de.flux.playground.deckcompare.analyze.CardConflictAnalyzer;
import de.flux.playground.deckcompare.analyze.DeckConflictAnalyzer;
@SpringBootApplication
public class Deckcompare {
public static void main(String[] args) throws Exception {
SpringApplication.run(Deckcompare.class, args);
}
@Bean
public DeckConflictAnalyzer deckConflictAnalyzer() {
return new DeckConflictAnalyzer();
}
@Bean
public CardConflictAnalyzer cardConflictAnalyzer() {
return new CardConflictAnalyzer();
}
} |
package de.slikey.effectlib.math;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
import net.objecthunter.exp4j.function.Function;
import org.bukkit.configuration.ConfigurationSection;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
public class EquationTransform implements Transform {
private Expression expression;
private static Function randFunction;
private final Set<String> inputVariables;
private boolean quiet;
private Exception exception;
@Override
public void load(ConfigurationSection parameters) {
setEquation(parameters.getString("equation", ""));
}
public EquationTransform() {
inputVariables = new HashSet<String>();
}
public EquationTransform(String equation) {
this(equation, "t");
}
public EquationTransform(String equation, String inputVariable) {
inputVariables = new HashSet<String>();
inputVariables.add(inputVariable);
setEquation(equation);
}
public EquationTransform(String equation, String... inputVariables) {
this.inputVariables = new HashSet<String>();
for (String inputVariable : inputVariables) {
this.inputVariables.add(inputVariable);
}
setEquation(equation);
}
public EquationTransform(String equation, Set<String> inputVariables) {
this.inputVariables = inputVariables;
setEquation(equation);
}
public boolean setEquation(String equation) {
try {
exception = null;
if (randFunction == null) {
randFunction = new Function("rand", 2) {
private Random random = new Random();
@Override
public double apply(double... args) {
return random.nextDouble() * (args[1] - args[0]) + args[0];
}
};
}
expression = new ExpressionBuilder(equation)
.function(randFunction)
.variables(inputVariables)
.build();
} catch (Exception ex) {
expression = null;
exception = ex;
if (!quiet) {
org.bukkit.Bukkit.getLogger().log(Level.WARNING, ex.getMessage());
}
}
return exception == null;
}
@Override
public double get(double t) {
if (expression == null) {
return 0;
}
for (String inputVariable : inputVariables) {
expression.setVariable(inputVariable, t);
}
return get();
}
public double get(double... t) {
if (expression == null) {
return 0;
}
int index = 0;
for (String inputVariable : inputVariables) {
expression.setVariable(inputVariable, t[index]);
if (index < t.length - 1) index++;
}
return get();
}
public void addVariable(String key) {
inputVariables.add(key);
}
public void setVariable(String key, double value) {
if (expression != null) {
expression.setVariable(key, value);
}
}
public double get() {
if (expression == null) {
return Double.NaN;
}
double value = Double.NaN;
try {
exception = null;
value = expression.evaluate();
} catch (Exception ex) {
exception = ex;
if (!quiet) {
org.bukkit.Bukkit.getLogger().log(Level.WARNING, ex.getMessage());
}
}
return value;
}
public void setQuiet(boolean quiet) {
this.quiet = quiet;
}
public Exception getException() {
return exception;
}
} |
package hprose.io.unserialize;
import hprose.io.HproseTags;
import hprose.util.DateTime;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.Date;
final class DateTimeUnserializer implements HproseUnserializer, HproseTags {
public final static DateTimeUnserializer instance = new DateTimeUnserializer();
@SuppressWarnings({"deprecation"})
private static Date toDate(Object obj) {
if (obj instanceof DateTime) {
return ((DateTime)obj).toDateTime();
}
return new Date(obj.toString());
}
@SuppressWarnings({"deprecation"})
final static Date read(HproseReader reader, ByteBuffer buffer) throws IOException {
int tag = buffer.get();
if (tag == TagDate) return DefaultUnserializer.readDateTime(reader, buffer).toDateTime();
if (tag == TagTime) return DefaultUnserializer.readTime(reader, buffer).toDateTime();
if (tag == TagNull || tag == TagEmpty) return null;
if (tag == TagRef) return toDate(reader.readRef(buffer));
switch (tag) {
case '0': return new Date(0l);
case '1': return new Date(1l);
case '2': return new Date(2l);
case '3': return new Date(3l);
case '4': return new Date(4l);
case '5': return new Date(5l);
case '6': return new Date(6l);
case '7': return new Date(7l);
case '8': return new Date(8l);
case '9': return new Date(9l);
case TagInteger:
case TagLong: return new Date(ValueReader.readLong(buffer));
case TagDouble: return new Date(Double.valueOf(ValueReader.readDouble(buffer)).longValue());
case TagString: return new Date(StringUnserializer.readString(reader, buffer));
default: throw ValueReader.castError(reader.tagToString(tag), Date.class);
}
}
@SuppressWarnings({"deprecation"})
final static Date read(HproseReader reader, InputStream stream) throws IOException {
int tag = stream.read();
if (tag == TagDate) return DefaultUnserializer.readDateTime(reader, stream).toDateTime();
if (tag == TagTime) return DefaultUnserializer.readTime(reader, stream).toDateTime();
if (tag == TagNull || tag == TagEmpty) return null;
if (tag == TagRef) return toDate(reader.readRef(stream));
switch (tag) {
case '0': return new Date(0l);
case '1': return new Date(1l);
case '2': return new Date(2l);
case '3': return new Date(3l);
case '4': return new Date(4l);
case '5': return new Date(5l);
case '6': return new Date(6l);
case '7': return new Date(7l);
case '8': return new Date(8l);
case '9': return new Date(9l);
case TagInteger:
case TagLong: return new Date(ValueReader.readLong(stream));
case TagDouble: return new Date(Double.valueOf(ValueReader.readDouble(stream)).longValue());
case TagString: return new Date(StringUnserializer.readString(reader, stream));
default: throw ValueReader.castError(reader.tagToString(tag), Date.class);
}
}
public final Object read(HproseReader reader, ByteBuffer buffer, Class<?> cls, Type type) throws IOException {
return read(reader, buffer);
}
public final Object read(HproseReader reader, InputStream stream, Class<?> cls, Type type) throws IOException {
return read(reader, stream);
}
} |
package io.github.classgraph;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import nonapi.io.github.classgraph.utils.JarUtils;
/** {@link ClassLoader} for classes found by ClassGraph during scanning. */
class ClassGraphClassLoader extends ClassLoader {
/** The scan result. */
private final ScanResult scanResult;
/**
* Constructor.
*
* @param scanResult
* The ScanResult.
*/
ClassGraphClassLoader(final ScanResult scanResult) {
super(null);
this.scanResult = scanResult;
registerAsParallelCapable();
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#findClass(java.lang.String)
*/
@Override
protected Class<?> findClass(final String className)
throws ClassNotFoundException, LinkageError, SecurityException {
// Use cached class, if it is already loaded
final Class<?> loadedClass = findLoadedClass(className);
if (loadedClass != null) {
return loadedClass;
}
// Get ClassInfo for named class
final ClassInfo classInfo = scanResult.getClassInfo(className);
// Try environment classloaders first
boolean triedClassInfoLoader = false;
final ClassLoader[] classLoaderOrder = scanResult.getClassLoaderOrderRespectingParentDelegation();
if (classLoaderOrder != null) {
// Try environment classloaders
for (final ClassLoader envClassLoader : classLoaderOrder) {
try {
return Class.forName(className, scanResult.scanSpec.initializeLoadedClasses, envClassLoader);
} catch (ClassNotFoundException | NoClassDefFoundError e) {
// Ignore
}
if (classInfo != null && envClassLoader == classInfo.classLoader) {
triedClassInfoLoader = true;
}
}
}
// Try null classloader (ClassGraph's classloader)
try {
return Class.forName(className, scanResult.scanSpec.initializeLoadedClasses, null);
} catch (ClassNotFoundException | NoClassDefFoundError e) {
// Ignore
}
// Try specific classloader for the classpath element that the classfile was obtained from
if (!triedClassInfoLoader && classInfo != null && classInfo.classLoader != null) {
try {
return Class.forName(className, scanResult.scanSpec.initializeLoadedClasses, classInfo.classLoader);
} catch (ClassNotFoundException | NoClassDefFoundError e) {
// Ignore
}
}
// If class came from a module, and it was not able to be loaded by the environment classloader,
// then it is possible it was a non-public class, and ClassGraph found it by ignoring class visibility
// when reading the resources in exported packages directly. Force ClassGraph to respect JPMS
// encapsulation rules by refusing to load modular classes that the context/system classloaders
// could not load. (A SecurityException should be thrown above, but this is here for completeness.)
if (classInfo != null && classInfo.classpathElement instanceof ClasspathElementModule
&& !classInfo.isPublic()) {
throw new ClassNotFoundException("Classfile for class " + className + " was found in a module, "
+ "but the context and system classloaders could not load the class, probably because "
+ "the class is not public.");
}
// Try obtaining the classfile as a resource, and defining the class from the resource content
final ResourceList classfileResources = scanResult
.getResourcesWithPath(JarUtils.classNameToClassfilePath(className));
if (classfileResources != null) {
for (final Resource resource : classfileResources) {
// Iterate through resources (only loading of first resource in the list will be attempted)
try {
// Load the content of the resource, and define a class from it
final ByteBuffer resourceByteBuffer = resource.read();
return defineClass(className, resourceByteBuffer, null);
} catch (final IOException e) {
throw new ClassNotFoundException("Could not load classfile for class " + className + " : " + e);
} finally {
resource.close();
}
}
}
throw new ClassNotFoundException("Could not load classfile for class " + className);
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#getResource(java.lang.String)
*/
@Override
public URL getResource(final String path) {
final ResourceList resourceList = scanResult.getResourcesWithPath(path);
if (resourceList == null || resourceList.isEmpty()) {
return super.getResource(path);
} else {
return resourceList.get(0).getURL();
}
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#getResources(java.lang.String)
*/
@Override
public Enumeration<URL> getResources(final String path) throws IOException {
final ResourceList resourceList = scanResult.getResourcesWithPath(path);
if (resourceList == null || resourceList.isEmpty()) {
return super.getResources(path);
} else {
return new Enumeration<URL>() {
/** The idx. */
int idx;
@Override
public boolean hasMoreElements() {
return idx < resourceList.size();
}
@Override
public URL nextElement() {
return resourceList.get(idx++).getURL();
}
};
}
}
/* (non-Javadoc)
* @see java.lang.ClassLoader#getResourceAsStream(java.lang.String)
*/
@Override
public InputStream getResourceAsStream(final String path) {
final ResourceList resourceList = scanResult.getResourcesWithPath(path);
if (resourceList == null || resourceList.isEmpty()) {
return super.getResourceAsStream(path);
} else {
try {
return resourceList.get(0).open();
} catch (final IOException e) {
return null;
}
}
}
} |
package is.landsbokasafn.deduplicator;
import static is.landsbokasafn.deduplicator.DedupAttributeConstants.A_CONTENT_STATE_KEY;
import static is.landsbokasafn.deduplicator.DedupAttributeConstants.CONTENT_UNCHANGED;
import static org.archive.modules.recrawl.RecrawlAttributeConstants.A_CONTENT_DIGEST;
import static org.archive.modules.recrawl.RecrawlAttributeConstants.A_FETCH_HISTORY;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermRangeFilter;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.FSDirectory;
import org.archive.modules.CrawlURI;
import org.archive.modules.ProcessResult;
import org.archive.modules.Processor;
import org.archive.modules.net.ServerCache;
import org.archive.util.ArchiveUtils;
import org.archive.util.Base32;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Heritrix compatible processor.
* <p>
* Will determine if CrawlURIs are <i>duplicates</i>.
* <p>
* Duplicate detection can only be performed <i>after</i> the fetch processors
* have run.
*
* @author Kristinn Sigurðsson
*/
@SuppressWarnings("unchecked")
public class DeDuplicator extends Processor implements InitializingBean {
private static Logger logger =
Logger.getLogger(DeDuplicator.class.getName());
// Spring configurable parameters
/* Location of Lucene Index to use for lookups */
private final static String ATTR_INDEX_LOCATION = "index-location";
public String getIndexLocation() {
return (String) kp.get(ATTR_INDEX_LOCATION);
}
public void setIndexLocation(String indexLocation) {
kp.put(ATTR_INDEX_LOCATION,indexLocation);
}
/* The matching method in use (by url or content digest) */
private final static String ATTR_MATCHING_METHOD = "matching-method";
private final static MatchingMethod DEFAULT_MATCHING_METHOD = MatchingMethod.URL;
{
setMatchingMethod(DEFAULT_MATCHING_METHOD);
}
public MatchingMethod getMatchingMethod() {
return (MatchingMethod) kp.get(ATTR_MATCHING_METHOD);
}
public void setMatchingMethod(MatchingMethod matchinMethod) {
kp.put(ATTR_MATCHING_METHOD, matchinMethod);
}
/* On duplicate, should jump to which part of processing chain?
* If not set, nothing is skipped. Otherwise this should be the identity of the processor to jump to.
*/
public final static String ATTR_JUMP_TO = "jump-to";
public String getJumpTo(){
return (String)kp.get(ATTR_JUMP_TO);
}
public void setJumpTo(String jumpTo){
kp.put(ATTR_JUMP_TO, jumpTo);
}
/* Origin of duplicate URLs. May be overridden by info from index*/
public final static String ATTR_ORIGIN = "origin";
{
setOrigin("");
}
public String getOrigin() {
return (String) kp.get(ATTR_ORIGIN);
}
public void setOrigin(String origin) {
kp.put(ATTR_ORIGIN,origin);
}
/* If an exact match is not made, should the processor try
* to find an equivalent match?
*/
public final static String ATTR_EQUIVALENT = "try-equivalent";
{
setTryEquivalent(false);
}
public boolean getTryEquivalent(){
return (Boolean)kp.get(ATTR_EQUIVALENT);
}
public void setTryEquivalent(boolean tryEquivalent){
kp.put(ATTR_EQUIVALENT,tryEquivalent);
}
/* The filter on mime types. This is either a blacklist or whitelist
* depending on ATTR_FILTER_MODE.
*/
public final static String ATTR_MIME_FILTER = "mime-filter";
public final static String DEFAULT_MIME_FILTER = "^text/.*";
{
setMimeFilter(DEFAULT_MIME_FILTER);
}
public String getMimeFilter(){
return (String)kp.get(ATTR_MIME_FILTER);
}
public void setMimeFilter(String mimeFilter){
kp.put(ATTR_MIME_FILTER, mimeFilter);
}
/* Is the mime filter a blacklist (do not apply processor to what matches)
* or whitelist (apply processor only to what matches).
*/
public final static String ATTR_FILTER_MODE = "filter-mode";
{
setBlacklist(true);
}
public boolean getBlacklist(){
return (Boolean)kp.get(ATTR_FILTER_MODE);
}
public void setBlacklist(boolean blacklist){
kp.put(ATTR_FILTER_MODE, blacklist);
}
/* Analysis mode. */
public final static String ATTR_ANALYZE_TIMESTAMP = "analyze-timestamp";
{
setAnalyzeTimestamp(false);
}
public boolean getAnalyzeTimestamp() {
return (Boolean) kp.get(ATTR_ANALYZE_TIMESTAMP);
}
public void setAnalyzeTimestamp(boolean analyzeTimestamp) {
kp.put(ATTR_ANALYZE_TIMESTAMP,analyzeTimestamp);
}
/* Should statistics be tracked per host? **/
public final static String ATTR_STATS_PER_HOST = "stats-per-host";
{
setStatsPerHost(false);
}
public boolean getStatsPerHost(){
return (Boolean)kp.get(ATTR_STATS_PER_HOST);
}
public void setStatsPerHost(boolean statsPerHost){
kp.put(ATTR_STATS_PER_HOST,statsPerHost);
}
/* Should we use sparse queries (uses less memory at a cost to performance? */
public final static String ATTR_USE_SPARSE_RANGE_FILTER = "use-sparse-range-filter";
{
setUseSparseRengeFilter(false);
}
public boolean getUseSparseRengeFilter(){
return (Boolean)kp.get(ATTR_USE_SPARSE_RANGE_FILTER);
}
public void setUseSparseRengeFilter(boolean useSparseRengeFilter){
kp.put(ATTR_USE_SPARSE_RANGE_FILTER, useSparseRengeFilter);
}
/* How should 'origin' be handled */
public final static String ATTR_ORIGIN_HANDLING = "origin-handling";
public final static OriginHandling DEFAULT_ORIGIN_HANDLING = OriginHandling.NONE;
{
setOriginHandling(DEFAULT_ORIGIN_HANDLING);
}
public OriginHandling getOriginHandling() {
return (OriginHandling) kp.get(ATTR_ORIGIN_HANDLING);
}
public void setOriginHandling(OriginHandling originHandling) {
kp.put(ATTR_ORIGIN_HANDLING,originHandling);
}
// Spring configured access ot Heritrix resources
// Gain access to the ServerCache for host based statistics.
protected ServerCache serverCache;
public ServerCache getServerCache() {
return this.serverCache;
}
@Autowired
public void setServerCache(ServerCache serverCache) {
this.serverCache = serverCache;
}
// Member variables.
protected IndexSearcher searcher = null;
protected boolean lookupByURL = true;
protected boolean statsPerHost = false;
protected boolean useOrigin = false;
protected boolean useOriginFromIndex = false;
protected Statistics stats = null;
protected HashMap<String, Statistics> perHostStats = null;
public void afterPropertiesSet() throws Exception {
// Index location
String indexLocation = getIndexLocation();
try {
searcher = new IndexSearcher(FSDirectory.open(new File(indexLocation)));
} catch (Exception e) {
throw new IllegalArgumentException("Unable to find/open index at " + indexLocation,e);
}
// Matching method
MatchingMethod matchingMethod = getMatchingMethod();
lookupByURL = matchingMethod == MatchingMethod.URL;
// Track per host stats
statsPerHost = getStatsPerHost();
// Origin handling.
OriginHandling originHandling = getOriginHandling();
if (originHandling != OriginHandling.NONE) {
useOrigin = true;
logger.fine("Use origin");
if (originHandling == OriginHandling.INDEX) {
useOriginFromIndex = true;
logger.fine("Use origin from index");
}
}
// Initialize some internal variables:
stats = new Statistics();
if (statsPerHost) {
perHostStats = new HashMap<String, Statistics>();
}
}
@Override
protected boolean shouldProcess(CrawlURI curi) {
if (curi.is2XXSuccess() == false) {
// Early return. No point in doing comparison on failed downloads.
logger.finest("Not handling " + curi.toString()
+ ", did not succeed.");
return false;
}
if (curi.isPrerequisite()) {
// Early return. Prerequisites are exempt from checking.
logger.finest("Not handling " + curi.toString()
+ ", prerequisite.");
return false;
}
if (curi.toString().startsWith("http")==false) {
// Early return. Non-http documents are not handled at present
logger.finest("Not handling " + curi.toString()
+ ", non-http.");
return false;
}
if(curi.getContentType() == null){
// No content type means we can not handle it.
logger.finest("Not handling " + curi.toString()
+ ", missing content (mime) type");
return false;
}
if(curi.getContentType().matches(getMimeFilter()) == getBlacklist()){
// Early return. Does not pass the mime filter
logger.finest("Not handling " + curi.toString()
+ ", excluded by mimefilter (" +
curi.getContentType() + ").");
return false;
}
if(curi.getData().containsKey(A_CONTENT_STATE_KEY) &&
((Integer)curi.getData().get(A_CONTENT_STATE_KEY)).intValue()==CONTENT_UNCHANGED){
// Early return. A previous processor or filter has judged this
// CrawlURI as having unchanged content.
logger.finest("Not handling " + curi.toString()
+ ", already flagged as unchanged.");
return false;
}
return true;
}
@Override
protected void innerProcess(CrawlURI puri) {
throw new AssertionError();
}
@Override
protected ProcessResult innerProcessResult(CrawlURI curi) throws InterruptedException {
ProcessResult processResult = ProcessResult.PROCEED; // Default. Continue as normal
logger.finest("Processing " + curi.toString() + "(" +
curi.getContentType() + ")");
stats.handledNumber++;
stats.totalAmount += curi.getContentSize();
Statistics currHostStats = null;
if(statsPerHost){
synchronized (perHostStats) {
String host = getServerCache().getHostFor(curi.getUURI()).getHostName();
currHostStats = perHostStats.get(host);
if(currHostStats==null){
currHostStats = new Statistics();
perHostStats.put(host,currHostStats);
}
}
currHostStats.handledNumber++;
currHostStats.totalAmount += curi.getContentSize();
}
Document duplicate = null;
if(lookupByURL){
duplicate = lookupByURL(curi,currHostStats);
} else {
duplicate = lookupByDigest(curi,currHostStats);
}
if (duplicate != null){
// Perform tasks common to when a duplicate is found.
// Increment statistics counters
stats.duplicateAmount += curi.getContentSize();
stats.duplicateNumber++;
if(statsPerHost){
currHostStats.duplicateAmount+=curi.getContentSize();
currHostStats.duplicateNumber++;
}
String jumpTo = getJumpTo();
// Duplicate. Skip part of processing chain?
if(jumpTo!=null){
processResult = ProcessResult.jump(jumpTo);
}
// Record origin?
String annotation = "duplicate";
if(useOrigin){
// TODO: Save origin in the CrawlURI so that other processors
// can make use of it. (Future: WARC)
if(useOriginFromIndex &&
duplicate.get(DigestIndexer.FIELD_ORIGIN)!=null){
// Index contains origin, use it.
annotation += ":\"" + duplicate.get(DigestIndexer.FIELD_ORIGIN) + "\"";
} else {
String tmp = getOrigin();
// Check if an origin value is actually available
if(tmp != null && tmp.trim().length() > 0){
// It is available, add it to the log line.
annotation += ":\"" + tmp + "\"";
}
}
}
// Make note in log
curi.getAnnotations().add(annotation);
if (lookupByURL) {
// A hack to have Heritrix count this as a duplicate.
// TODO: Get gojomo to change how Heritrix decides CURIs are duplicates.
int targetHistoryLength = 2;
Map[] history = null;
if (curi.containsDataKey(A_FETCH_HISTORY)) {
// Rotate up and add new one
history = (HashMap[]) curi.getData().get(A_FETCH_HISTORY);
// Create space
if(history.length != targetHistoryLength) {
HashMap[] newHistory = new HashMap[targetHistoryLength];
System.arraycopy(
history,0,
newHistory,0,
Math.min(history.length,newHistory.length));
history = newHistory;
}
// rotate all history entries up one slot except the newest
// insert from index at [1]
for(int i = history.length-1; i >1; i
history[i] = history[i-1];
}
// Fake the 'last' entry
Map oldVisit = new HashMap();
oldVisit.put(A_CONTENT_DIGEST, curi.getContentDigestSchemeString());
history[1]=oldVisit;
} else {
// Fake the whole thing, set the current digest as both the current visit and previous visit
history = new HashMap[targetHistoryLength];
Map oldVisit = new HashMap();
oldVisit.put(A_CONTENT_DIGEST, curi.getContentDigestSchemeString());
history[0]=oldVisit;
history[1]=oldVisit;
}
curi.getData().put(A_FETCH_HISTORY,history);
} // TODO: Handle matching on digest
// Mark as duplicate for other processors
curi.getData().put(A_CONTENT_STATE_KEY, CONTENT_UNCHANGED);
}
if(getAnalyzeTimestamp()){
doAnalysis(curi,currHostStats, duplicate!=null);
}
return processResult;
}
/**
* Process a CrawlURI looking up in the index by URL
* @param curi The CrawlURI to process
* @param currHostStats A statistics object for the current host.
* If per host statistics tracking is enabled this
* must be non null and the method will increment
* appropriate counters on it.
* @return The result of the lookup (a Lucene document). If a duplicate is
* not found null is returned.
*/
protected Document lookupByURL(CrawlURI curi, Statistics currHostStats){
// Look the CrawlURI's URL up in the index.
try {
Query query = queryField(DigestIndexer.FIELD_URL, curi.toString());
TopScoreDocCollector collector = TopScoreDocCollector.create(
searcher.docFreq(new Term(DigestIndexer.FIELD_URL, curi.toString())), false);
searcher.search(query, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
Document doc = null;
String currentDigest = getDigestAsString(curi);
if(hits != null && hits.length > 0){
// Typically there should only be one hit, but we'll allow for
// multiple hits.
for(int i=0 ; i<hits.length ; i++){
// Multiple hits on same exact URL should be rare
// See if any have matching content digests
doc = searcher.doc(hits[i].doc);
String oldDigest = doc.get(DigestIndexer.FIELD_DIGEST);
if(oldDigest.equalsIgnoreCase(currentDigest)){
stats.exactURLDuplicates++;
if(statsPerHost){
currHostStats.exactURLDuplicates++;
}
logger.finest("Found exact match for " +
curi.toString());
// If we found a hit, no need to look at other hits.
return doc;
}
}
}
if(getTryEquivalent()) {
// No exact hits. Let's try lenient matching.
String normalizedURL = DigestIndexer.stripURL(curi.toString());
query = queryField(DigestIndexer.FIELD_URL_NORMALIZED, normalizedURL);
collector = TopScoreDocCollector.create(
searcher.docFreq(new Term(DigestIndexer.FIELD_URL_NORMALIZED, normalizedURL)), false);
searcher.search(query,collector);
hits = collector.topDocs().scoreDocs;
for(int i=0 ; i<hits.length ; i++){
doc = searcher.doc(hits[i].doc);
String indexDigest = doc.get(DigestIndexer.FIELD_DIGEST);
if(indexDigest.equals(currentDigest)){
// Make note in log
String equivURL = doc.get(
DigestIndexer.FIELD_URL);
curi.getAnnotations().add("equivalentURL:\"" + equivURL + "\"");
// Increment statistics counters
stats.equivalentURLDuplicates++;
if(statsPerHost){
currHostStats.equivalentURLDuplicates++;
}
logger.finest("Found equivalent match for " +
curi.toString() + ". Normalized: " +
normalizedURL + ". Equivalent to: " + equivURL);
//If we found a hit, no need to look at more.
return doc;
}
}
}
} catch (IOException e) {
logger.log(Level.SEVERE,"Error accessing index.",e);
}
// If we make it here then this is not a duplicate.
return null;
}
/**
* Process a CrawlURI looking up in the index by content digest
* @param curi The CrawlURI to process
* @param currHostStats A statistics object for the current host.
* If per host statistics tracking is enabled this
* must be non null and the method will increment
* appropriate counters on it.
* @return The result of the lookup (a Lucene document). If a duplicate is
* not found null is returned.
*/
protected Document lookupByDigest(CrawlURI curi, Statistics currHostStats) {
Document duplicate = null;
String currentDigest = null;
Object digest = curi.getContentDigest();
if (digest != null) {
currentDigest = Base32.encode((byte[])digest);
}
Query query = queryField(DigestIndexer.FIELD_DIGEST, currentDigest);
try {
int hitsOnDigest = searcher.docFreq(new Term(DigestIndexer.FIELD_DIGEST,currentDigest));
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsOnDigest, false);
searcher.search(query,collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
StringBuffer mirrors = new StringBuffer();
mirrors.append("mirrors: ");
String url = curi.toString();
String normalizedURL =
getTryEquivalent() ? DigestIndexer.stripURL(url) : null;
if(hits != null && hits.length > 0){
// Can definitely be more then one
// Note: We may find an equivalent match before we find an
// (existing) exact match.
// TODO: Ensure that an exact match is recorded if it exists.
for(int i=0 ; i<hits.length && duplicate==null ; i++){
Document doc = searcher.doc(hits[i].doc);
String indexURL = doc.get(DigestIndexer.FIELD_URL);
// See if the current hit is an exact match.
if(url.equals(indexURL)){
duplicate = doc;
stats.exactURLDuplicates++;
if(statsPerHost){
currHostStats.exactURLDuplicates++;
}
logger.finest("Found exact match for " + curi.toString());
}
// If not, then check if it is an equivalent match (if
// equivalent matches are allowed).
if(duplicate == null && getTryEquivalent()){
String indexNormalizedURL =
doc.get(DigestIndexer.FIELD_URL_NORMALIZED);
if(normalizedURL.equals(indexNormalizedURL)){
duplicate = doc;
stats.equivalentURLDuplicates++;
if(statsPerHost){
currHostStats.equivalentURLDuplicates++;
}
curi.getAnnotations().add("equivalentURL:\"" + indexURL + "\"");
logger.finest("Found equivalent match for " +
curi.toString() + ". Normalized: " +
normalizedURL + ". Equivalent to: " + indexURL);
}
}
if(duplicate == null){
// Will only be used if no exact (or equivalent) match
// is found.
mirrors.append(indexURL + " ");
}
}
if(duplicate == null){
stats.mirrorNumber++;
if (statsPerHost) {
currHostStats.mirrorNumber++;
}
logger.log(Level.FINEST,"Found mirror URLs for " +
curi.toString() + ". " + mirrors);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE,"Error accessing index.",e);
}
return duplicate;
}
public String report() {
StringBuffer ret = new StringBuffer();
ret.append("Processor: is.hi.bok.digest.DeDuplicator\n");
ret.append(" Function: Abort processing of duplicate records\n");
ret.append(" - Lookup by " +
(lookupByURL?"url":"digest") + " in use\n");
ret.append(" Total handled: " + stats.handledNumber + "\n");
ret.append(" Duplicates found: " + stats.duplicateNumber + " " +
getPercentage(stats.duplicateNumber,stats.handledNumber) + "\n");
ret.append(" Bytes total: " + stats.totalAmount + " (" +
ArchiveUtils.formatBytesForDisplay(stats.totalAmount) + ")\n");
ret.append(" Bytes discarded: " + stats.duplicateAmount + " (" +
ArchiveUtils.formatBytesForDisplay(stats.duplicateAmount) + ") " +
getPercentage(stats.duplicateAmount, stats.totalAmount) + "\n");
ret.append(" New (no hits): " + (stats.handledNumber-
(stats.mirrorNumber+stats.exactURLDuplicates+stats.equivalentURLDuplicates)) + "\n");
ret.append(" Exact hits: " + stats.exactURLDuplicates + "\n");
ret.append(" Equivalent hits: " + stats.equivalentURLDuplicates + "\n");
if(lookupByURL==false){
ret.append(" Mirror hits: " + stats.mirrorNumber + "\n");
}
if(getAnalyzeTimestamp()){
ret.append(" Timestamp predicts: (Where exact URL existed in the index)\n");
ret.append(" Change correctly: " + stats.timestampChangeCorrect + "\n");
ret.append(" Change falsly: " + stats.timestampChangeFalse + "\n");
ret.append(" Non-change correct:" + stats.timestampNoChangeCorrect + "\n");
ret.append(" Non-change falsly: " + stats.timestampNoChangeFalse + "\n");
ret.append(" Missing timpestamp:" + stats.timestampMissing + "\n");
}
if(statsPerHost){
ret.append(" [Host] [total] [duplicates] [bytes] " +
"[bytes discarded] [new] [exact] [equiv]");
if(lookupByURL==false){
ret.append(" [mirror]");
}
if(getAnalyzeTimestamp()){
ret.append(" [change correct] [change falsly]");
ret.append(" [non-change correct] [non-change falsly]");
ret.append(" [no timestamp]");
}
ret.append("\n");
synchronized (perHostStats) {
Iterator<String> it = perHostStats.keySet().iterator();
while(it.hasNext()){
String key = it.next();
Statistics curr = perHostStats.get(key);
ret.append(" " +key);
ret.append(" ");
ret.append(curr.handledNumber);
ret.append(" ");
ret.append(curr.duplicateNumber);
ret.append(" ");
ret.append(curr.totalAmount);
ret.append(" ");
ret.append(curr.duplicateAmount);
ret.append(" ");
ret.append(curr.handledNumber-
(curr.mirrorNumber+
curr.exactURLDuplicates+
curr.equivalentURLDuplicates));
ret.append(" ");
ret.append(curr.exactURLDuplicates);
ret.append(" ");
ret.append(curr.equivalentURLDuplicates);
if(lookupByURL==false){
ret.append(" ");
ret.append(curr.mirrorNumber);
}
if(getAnalyzeTimestamp()){
ret.append(" ");
ret.append(curr.timestampChangeCorrect);
ret.append(" ");
ret.append(curr.timestampChangeFalse);
ret.append(" ");
ret.append(curr.timestampNoChangeCorrect);
ret.append(" ");
ret.append(curr.timestampNoChangeFalse);
ret.append(" ");
ret.append(curr.timestampMissing);
}
ret.append("\n");
}
}
}
ret.append("\n");
return ret.toString();
}
protected static String getPercentage(double portion, double total){
double value = portion / total;
value = value*100;
String ret = Double.toString(value);
int dot = ret.indexOf('.');
if(dot+3<ret.length()){
ret = ret.substring(0,dot+3);
}
return ret + "%";
}
private static String getDigestAsString(CrawlURI curi){
// The CrawlURI now has a method for this. For backwards
// compatibility with older Heritrix versions that is not used.
Object digest = curi.getContentDigest();
if (digest != null) {
return Base32.encode((byte[])digest);
}
return null;
}
protected void doAnalysis(CrawlURI curi, Statistics currHostStats,
boolean isDuplicate) {
try{
Query query = queryField(DigestIndexer.FIELD_URL, curi.toString());
TopScoreDocCollector collector = TopScoreDocCollector.create(
searcher.docFreq(new Term(DigestIndexer.FIELD_URL, curi.toString())), false);
searcher.search(query,collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
Document doc = null;
if(hits != null && hits.length > 0){
// If there are multiple hits, use the one with the most
// recent date.
Document docToEval = null;
for(int i=0 ; i<hits.length ; i++){
doc = searcher.doc(hits[i].doc);
// The format of the timestamp ("yyyyMMddHHmmssSSS") allows
// us to do a greater then (later) or lesser than (earlier)
// comparison of the strings.
String timestamp = doc.get(DigestIndexer.FIELD_TIMESTAMP);
if(docToEval == null
|| docToEval.get(DigestIndexer.FIELD_TIMESTAMP)
.compareTo(timestamp)>0){
// Found a more recent hit.
docToEval = doc;
}
}
doTimestampAnalysis(curi,docToEval, currHostStats, isDuplicate);
}
} catch(IOException e){
logger.log(Level.SEVERE,"Error accessing index.",e);
}
}
protected void doTimestampAnalysis(CrawlURI curi, Document urlHit,
Statistics currHostStats, boolean isDuplicate){
HttpMethod method = curi.getHttpMethod();
// Compare datestamps (last-modified versus the indexed date)
Date lastModified = null;
if (method.getResponseHeader("last-modified") != null) {
SimpleDateFormat sdf =
new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z",
Locale.ENGLISH);
try {
lastModified = sdf.parse(
method.getResponseHeader("last-modified").getValue());
} catch (ParseException e) {
logger.log(Level.INFO,"Exception parsing last modified of " +
curi.toString(),e);
return;
}
} else {
stats.timestampMissing++;
if (statsPerHost) {
currHostStats.timestampMissing++;
logger.finest("Missing timestamp on " + curi.toString());
}
return;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date lastFetch = null;
try {
lastFetch = sdf.parse(
urlHit.get(DigestIndexer.FIELD_TIMESTAMP));
} catch (ParseException e) {
logger.log(Level.WARNING,"Exception parsing indexed date for " +
urlHit.get(DigestIndexer.FIELD_URL),e);
return;
}
if(lastModified.after(lastFetch)){
// Header predicts change
if(isDuplicate){
// But the DeDuplicator did not notice a change.
stats.timestampChangeFalse++;
if (statsPerHost){
currHostStats.timestampChangeFalse++;
}
logger.finest("Last-modified falsly predicts change on " +
curi.toString());
} else {
stats.timestampChangeCorrect++;
if (statsPerHost){
currHostStats.timestampChangeCorrect++;
}
logger.finest("Last-modified correctly predicts change on " +
curi.toString());
}
} else {
// Header does not predict change.
if(isDuplicate){
// And the DeDuplicator verifies that no change had occurred
stats.timestampNoChangeCorrect++;
if (statsPerHost){
currHostStats.timestampNoChangeCorrect++;
}
logger.finest("Last-modified correctly predicts no-change on " +
curi.toString());
} else {
// As this is particularly bad we'll log the URL at INFO level
logger.log(Level.INFO,"Last-modified incorrectly indicated " +
"no-change on " + curi.toString() + " " +
curi.getContentType() + ". last-modified: " +
lastModified + ". Last fetched: " + lastFetch);
stats.timestampNoChangeFalse++;
if (statsPerHost){
currHostStats.timestampNoChangeFalse++;
}
}
}
}
/** Run a simple Lucene query for a single term in a single field.
*
* @param fieldName name of the field to look in.
* @param value The value to query for
* @returns A Query for the given value in the given field.
*/
protected Query queryField(String fieldName, String value) {
Query query = null;
query = new ConstantScoreQuery(
new TermRangeFilter(fieldName, value, value, true, true));
return query;
}
protected void finalTasks() {
try {
if (searcher != null) {
searcher.close();
}
} catch (IOException e) {
logger.log(Level.SEVERE,"Error closing index",e);
}
}
}
class Statistics{
// General statistics
/** Number of URIs that make it through the processors exclusion rules
* and are processed by it.
*/
long handledNumber = 0;
/** Number of URIs that are deemed duplicates and further processing is
* aborted
*/
long duplicateNumber = 0;
/** Then number of URIs that turned out to have exact URL and content
* digest matches.
*/
long exactURLDuplicates = 0;
/** The number of URIs that turned out to have equivalent URL and content
* digest matches.
*/
long equivalentURLDuplicates = 0;
/** The number of URIs that, while having no exact or equivalent matches,
* do have exact content digest matches against non-equivalent URIs.
*/
long mirrorNumber = 0;
/** The total amount of data represented by the documents who were deemed
* duplicates and excluded from further processing.
*/
long duplicateAmount = 0;
/** The total amount of data represented by all the documents processed **/
long totalAmount = 0;
// Timestamp analysis
long timestampChangeCorrect = 0;
long timestampChangeFalse = 0;
long timestampNoChangeCorrect = 0;
long timestampNoChangeFalse = 0;
long timestampMissing = 0;
// ETag analysis;
long ETagChangeCorrect = 0;
long ETagChangeFalse = 0;
long ETagNoChangeCorrect = 0;
long ETagNoChangeFalse = 0;
long ETagMissingIndex = 0;
long ETagMissingCURI = 0;
} |
package jp.gr.java_conf.dyama.rink.parser;
public interface Sentence {
/**
* Returns the number of words
* @return number of words
*/
public int size();
public Word getWord(int i);
/**
* Returns the string of the sentence.
* @return the string of the sentence
*/
public String getString();
} |
package jp.pushmestudio.kcuc.rest;
import java.util.HashMap;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.json.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jp.pushmestudio.kcuc.controller.KCData;
import jp.pushmestudio.kcuc.model.UserInfo;
@Api(value = "kcuc")
@Path("/check")
public class KCNoticeResource {
// TODO
KCData data = new KCData();
/**
*
*
* @param href
*
* @return
*/
@Path("/users")
@GET
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "", response = UserInfo.class, notes = " ")
public UserInfo getUpdatedUsers(
@ApiParam(value = "", required = true) @QueryParam("href") @DefaultValue("") String href) {
JSONObject results = data.checkUpdateByPage(href);
return new UserInfo("tkhm", "hoge", new HashMap<String, Long>());
}
/**
*
*
* @param user
*
* @return
*/
@Path("/pages")
@GET
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "", notes = " ")
public String getUpdatedPages(
@ApiParam(value = "", required = true) @QueryParam("user") @DefaultValue("") String user) {
JSONObject results = data.checkUpdateByUser(user);
return results.toString();
}
/**
*
*
* @param user
* Cookie
* @param href
*
* @return
*/
@Path("/pages")
@POST
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "", notes = " ")
public String setSubscribe(
@ApiParam(value = "", required = true) @FormParam("user") @DefaultValue("") String user,
@ApiParam(value = "", required = true) @FormParam("href") String href) {
JSONObject results = data.registerSubscribedPage(user, href);
return results.toString();
}
} |
package lee.study.down.hanndle;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.ReferenceCountUtil;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import lee.study.down.HttpDownServer;
import lee.study.down.dispatch.HttpDownCallback;
import lee.study.down.model.ChunkInfo;
import lee.study.down.model.TaskInfo;
public class HttpDownInitializer extends ChannelInitializer {
private boolean isSsl;
private TaskInfo taskInfo;
private ChunkInfo chunkInfo;
private HttpDownCallback callback;
private FileChannel fileChannel;
public HttpDownInitializer(boolean isSsl, TaskInfo taskInfo, ChunkInfo chunkInfo,
HttpDownCallback callback) throws Exception {
this.isSsl = isSsl;
this.taskInfo = taskInfo;
this.chunkInfo = chunkInfo;
this.callback = callback;
}
@Override
protected void initChannel(Channel ch) throws Exception {
this.chunkInfo.setChannel(ch);
if (isSsl) {
ch.pipeline().addLast(HttpDownServer.CLIENT_SSL_CONTEXT.newHandler(ch.alloc()));
}
ch.pipeline().addLast("httpCodec", new HttpClientCodec());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
try {
if (msg instanceof HttpContent) {
if (!fileChannel.isOpen()) {
return;
}
HttpContent httpContent = (HttpContent) msg;
ByteBuf byteBuf = httpContent.content();
int readableBytes = byteBuf.readableBytes();
fileChannel.write(byteBuf.nioBuffer());
chunkInfo.setDownSize(chunkInfo.getDownSize() + readableBytes);
taskInfo.setDownSize(taskInfo.getDownSize() + readableBytes);
callback.progress(taskInfo, chunkInfo);
//fileChannel
if (httpContent instanceof LastHttpContent || chunkInfo.getDownSize() == chunkInfo
.getTotalSize()) {
fileChannel.close();
chunkInfo.setStatus(2);
chunkInfo.setLastTime(System.currentTimeMillis());
callback.chunkDone(taskInfo, chunkInfo);
if (taskInfo.getChunkInfoList().stream()
.allMatch((chunk) -> chunk.getStatus() == 2)) {
taskInfo.setStatus(2);
taskInfo.setLastTime(System.currentTimeMillis());
callback.done(taskInfo);
ctx.channel().close();
}
}
} else {
fileChannel = new RandomAccessFile(
taskInfo.getFilePath() + File.separator + taskInfo.getFileName(), "rw")
.getChannel();
if (taskInfo.isSupportRange()) {
fileChannel.position(chunkInfo.getOriStartPosition() + chunkInfo.getDownSize());
}
chunkInfo.setStatus(1);
chunkInfo.setFileChannel(fileChannel);
callback.chunkStart(taskInfo, chunkInfo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println(
"" + chunkInfo.getIndex() + "\t" + chunkInfo.getDownSize());
chunkInfo.setStatus(3);
callback.error(taskInfo, chunkInfo, cause);
//super.exceptionCaught(ctx, cause);
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
super.channelUnregistered(ctx);
ctx.channel().close();
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
public static void main(String[] args) throws IOException {
byte[] bts1 = new byte[26];
for (byte i = 0, j = 'a'; i < bts1.length; i++, j++) {
bts1[i] = j;
}
byte[] bts2 = new byte[26];
for (byte i = 0, j = 'A'; i < bts2.length; i++, j++) {
bts2[i] = j;
}
Files.write(Paths.get("f:/down/test1.txt"), bts1);
Files.write(Paths.get("f:/down/test2.txt"), bts2);
}
} |
package linenux.view;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import linenux.control.ControlUnit;
public class ExpandableResultBoxController {
@FXML
Button button;
@FXML
TextArea textArea;
private BooleanProperty expanded = new SimpleBooleanProperty(false);
private ControlUnit controlUnit;
public void setControlUnit(ControlUnit controlUnit) {
this.controlUnit = controlUnit;
this.controlUnit.getLastCommandResultProperty().addListener((change) -> {
this.setText(this.controlUnit.getLastCommandResultProperty().get().getFeedback());
});
}
@FXML
private void initialize() {
this.expanded.addListener(change -> {
this.render();
});
}
@FXML
private void toggleExpandedState() {
this.expanded.set(!this.expanded.get());
}
private void render() {
if (this.expanded.get()) {
this.button.setText("Hide");
this.textArea.setPrefHeight(200);
} else {
this.button.setText("Show");
this.textArea.setPrefHeight(0);
}
}
private void setText(String text) {
if (text.trim().contains("\n")) {
this.expanded.set(true);
this.textArea.setText(text.trim());
} else {
// TODO show the reminders instead.
this.textArea.setText("");
}
}
} |
package me.coley.recaf.ui.controls.text;
import javafx.application.Platform;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import me.coley.recaf.control.gui.GuiController;
import me.coley.recaf.ui.controls.CodeAreaExt;
import me.coley.recaf.ui.controls.SearchBar;
import me.coley.recaf.ui.controls.text.model.*;
import me.coley.recaf.util.ThreadUtil;
import me.coley.recaf.util.struct.Pair;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;
import org.fxmisc.wellbehaved.event.EventPattern;
import org.fxmisc.wellbehaved.event.InputMap;
import org.fxmisc.wellbehaved.event.Nodes;
import java.awt.Toolkit;
import java.util.function.*;
/**
* Text editor panel.
*
* @param <E>
* Error handler type.
* @param <C>
* Context handler type.
*
* @author Matt
*/
public class EditorPane<E extends ErrorHandling, C extends ContextHandling> extends BorderPane {
protected final GuiController controller;
protected final CodeArea codeArea = new CodeAreaExt();
protected final C contextHandler;
protected final BorderPane bottomContent = new BorderPane();
protected final ErrorList errorList = new ErrorList(this);
protected final SplitPane split;
private final SearchBar search = new SearchBar(codeArea::getText);
private Consumer<String> onCodeChange;
private E errHandler;
/**
* @param controller
* Controller to act on.
* @param language
* Type of text content.
* @param handlerFunc
* Function to supply the context handler.
*/
public EditorPane(GuiController controller, Language language, BiFunction<GuiController, CodeArea, C> handlerFunc) {
this.controller = controller;
this.contextHandler = handlerFunc.apply(controller, codeArea);
getStyleClass().add("editor-pane");
setupCodeArea(language);
setupSearch();
VirtualizedScrollPane<CodeArea> scroll = new VirtualizedScrollPane<>(codeArea);
split = new SplitPane(scroll, bottomContent);
split.setOrientation(Orientation.VERTICAL);
split.setDividerPositions(1);
split.getStyleClass().add("no-border");
setupBottomContent();
setCenter(split);
}
protected void setupBottomContent() {
bottomContent.setCenter(errorList);
SplitPane.setResizableWithParent(bottomContent, Boolean.FALSE);
}
private void setupCodeArea(Language language) {
codeArea.setEditable(false);
IntFunction<Node> lineFactory = LineNumberFactory.get(codeArea);
IntFunction<Node> errorFactory = new ErrorIndicatorFactory();
IntFunction<Node> decorationFactory = line -> {
HBox hbox = new HBox(
lineFactory.apply(line),
errorFactory.apply(line));
hbox.setAlignment(Pos.CENTER_LEFT);
return hbox;
};
Platform.runLater(() -> codeArea.setParagraphGraphicFactory(decorationFactory));
LanguageStyler styler = new LanguageStyler(language);
codeArea.richChanges()
.filter(ch -> !ch.isPlainTextIdentity())
.filter(ch -> !ch.getInserted().equals(ch.getRemoved()))
.subscribe(change -> ThreadUtil.runSupplyConsumer(() -> {
if(onCodeChange != null)
onCodeChange.accept(codeArea.getText());
return styler.computeStyle(codeArea.getText());
}, computedStyle -> codeArea.setStyleSpans(0, computedStyle)));
// So, tabs are hard-coded to be 8-characters wide visually until JavaFX 14
// Its not great, but using 4 actual spaces is a good enough solution.
InputMap<KeyEvent> im = InputMap.consume(
EventPattern.keyPressed(KeyCode.TAB),
e -> codeArea.replaceSelection(" ")
);
Nodes.addInputMap(codeArea, im);
}
private void setupSearch() {
setOnKeyPressed(e -> {
if(controller.config().keys().find.match(e)) {
// On search bind:
// - open search field if necessary
// - select search field text
boolean open = getTop() != null && getTop().equals(search);
if(!open)
setTop(search);
search.focus();
}
});
search.setOnEscape(() -> {
// Escape -> Hide field
search.clear();
codeArea.requestFocus();
setTop(null);
});
search.setOnSearch(results -> {
// On search, goto next result
int caret = codeArea.getCaretPosition();
Pair<Integer, Integer> range = results.next(caret);
if (range == null) {
// No results
Toolkit.getDefaultToolkit().beep();
} else {
// Move caret to result range
codeArea.selectRange(range.getKey(), range.getValue());
codeArea.requestFollowCaret();
}
});
}
/**
* Forgets history.
*/
public void forgetHistory() {
codeArea.getUndoManager().forgetHistory();
}
/**
* @return Text content
*/
public String getText() {
return codeArea.getText();
}
/**
* @param text
* Text content.
*/
public void setText(String text) {
codeArea.replaceText(text);
}
/**
* @param text
* Text content to append.
*/
public void appendText(String text) {
codeArea.appendText(text);
}
/**
* @param wrap
* Should text wrap lines.
*/
public void setWrapText(boolean wrap) {
codeArea.setWrapText(wrap);
}
/**
* @param editable
* Should text be editable.
*/
public void setEditable(boolean editable) {
codeArea.setEditable(editable);
}
/**
* @param onCodeChange
* Action to run when text is modified.
*/
protected void setOnCodeChange(Consumer<String> onCodeChange) {
this.onCodeChange = onCodeChange;
}
/**
* @param errHandler
* Error handler.
*/
protected void setErrorHandler(E errHandler) {
if (this.errHandler != null)
this.errHandler.unbind();
this.errHandler = errHandler;
this.errHandler.bind(errorList);
}
/**
* @return The error handler instance.
*/
public E getErrorHandler() {
return errHandler;
}
/**
* @return the CodeArea instance
*/
public CodeArea getCodeArea(){
return codeArea;
}
protected boolean hasNoErrors() {
if (errHandler == null)
return true;
return !errHandler.hasErrors();
}
private boolean hasError(int line) {
if (hasNoErrors())
return false;
return errHandler.hasError(line);
}
private String getLineComment(int line) {
if (hasNoErrors())
return null;
return errHandler.getLineComment(line);
}
/**
* Decorator factory for building error indicators.
*/
class ErrorIndicatorFactory implements IntFunction<Node> {
private final double[] shape = new double[]{0, 0, 10, 5, 0, 10};
@Override
public Node apply(int lineNo) {
Polygon poly = new Polygon(shape);
poly.getStyleClass().add("cursor-pointer");
poly.setFill(Color.RED);
if(hasError(lineNo)) {
String msg = getLineComment(lineNo);
if(msg != null) {
Tooltip.install(poly, new Tooltip(msg));
}
} else {
poly.setVisible(false);
}
return poly;
}
}
} |
package me.nallar.modpatcher.tasks;
import com.google.common.io.ByteStreams;
import lombok.SneakyThrows;
import lombok.val;
import lzma.sdk.lzma.Encoder;
import lzma.streams.LzmaOutputStream;
import me.nallar.ModPatcherPlugin;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.omg.CORBA.StringHolder;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
public class BinaryProcessor {
private static final HashMap<String, String> classExtends = new HashMap<>();
public static void process(ModPatcherPlugin plugin, File deobfJar) {
if (!deobfJar.exists()) {
ModPatcherPlugin.logger.warn("Could not find minecraft code to process. Expected to find it at " + deobfJar);
return;
}
plugin.mixinTransform(deobfJar.toPath());
if (plugin.extension.generateInheritanceHierarchy)
generateMappings(deobfJar);
if (plugin.extension.generateStubMinecraftClasses)
generateStubMinecraftClasses(deobfJar);
}
private static void addClassToExtendsMap(byte[] inputCode) {
ClassReader classReader = new ClassReader(inputCode);
StringHolder nameHolder = new StringHolder();
StringHolder superNameHolder = new StringHolder();
try {
classReader.accept(new ClassVisitor(Opcodes.ASM5) {
@Override
public void visit(int i, int i1, String name, String s1, String superName, String[] strings) {
nameHolder.value = name;
superNameHolder.value = superName;
throw new RuntimeException("visiting aborted");
}
}, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
} catch (RuntimeException e) {
if (!e.getMessage().equals("visiting aborted")) {
throw e;
}
}
String superName = superNameHolder.value == null ? null : superNameHolder.value.replace("/", ".");
if (superName != null && !superName.equals("java.lang.Object")) {
classExtends.put(nameHolder.value.replace("/", "."), superName);
}
}
@SneakyThrows
private static File getGeneratedDirectory() {
File generatedDirectory = new File("./generated/");
generatedDirectory = generatedDirectory.getCanonicalFile();
if (!generatedDirectory.exists()) {
//noinspection ResultOfMethodCallIgnored
generatedDirectory.mkdir();
}
return generatedDirectory;
}
private static Encoder getEncoder() {
val encoder = new Encoder();
encoder.setDictionarySize(1 << 23);
encoder.setEndMarkerMode(true);
encoder.setMatchFinder(Encoder.EMatchFinderTypeBT4);
encoder.setNumFastBytes(0x20);
return encoder;
}
@SneakyThrows
private static void generateMappings(File jar) {
JarInputStream istream = new JarInputStream(new FileInputStream(jar));
JarEntry entry;
while ((entry = istream.getNextJarEntry()) != null) {
byte[] classBytes = ByteStreams.toByteArray(istream);
if (entry.getName().endsWith(".class")) {
addClassToExtendsMap(classBytes);
}
istream.closeEntry();
}
istream.close();
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new LzmaOutputStream(new FileOutputStream(new File(getGeneratedDirectory(), "extendsMap.obj.lzma")), getEncoder()))) {
objectOutputStream.writeObject(classExtends);
}
}
@SneakyThrows
private static void generateStubMinecraftClasses(File jar) {
try (val os = new JarOutputStream(new LzmaOutputStream(new FileOutputStream(new File(getGeneratedDirectory(), "minecraft_stubs.jar.lzma")), getEncoder()))) {
os.setLevel(Deflater.NO_COMPRESSION);
JarInputStream istream = new JarInputStream(new FileInputStream(jar));
JarEntry entry;
while ((entry = istream.getNextJarEntry()) != null) {
byte[] classBytes = ByteStreams.toByteArray(istream);
if (entry.getName().endsWith(".class")
&& entry.getName().startsWith("net/minecraft")
&& !entry.getName().startsWith("net/minecraft/client")) {
val reader = new ClassReader(classBytes);
val node = new ClassNode();
reader.accept(node, ClassReader.SKIP_CODE | ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
val writer = new ClassWriter(0);
node.accept(writer);
val stub = writer.toByteArray();
val jarEntry = new JarEntry(entry.getName());
os.putNextEntry(jarEntry);
os.write(stub);
os.closeEntry();
}
istream.closeEntry();
}
istream.close();
}
}
} |
package mods.ocminecart.common.util;
import mods.ocminecart.OCMinecart;
import net.minecraft.util.MathHelper;
import net.minecraftforge.common.util.ForgeDirection;
public class RotationHelper {
public static ForgeDirection[] dir = {
ForgeDirection.SOUTH,
ForgeDirection.WEST,
ForgeDirection.NORTH,
ForgeDirection.EAST
};
public static ForgeDirection calcLocalDirection(ForgeDirection value, ForgeDirection face){
int n = indexHelperArray(face);
int d = indexHelperArray(value);
if(n<0 || d<0) return value;
return dir[(d+n+4)%4];
}
public static ForgeDirection calcGlobalDirection(ForgeDirection value, ForgeDirection face){
int n = indexHelperArray(face);
int d = indexHelperArray(value);
if(n<0 || d<0) return value;
return dir[(d-n+4)%4];
}
public static int indexHelperArray(ForgeDirection direction){
for(int i=0;i<dir.length;i+=1){
if(dir[i] == direction) return i;
}
return -1;
}
public static ForgeDirection directionFromYaw(double yaw){
yaw+=45;
yaw = (yaw+360)%360;
int di = MathHelper.floor_double((yaw * 4.0D / 360D) + 0.5D);
di=(di+4)%4;
return RotationHelper.dir[di];
}
} |
package net.gtaun.wl.vehicle.util;
import java.util.HashMap;
import java.util.Map;
import net.gtaun.shoebill.constant.VehicleComponentSlot;
import net.gtaun.shoebill.constant.VehicleModel.VehicleType;
import net.gtaun.shoebill.object.Player;
import net.gtaun.wl.lang.LocalizedStringSet;
import net.gtaun.wl.lang.LocalizedStringSet.PlayerStringSet;
public final class VehicleTextUtils
{
private static final Map<VehicleComponentSlot, String> COMPONENT_SLOT_NAME_KEYS = new HashMap<>();
static
{
COMPONENT_SLOT_NAME_KEYS.put(null, "Component.Slot.Unknown");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.SPOILER, "Component.Slot.Spoiler");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.SPOILER, "Component.Slot.Spoiler");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.HOOD, "Component.Slot.Hood");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.ROOF, "Component.Slot.Roof");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.SIDE_SKIRT, "Component.Slot.SideSkirt");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.LAMPS, "Component.Slot.Lamps");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.NITRO, "Component.Slot.Nitro");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.EXHAUST, "Component.Slot.Exhaust");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.WHEELS, "Component.Slot.Wheels");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.STEREO, "Component.Slot.Stereo");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.HYDRAULICS, "Component.Slot.Hydraulics");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.FRONT_BUMPER, "Component.Slot.FrontBumper");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.REAR_BUMPER, "Component.Slot.RearBumper");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.VENT_RIGHT, "Component.Slot.VentRight");
COMPONENT_SLOT_NAME_KEYS.put(VehicleComponentSlot.VENT_LEFT, "Component.Slot.VentLeft");
}
private static final Map<VehicleType, String> VEHICLE_TYPE_NAME_KEYS = new HashMap<>();
static
{
VEHICLE_TYPE_NAME_KEYS.put(null, "Vehicle.Type.Unknown");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.UNKNOWN, "Vehicle.Type.Unknown");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.BICYCLE, "Vehicle.Type.Bicycle");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.MOTORBIKE, "Vehicle.Type.Motorbike");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.CAR, "Vehicle.Type.Car");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.TRAILER, "Vehicle.Type.Trailer");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.REMOTE_CONTROL, "Vehicle.Type.RemoteControl");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.TRAIN, "Vehicle.Type.Train");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.BOAT, "Vehicle.Type.Boat");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.AIRCRAFT, "Vehicle.Type.Aircraft");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.HELICOPTER, "Vehicle.Type.Helicopter");
VEHICLE_TYPE_NAME_KEYS.put(VehicleType.TANK, "Vehicle.Type.Tank");
}
public static String getComponentSlotName(LocalizedStringSet stringSet, Player player, VehicleComponentSlot slot)
{
String key = COMPONENT_SLOT_NAME_KEYS.get(slot);
return stringSet.get(player, key);
}
public static String getComponentSlotName(PlayerStringSet stringSet, VehicleComponentSlot slot)
{
String key = COMPONENT_SLOT_NAME_KEYS.get(slot);
return stringSet.get(key);
}
public static String getVehicleTypeName(LocalizedStringSet stringSet, Player player, VehicleType type)
{
String key = VEHICLE_TYPE_NAME_KEYS.get(type);
return stringSet.get(player, key);
}
public static String getVehicleTypeName(PlayerStringSet stringSet, VehicleType type)
{
String key = VEHICLE_TYPE_NAME_KEYS.get(type);
return stringSet.get(key);
}
private VehicleTextUtils()
{
}
} |
package net.minecraftforge.gradle.common;
import groovy.lang.Closure;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import net.minecraftforge.gradle.StringUtils;
import net.minecraftforge.gradle.dev.DevExtension;
import org.gradle.api.Project;
import argo.jdom.JdomParser;
import com.google.common.base.Joiner;
public class Constants
{
public static enum OperatingSystem
{
WINDOWS, OSX, LINUX;
public String toString()
{
return StringUtils.lower(name());
}
}
public static enum SystemArch
{
BIT_32, BIT_64;
public String toString()
{
return StringUtils.lower(name()).replace("bit_", "");
}
}
public static final OperatingSystem OPERATING_SYSTEM = getOs();
public static final SystemArch SYSTEM_ARCH = getArch();
// extension nam
public static final String EXT_NAME_MC = "minecraft";
public static final String EXT_NAME_JENKINS = "jenkins";
// json parser
public static final JdomParser PARSER = new JdomParser();
@SuppressWarnings("serial")
public static final Closure<Boolean> CALL_FALSE = new Closure<Boolean>(null){ public Boolean call(Object o){ return false; }};
// urls
public static final String MC_JAR_URL = "http://s3.amazonaws.com/Minecraft.Download/versions/{MC_VERSION}/{MC_VERSION}.jar";
public static final String MC_SERVER_URL = "http://s3.amazonaws.com/Minecraft.Download/versions/{MC_VERSION}/minecraft_server.{MC_VERSION}.jar";
public static final String MCP_URL = "http://files.minecraftforge.net/fernflower_temporary.zip";
public static final String ASSETS_URL = "http://resources.download.minecraft.net";
public static final String LOG = ".gradle/gradle.log";
// things in the cache dir.
public static final String JAR_CLIENT_FRESH = "{CACHE_DIR}/minecraft/net/minecraft/minecraft/{MC_VERSION}/minecraft-{MC_VERSION}.jar";
public static final String JAR_SERVER_FRESH = "{CACHE_DIR}/minecraft/net/minecraft/minecraft_server/{MC_VERSION}/minecraft_server-{MC_VERSION}.jar";
public static final String JAR_MERGED = "{CACHE_DIR}/minecraft/net/minecraft/minecraft_merged/{MC_VERSION}/minecraft_merged-{MC_VERSION}.jar";
public static final String FERNFLOWER = "{CACHE_DIR}/minecraft/fernflower.jar";
public static final String EXCEPTOR = "{CACHE_DIR}/minecraft/exceptor.jar";
public static final String ASSETS = "{CACHE_DIR}/minecraft/assets";
public static final String DEOBF_JAR = "{BUILD_DIR}/deobfuscated.jar";
public static final String DEOBF_BIN_JAR = "{BUILD_DIR}/deobfuscated-bin.jar";
public static final String DECOMP_JAR = "{BUILD_DIR}/decompiled.jar";
public static final String DECOMP_FMLED = "{BUILD_DIR}/decompiled-fmled.jar";
public static final String DECOMP_FMLINJECTED = "{BUILD_DIR}/decompiled-fmlinjected.jar";
public static final String DECOMP_FORGED = "{BUILD_DIR}/decompiled-forged.jar";
public static final String DECOMP_FORGEINJECTED = "{BUILD_DIR}/decompiled-forgeinjected.jar";
public static final String DECOMP_REMAPPED = "{BUILD_DIR}/decompiled-remapped.jar";
// util
public static final String NEWLINE = System.getProperty("line.separator");
private static final OutputStream NULL_OUT = new OutputStream()
{
public void write(int b) throws IOException{}
};
// helper methods
public static File cacheFile(Project project, String... otherFiles)
{
return Constants.file(project.getGradle().getGradleUserHomeDir(), otherFiles);
}
public static File file(File file, String... otherFiles)
{
String othersJoined = Joiner.on('/').join(otherFiles);
return new File(file, othersJoined);
}
public static File file(String... otherFiles)
{
String othersJoined = Joiner.on('/').join(otherFiles);
return new File(othersJoined);
}
public static List<String> getClassPath()
{
URL[] urls = ((URLClassLoader) DevExtension.class.getClassLoader()).getURLs();
ArrayList<String> list = new ArrayList<String>();
for (URL url : urls)
{
list.add(url.getPath());
}
//System.out.println(Joiner.on(';').join(((URLClassLoader) ExtensionObject.class.getClassLoader()).getURLs()));
return list;
}
private static OperatingSystem getOs()
{
String name = StringUtils.lower(System.getProperty("os.name"));
if (name.contains("windows"))
{
return OperatingSystem.WINDOWS;
}
else if (name.contains("mac"))
{
return OperatingSystem.OSX;
}
else if (name.contains("linux"))
{
return OperatingSystem.LINUX;
}
else
{
return null;
}
}
private static SystemArch getArch()
{
String name = StringUtils.lower(System.getProperty("os.arch"));
if (name.contains("64"))
{
return SystemArch.BIT_64;
}
else
{
return SystemArch.BIT_32;
}
}
public static String hash(File file)
{
try
{
InputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do
{
numRead = fis.read(buffer);
if (numRead > 0)
{
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
byte[] hash = complete.digest();
String result = "";
for (int i = 0; i < hash.length; i++)
{
result += Integer.toString((hash[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public static String hash(String str)
{
try
{
MessageDigest complete = MessageDigest.getInstance("MD5");
byte[] hash = complete.digest(str.getBytes());
String result = "";
for (int i = 0; i < hash.length; i++)
{
result += Integer.toString((hash[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
/**
* DON'T FORGET TO CLOSE
*/
public static OutputStream getNullStream()
{
return NULL_OUT;
}
} |
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.ref.LongReference;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.values.LongValue;
import net.openhft.chronicle.threads.Pauser;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
public class LongValueBitSet implements Marshallable {
/*
* BitSets are packed into arrays of "words." Currently a word is
* a long, which consists of 64 bits, requiring 6 address bits.
* The choice of word size is determined purely by performance concerns.
*/
private final static int ADDRESS_BITS_PER_WORD = 6;
private final static int BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD;
/* Used to shift left or right for a partial word mask */
private static final long WORD_MASK = 0xffffffffffffffffL;
private transient Pauser pauser = Pauser.busy();
/**
* The internal field corresponding to the serialField "bits".
*/
private LongValue[] words;
/**
* Whether the size of "words" is user-specified. If so, we assume
* the user knows what he's doing and try harder to preserve it.
*/
private transient boolean sizeIsSticky = true;
public LongValueBitSet(final int maxNumberOfBits) {
int size = (maxNumberOfBits / 64) + 1;
words = new LongValue[size];
pauser = Pauser.busy();
}
public LongValueBitSet(final int maxNumberOfBits, Wire w) {
this(maxNumberOfBits);
writeMarshallable(w);
readMarshallable(w);
}
/**
* Given a bit index, return word index containing it.
*/
private static int wordIndex(int bitIndex) {
return bitIndex >> ADDRESS_BITS_PER_WORD;
}
/**
* Every public method must preserve these invariants.
*/
// private void checkInvariants() {
// assert (wordsInUse.getVolatileValue() == 0 || words[wordsInUse.getVolatileValue() - 1]
// .getValue() != 0);
// assert (wordsInUse.getVolatileValue() >= 0 && wordsInUse.getVolatileValue() <= words
// .length);
// assert (wordsInUse.getVolatileValue() == words.length || words[wordsInUse
// .getVolatileValue()].getValue() == 0);
/**
* Returns a new bit set containing all the bits in the given byte array.
*
* <p>More precisely,
* <br>{@code BitSet.valueOf(bytes).get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}
* <br>for all {@code n < 8 * bytes.length}.
*
* <p>This method is equivalent to
* {@code BitSet.valueOf(ByteBuffer.wrap(bytes))}.
*
* @param bytes a byte array containing a little-endian
* representation of a sequence of bits to be used as the
* initial bits of the new bit set
* @return a {@code BitSet} containing all the bits in the byte array
* @since 1.7
*/
public static BitSet valueOf(byte[] bytes) {
return BitSet.valueOf(ByteBuffer.wrap(bytes));
}
/**
* Checks that fromIndex ... toIndex is a valid range of bit indices.
*/
private static void checkRange(int fromIndex, int toIndex) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
if (toIndex < 0)
throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex);
if (fromIndex > toIndex)
throw new IndexOutOfBoundsException("fromIndex: " + fromIndex +
" > toIndex: " + toIndex);
}
/**
* Sets the field wordsInUse.getValue() to the logical size in words of the bit set.
* WARNING:This method assumes that the number of words actually in use is
* less than or equal to the current value of wordsInUse.getValue()!
*/
/* private void recalculatewordsInUse()
{
// Traverse the bitset until a used word is found
int i;
for (i = getWordsInUse() - 1; i >= 0; i--)
if (words[i].getVolatileValue() != 0)
break;
wordsInUse.setOrderedValue(i + 1); // The new logical size
}*/
private int getWordsInUse() {
return words.length;
}
public void set(LongValue word, long param, LongFunction function) {
Pauser pauser = pauser();
pauser.reset();
for (; ; ) {
long oldValue = word.getVolatileValue();
if (word.compareAndSwapValue(oldValue, function.apply(oldValue, param)))
break;
pauser.pause();
}
}
private Pauser pauser() {
if (this.pauser == null)
this.pauser = Pauser.busy();
return this.pauser;
}
public void set(LongValue word, long newValue) {
pauser.reset();
long oldValue = word.getVolatileValue();
while (!word.compareAndSwapValue(oldValue, newValue)) {
pauser.pause();
}
}
/**
* Returns a new byte array containing all the bits in this bit set.
*
* <p>More precisely, if
* <br>{@code byte[] bytes = s.toByteArray();}
* <br>then {@code bytes.length == (s.length()+7)/8} and
* <br>{@code s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)}
* <br>for all {@code n < 8 * bytes.length}.
*
* @return a byte array containing a little-endian representation
* of all the bits in this bit set
* @since 1.7
*/
public byte[] toByteArray() {
int n = getWordsInUse();
if (n == 0)
return new byte[0];
int len = 8 * (n - 1);
for (long x = words[n - 1].getValue(); x != 0; x >>>= 8)
len++;
byte[] bytes = new byte[len];
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < n - 1; i++)
bb.putLong(words[i].getVolatileValue());
for (long x = words[n - 1].getValue(); x != 0; x >>>= 8)
bb.put((byte) (x & 0xff));
return bytes;
}
/**
* Ensures that the BitSet can hold enough words.
*
* @param wordsRequired the minimum acceptable number of words.
*/
/*
private void ensureCapacity(int wordsRequired) {
if (words.length < wordsRequired) {
// Allocate larger of doubled size or required size
int request = Math.max(2 * words.length, wordsRequired);
words = Arrays.copyOf(words, request);
sizeIsSticky = false;
}
}
*/
/**
* Ensures that the BitSet can accommodate a given wordIndex,
* temporarily violating the invariants. The caller must
* restore the invariants before returning to the user,
* possibly using recalculatewordsInUse.getValue()().
*
* @param wordIndex the index to be accommodated.
*/
private void expandTo(int wordIndex) {
int wordsRequired = wordIndex + 1;
if (getWordsInUse() < wordsRequired) {
throw new UnsupportedOperationException("todo: it is not possible currently to expand " +
"this stucture, because if its concurrent nature and have to implement cross " +
"process locking");
// ensureCapacity(wordsRequired);
// wordsInUse.setValue(wordsRequired);
}
}
/**
* Sets the bit at the specified index to the complement of its
* current value.
*
* @param bitIndex the index of the bit to flip
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public void flip(int bitIndex) {
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
int wordIndex = wordIndex(bitIndex);
expandTo(wordIndex);
caret(words[wordIndex], 1L << bitIndex);
// recalculatewordsInUse();
//checkInvariants();
}
private void caret(LongValue word, long param) {
set(word, param, (x, y) -> x ^ y);
}
private void and(LongValue word, final long param) {
set(word, param, (x, y) -> x & y);
}
/**
* Sets each bit from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to the complement of its current
* value.
*
* @param fromIndex index of the first bit to flip
* @param toIndex index after the last bit to flip
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
public void flip(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
if (fromIndex == toIndex)
return;
int startWordIndex = wordIndex(fromIndex);
int endWordIndex = wordIndex(toIndex - 1);
expandTo(endWordIndex);
long firstWordMask = WORD_MASK << fromIndex;
long lastWordMask = WORD_MASK >>> -toIndex;
if (startWordIndex == endWordIndex) {
// Case 1: One word
caret(words[startWordIndex], firstWordMask & lastWordMask);
} else {
// Case 2: Multiple words
// Handle first word
caret(words[startWordIndex], firstWordMask);
// Handle intermediate words, if any
for (int i = startWordIndex + 1; i < endWordIndex; i++)
caret(words[i], WORD_MASK);
// Handle last word
caret(words[endWordIndex], lastWordMask);
}
// recalculatewordsInUse();
// checkInvariants();
}
/**
* Sets the bit at the specified index to {@code true}.
*
* @param bitIndex a bit index
* @throws IndexOutOfBoundsException if the specified index is negative
* @since JDK1.0
*/
public void set(int bitIndex) {
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
int wordIndex = wordIndex(bitIndex);
// expandTo(wordIndex);
pipe(words[wordIndex], (1L << bitIndex)); // Restores
// invariants
// checkInvariants();
}
private void pipe(LongValue word, long param) {
set(word, param, (x, y) -> x | y);
}
/**
* Sets the bit at the specified index to the specified value.
*
* @param bitIndex a bit index
* @param value a boolean value to set
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public void set(int bitIndex, boolean value) {
if (value)
set(bitIndex);
else
clear(bitIndex);
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to {@code true}.
*
* @param fromIndex index of the first bit to be set
* @param toIndex index after the last bit to be set
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
public void set(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
if (fromIndex == toIndex)
return;
// Increase capacity if necessary
int startWordIndex = wordIndex(fromIndex);
int endWordIndex = wordIndex(toIndex - 1);
expandTo(endWordIndex);
long firstWordMask = WORD_MASK << fromIndex;
long lastWordMask = WORD_MASK >>> -toIndex;
if (startWordIndex == endWordIndex) {
// Case 1: One word
pipe(words[startWordIndex], firstWordMask & lastWordMask);
} else {
// Case 2: Multiple words
// Handle first word
pipe(words[startWordIndex], firstWordMask);
// Handle intermediate words, if any
for (int i = startWordIndex + 1; i < endWordIndex; i++)
set(words[i], WORD_MASK, (x, y) -> x);
// Handle last word (restores invariants)
pipe(words[endWordIndex], lastWordMask);
}
//checkInvariants();
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to the specified value.
*
* @param fromIndex index of the first bit to be set
* @param toIndex index after the last bit to be set
* @param value value to set the selected bits to
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
public void set(int fromIndex, int toIndex, boolean value) {
if (value)
set(fromIndex, toIndex);
else
clear(fromIndex, toIndex);
}
/**
* Sets the bit specified by the index to {@code false}.
*
* @param bitIndex the index of the bit to be cleared
* @throws IndexOutOfBoundsException if the specified index is negative
* @since JDK1.0
*/
public void clear(int bitIndex) {
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
int wordIndex = wordIndex(bitIndex);
if (wordIndex >= getWordsInUse())
return;
and(words[wordIndex], ~(1L << bitIndex));
//recalculatewordsInUse();
//checkInvariants();
}
/**
* Sets the bits from the specified {@code fromIndex} (inclusive) to the
* specified {@code toIndex} (exclusive) to {@code false}.
*
* @param fromIndex index of the first bit to be cleared
* @param toIndex index after the last bit to be cleared
* @throws IndexOutOfBoundsException if {@code fromIndex} is negative,
* or {@code toIndex} is negative, or {@code fromIndex} is
* larger than {@code toIndex}
* @since 1.4
*/
public void clear(int fromIndex, int toIndex) {
checkRange(fromIndex, toIndex);
if (fromIndex == toIndex)
return;
int startWordIndex = wordIndex(fromIndex);
if (startWordIndex >= getWordsInUse())
return;
int endWordIndex = wordIndex(toIndex - 1);
if (endWordIndex >= getWordsInUse()) {
toIndex = length();
endWordIndex = getWordsInUse() - 1;
}
long firstWordMask = WORD_MASK << fromIndex;
long lastWordMask = WORD_MASK >>> -toIndex;
if (startWordIndex == endWordIndex) {
// Case 1: One word
and(words[startWordIndex], ~(firstWordMask &
lastWordMask));
} else {
// Case 2: Multiple words
// Handle first word
and(words[startWordIndex], ~firstWordMask);
// Handle intermediate words, if any
for (int i = startWordIndex + 1; i < endWordIndex; i++)
words[i].setOrderedValue(0);
// Handle last word
and(words[endWordIndex], ~lastWordMask);
}
//recalculatewordsInUse();
//checkInvariants();
}
/**
* Sets all of the bits in this BitSet to {@code false}.
*
* @since 1.4
*/
public void clear() {
int value = getWordsInUse();
while (value > 0)
words[--value].setValue(0);
//wordsInUse.setValue(value);
}
/**
* Returns the value of the bit with the specified index. The value
* is {@code true} if the bit with the index {@code bitIndex}
* is currently set in this {@code BitSet}; otherwise, the result
* is {@code false}.
*
* @param bitIndex the bit index
* @return the value of the bit with the specified index
* @throws IndexOutOfBoundsException if the specified index is negative
*/
public boolean get(int bitIndex) {
if (bitIndex < 0)
throw new IndexOutOfBoundsException("bitIndex < 0: " + bitIndex);
// checkInvariants();
int wordIndex = wordIndex(bitIndex);
return (wordIndex < getWordsInUse())
&& ((words[wordIndex].getValue() & (1L << bitIndex)) != 0);
}
/**
* Returns the index of the first bit that is set to {@code true}
* that occurs on or after the specified starting index. If no such
* bit exists then {@code -1} is returned.
*
* <p>To iterate over the {@code true} bits in a {@code BitSet},
* use the following loop:
*
* <pre> {@code
* for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
* // operate on index i here
* if (i == Integer.MAX_VALUE) {
* break; // or (i+1) would overflow
* }
* }}</pre>
*
* @param fromIndex the index to start checking from (inclusive)
* @return the index of the next set bit, or {@code -1} if there
* is no such bit
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public int nextSetBit(int fromIndex) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
//checkInvariants();
int u = wordIndex(fromIndex);
if (u >= getWordsInUse())
return -1;
long word = words[u].getVolatileValue() & (WORD_MASK << fromIndex);
while (true) {
if (word != 0)
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
if (++u == getWordsInUse())
return -1;
word = words[u].getVolatileValue();
}
}
/**
* Returns the index of the first bit that is set to {@code true}
* that occurs on or after the specified starting index. If no such
* bit exists then {@code -1} is returned.
*
* <p>To iterate over the {@code true} bits in a {@code BitSet},
* use the following loop:
*
* <pre> {@code
* for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1,to)) {
* // operate on index i here
* if (i == Integer.MAX_VALUE) {
* break; // or (i+1) would overflow
* }
* }}</pre>
*
* @param fromIndex the index to start checking from (inclusive)
* @param toIndex (inclusive) returns -1 if a bit is not found before this value
* @return the index of the next set bit, or {@code -1} if there
* is no such bit
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public int nextSetBit(int fromIndex, int toIndex) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
//checkInvariants();
int u = wordIndex(fromIndex);
if (u >= getWordsInUse())
return -1;
long word = words[u].getVolatileValue() & (WORD_MASK << fromIndex);
while (true) {
if (word != 0)
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
if (++u == getWordsInUse())
return -1;
if (u * BITS_PER_WORD > toIndex)
return -1;
word = words[u].getVolatileValue();
}
}
/**
* Returns the index of the first bit that is set to {@code false}
* that occurs on or after the specified starting index.
*
* @param fromIndex the index to start checking from (inclusive)
* @return the index of the next clear bit
* @throws IndexOutOfBoundsException if the specified index is negative
* @since 1.4
*/
public int nextClearBit(int fromIndex) {
// Neither spec nor implementation handle bitsets of maximal length.
// See 4816253.
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
// checkInvariants();
int u = wordIndex(fromIndex);
if (u >= getWordsInUse())
return fromIndex;
long word = ~words[u].getVolatileValue() & (WORD_MASK << fromIndex);
while (true) {
if (word != 0)
return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word);
if (++u == getWordsInUse())
return getWordsInUse() * BITS_PER_WORD;
word = ~words[u].getValue();
}
}
/**
* Returns the index of the nearest bit that is set to {@code true}
* that occurs on or before the specified starting index.
* If no such bit exists, or if {@code -1} is given as the
* starting index, then {@code -1} is returned.
*
* <p>To iterate over the {@code true} bits in a {@code BitSet},
* use the following loop:
*
* <pre> {@code
* for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
* // operate on index i here
* }}</pre>
*
* @param fromIndex the index to start checking from (inclusive)
* @return the index of the previous set bit, or {@code -1} if there
* is no such bit
* @throws IndexOutOfBoundsException if the specified index is less
* than {@code -1}
* @since 1.7
*/
public int previousSetBit(int fromIndex) {
if (fromIndex < 0) {
if (fromIndex == -1)
return -1;
throw new IndexOutOfBoundsException(
"fromIndex < -1: " + fromIndex);
}
//checkInvariants();
int u = wordIndex(fromIndex);
if (u >= getWordsInUse())
return length() - 1;
long word = words[u].getValue() & (WORD_MASK >>> -(fromIndex + 1));
while (true) {
if (word != 0)
return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word);
if (u
return -1;
word = words[u].getValue();
}
}
/**
* Returns the index of the nearest bit that is set to {@code false}
* that occurs on or before the specified starting index.
* If no such bit exists, or if {@code -1} is given as the
* starting index, then {@code -1} is returned.
*
* @param fromIndex the index to start checking from (inclusive)
* @return the index of the previous clear bit, or {@code -1} if there
* is no such bit
* @throws IndexOutOfBoundsException if the specified index is less
* than {@code -1}
* @since 1.7
*/
public int previousClearBit(int fromIndex) {
if (fromIndex < 0) {
if (fromIndex == -1)
return -1;
throw new IndexOutOfBoundsException(
"fromIndex < -1: " + fromIndex);
}
///checkInvariants();
int u = wordIndex(fromIndex);
if (u >= getWordsInUse())
return fromIndex;
long word = ~words[u].getVolatileValue() & (WORD_MASK >>> -(fromIndex + 1));
while (true) {
if (word != 0)
return (u + 1) * BITS_PER_WORD - 1 - Long.numberOfLeadingZeros(word);
if (u
return -1;
word = ~words[u].getValue();
}
}
/**
* Returns the "logical size" of this {@code BitSet}: the index of
* the highest set bit in the {@code BitSet} plus one. Returns zero
* if the {@code BitSet} contains no set bits.
*
* @return the logical size of this {@code BitSet}
* @since 1.2
*/
public int length() {
if (getWordsInUse() == 0)
return 0;
return BITS_PER_WORD * (getWordsInUse() - 1) +
(BITS_PER_WORD - Long.numberOfLeadingZeros(words[getWordsInUse() - 1].getValue()));
}
/**
* Returns true if this {@code BitSet} contains no bits that are set
* to {@code true}.
*
* @return boolean indicating whether this {@code BitSet} is empty
* @since 1.4
*/
public boolean isEmpty() {
return getWordsInUse() == 0;
}
/**
* Returns true if the specified {@code BitSet} has any bits set to
* {@code true} that are also set to {@code true} in this {@code BitSet}.
*
* @param set {@code BitSet} to intersect with
* @return boolean indicating whether this {@code BitSet} intersects
* the specified {@code BitSet}
* @since 1.4
*/
public boolean intersects(LongValueBitSet set) {
for (int i = Math.min(getWordsInUse(), set.getWordsInUse()) - 1; i >= 0; i
if ((words[i].getVolatileValue() & set.words[i].getVolatileValue()) != 0)
return true;
return false;
}
/**
* Returns the number of bits set to {@code true} in this {@code BitSet}.
*
* @return the number of bits set to {@code true} in this {@code BitSet}
* @since 1.4
*/
public int cardinality() {
int sum = 0;
for (int i = 0; i < getWordsInUse(); i++)
sum += Long.bitCount(words[i].getVolatileValue());
return sum;
}
/**
* Performs a logical <b>AND</b> of this target bit set with the
* argument bit set. This bit set is modified so that each bit in it
* has the value {@code true} if and only if it both initially
* had the value {@code true} and the corresponding bit in the
* bit set argument also had the value {@code true}.
*
* @param set a bit set
*/
public void and(LongValueBitSet set) {
if (this == set)
return;
int value = getWordsInUse();
while (getWordsInUse() > set.getWordsInUse()) {
words[--value].setValue(0);
}
// wordsInUse.setValue(value);
// Perform logical AND on words in common
for (int i = 0; i < getWordsInUse(); i++)
and(words[i], set.words[i].getVolatileValue());
// recalculatewordsInUse();
// checkInvariants();
}
/**
* Performs a logical <b>OR</b> of this bit set with the bit set
* argument. This bit set is modified so that a bit in it has the
* value {@code true} if and only if it either already had the
* value {@code true} or the corresponding bit in the bit set
* argument has the value {@code true}.
*
* @param set a bit set
*/
public void or(LongValueBitSet set) {
if (this == set)
return;
int wordsInCommon = Math.min(getWordsInUse(), set.getWordsInUse());
// if (getWordsInUse() < set.getWordsInUse()) {
// ensureCapacity(set.getWordsInUse());
// wordsInUse.setValue(set.getWordsInUse());
// Perform logical OR on words in common
for (int i = 0; i < wordsInCommon; i++)
pipe(words[i], set.words[i].getVolatileValue());
// Copy any remaining words
if (wordsInCommon < set.getWordsInUse())
System.arraycopy(set.words, wordsInCommon,
words, wordsInCommon,
getWordsInUse() - wordsInCommon);
// recalculatewordsInUse.getValue()() is unnecessary
// checkInvariants();
}
/**
* Performs a logical <b>XOR</b> of this bit set with the bit set
* argument. This bit set is modified so that a bit in it has the
* value {@code true} if and only if one of the following
* statements holds:
* <ul>
* <li>The bit initially has the value {@code true}, and the
* corresponding bit in the argument has the value {@code false}.
* <li>The bit initially has the value {@code false}, and the
* corresponding bit in the argument has the value {@code true}.
* </ul>
*
* @param set a bit set
*/
public void xor(LongValueBitSet set) {
int wordsInCommon = Math.min(getWordsInUse(), set.getWordsInUse());
// if (getWordsInUse() < set.getWordsInUse()) {
// // ensureCapacity(set.getWordsInUse());
// wordsInUse.setValue(set.getWordsInUse());
// Perform logical XOR on words in common
//for (int i = 0; i < wordsInCommon; i++) {
// final long result;
// result = words[i].getVolatileValue() ^ set.words[i].getVolatileValue();
// Copy any remaining words
if (wordsInCommon < set.getWordsInUse())
System.arraycopy(set.words, wordsInCommon,
words, wordsInCommon,
set.getWordsInUse() - wordsInCommon);
// recalculatewordsInUse();
// checkInvariants();
}
/**
* Clears all of the bits in this {@code BitSet} whose corresponding
* bit is set in the specified {@code BitSet}.
*
* @param set the {@code BitSet} with which to mask this
* {@code BitSet}
* @since 1.2
*/
public void andNot(LongValueBitSet set) {
// Perform logical (a & !b) on words in common
for (int i = Math.min(getWordsInUse(), set.getWordsInUse()) - 1; i >= 0; i
and(words[i], ~set.words[i].getVolatileValue());
// recalculatewordsInUse();
//checkInvariants();
}
/**
* Returns the hash code value for this bit set. The hash code depends
* only on which bits are set within this {@code BitSet}.
*
* <p>The hash code is defined to be the result of the following
* calculation:
* <pre> {@code
* public int hashCode() {
* long h = 1234;
* long[] words = toLongArray();
* for (int i = words.length; --i >= 0; )
* h ^= words[i] * (i + 1);
* return (int)((h >> 32) ^ h);
* }}</pre>
* Note that the hash code changes if the set of bits is altered.
*
* @return the hash code value for this bit set
*/
public int hashCode() {
long h = 1234;
for (int i = getWordsInUse(); --i >= 0; )
h ^= words[i].getVolatileValue() * (i + 1);
return (int) ((h >> 32) ^ h);
}
/**
* Returns the number of bits of space actually in use by this
* {@code BitSet} to represent bit values.
* The maximum element in the set is the size - 1st element.
*
* @return the number of bits currently in this bit set
*/
public int size() {
return words.length * BITS_PER_WORD;
}
/**
* Compares this object against the specified object.
* The result is {@code true} if and only if the argument is
* not {@code null} and is a {@code Bitset} object that has
* exactly the same set of bits set to {@code true} as this bit
* set. That is, for every nonnegative {@code int} index {@code k},
* <pre>((BitSet)obj).get(k) == this.get(k)</pre>
* must be true. The current sizes of the two bit sets are not compared.
*
* @param obj the object to compare with
* @return {@code true} if the objects are the same;
* {@code false} otherwise
* @see #size()
*/
public boolean equals(Object obj) {
if (!(obj instanceof LongValueBitSet))
return false;
if (this == obj)
return true;
LongValueBitSet set = (LongValueBitSet) obj;
// checkInvariants();
// set.checkInvariants();
if (getWordsInUse() != set.getWordsInUse())
return false;
// Check words in use by both BitSets
for (int i = 0; i < getWordsInUse(); i++)
if (words[i].getVolatileValue() != set.words[i].getVolatileValue())
return false;
return true;
}
/**
* Attempts to reduce internal storage used for the bits in this bit set.
* Calling this method may, but is not required to, affect the value
* returned by a subsequent call to the {@link #size()} method.
*/
private void trimToSize() {
if (getWordsInUse() != words.length) {
words = Arrays.copyOf(words, getWordsInUse());
// checkInvariants();
}
}
/**
* Save the state of the {@code BitSet} instance to a stream (i.e.,
* serialize it).
*/
private void writeObject(ObjectOutputStream s)
throws IOException {
// checkInvariants();
if (!sizeIsSticky)
trimToSize();
ObjectOutputStream.PutField fields = s.putFields();
fields.put("bits", words);
s.writeFields();
}
/**
* Returns a string representation of this bit set. For every index
* for which this {@code BitSet} contains a bit in the set
* state, the decimal representation of that index is included in
* the result. Such indices are listed in order from lowest to
* highest, separated by ", " (a comma and a space) and
* surrounded by braces, resulting in the usual mathematical
* notation for a set of integers.
*
* <p>Example:
* <pre>
* BitSet drPepper = new BitSet();</pre>
* Now {@code drPepper.toString()} returns "{@code {}}".
* <pre>
* drPepper.set(2);</pre>
* Now {@code drPepper.toString()} returns "{@code {2}}".
* <pre>
* drPepper.set(4);
* drPepper.set(10);</pre>
* Now {@code drPepper.toString()} returns "{@code {2, 4, 10}}".
*
* @return a string representation of this bit set
*/
public String toString() {
// checkInvariants();
int numBits = (getWordsInUse() > 128) ?
cardinality() : getWordsInUse() * BITS_PER_WORD;
StringBuilder b = new StringBuilder(6 * numBits + 2);
b.append('{');
int i = nextSetBit(0);
if (i != -1) {
b.append(i);
while (true) {
if (++i < 0) break;
if ((i = nextSetBit(i)) < 0) break;
int endOfRun = nextClearBit(i);
do {
b.append(", ").append(i);
}
while (++i != endOfRun);
}
}
b.append('}');
return b.toString();
}
/**
* Returns a stream of indices for which this {@code BitSet}
* contains a bit in the set state. The indices are returned
* in order, from lowest to highest. The size of the stream
* is the number of bits in the set state, equal to the value
* returned by the {@link #cardinality()} method.
*
* <p>The bit set must remain constant during the execution of the
* terminal stream operation. Otherwise, the result of the terminal
* stream operation is undefined.
*
* @return a stream of integers representing set indices
* @since 1.8
*/
public IntStream stream() {
class BitSetIterator implements PrimitiveIterator.OfInt {
int next = nextSetBit(0);
@Override
public boolean hasNext() {
return next != -1;
}
@Override
public int nextInt() {
if (next != -1) {
int ret = next;
next = nextSetBit(next + 1);
return ret;
} else {
throw new NoSuchElementException();
}
}
}
return StreamSupport.intStream(
() -> Spliterators.spliterator(
new BitSetIterator(), cardinality(),
Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED),
Spliterator.SIZED | Spliterator.SUBSIZED |
Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED,
false);
}
@Override
public void writeMarshallable(@NotNull final WireOut wire) {
try (DocumentContext dc = wire.writingDocument()) {
wire.write("numberOfLongValues").int32(words.length);
// wire.write("wordsInUse").int32forBinding(wordsInUse == null ? 0 : getWordsInUse());
dc.wire().consumePadding();
for (int i = 0; i < words.length; i++) {
if (words[i] == null)
words[i] = wire.newLongReference();
wire.getValueOut().int64forBinding(words[i].getValue());
}
}
}
@Override
public void readMarshallable(@NotNull final WireIn wire) throws IORuntimeException {
try (DocumentContext dc = wire.readingDocument()) {
int numberOfLongValues = wire.read("numberOfLongValues").int32();
// this.wordsInUse = wire.read("wordsInUse").int32ForBinding((IntValue) null);
dc.wire().padToCacheAlign();
words = new LongReference[numberOfLongValues];
for (int i = 0; i < numberOfLongValues; i++) {
words[i] = wire.getValueIn().int64ForBinding(null);
}
}
}
interface LongFunction {
long apply(long oldValue, long param);
}
} |
package net.prasenjit.identity.service;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import net.prasenjit.identity.entity.AccessToken;
import net.prasenjit.identity.entity.AuthorizationCode;
import net.prasenjit.identity.entity.RefreshToken;
import net.prasenjit.identity.model.OAuthToken;
import net.prasenjit.identity.repository.AccessTokenRepository;
import net.prasenjit.identity.repository.AuthorizationCodeRepository;
import net.prasenjit.identity.repository.RefreshTokenRepository;
//@Slf4j
@Component
@RequiredArgsConstructor
public class CodeFactory {
private final AuthorizationCodeRepository authorizationCodeRepository;
private final RefreshTokenRepository refreshTokenRepository;
private final AccessTokenRepository accessTokenRepository;
public AuthorizationCode createAuthorizationCode(String clientId, String returnUrl, String scope, String userName, String state, Duration validity) {
AuthorizationCode authorizationCode = new AuthorizationCode();
authorizationCode.setClientId(clientId);
LocalDateTime creationDate = LocalDateTime.now();
authorizationCode.setCreationDate(creationDate);
authorizationCode.setExpiryDate(creationDate.plus(validity));
authorizationCode.setReturnUrl(returnUrl);
authorizationCode.setScope(scope);
authorizationCode.setUsername(userName);
authorizationCode.setUsed(false);
authorizationCode.setState(state);
authorizationCode.setAuthorizationCode(RandomStringUtils.randomAlphanumeric(8));
authorizationCodeRepository.saveAndFlush(authorizationCode);
return authorizationCode;
}
public AccessToken createAccessToken(UserDetails user, String clientId, Duration duration, String scope) {
AccessToken accessToken = new AccessToken();
accessToken.setAssessToken(RandomStringUtils.randomAlphanumeric(24));
accessToken.setUsername(user.getUsername());
LocalDateTime creationDate = LocalDateTime.now();
accessToken.setCreationDate(creationDate);
accessToken.setExpiryDate(creationDate.plus(duration));
accessToken.setUserProfile(user);
accessToken.setClientId(clientId);
accessToken.setScope(scope);
accessTokenRepository.saveAndFlush(accessToken);
return accessToken;
}
public RefreshToken createRefreshToken(String clientId, String userName, String scope, Duration duration) {
RefreshToken refreshToken = new RefreshToken();
refreshToken.setClientId(clientId);
LocalDateTime creationDate = LocalDateTime.now();
refreshToken.setCreationDate(creationDate);
refreshToken.setExpiryDate(creationDate.plus(duration));
refreshToken.setScope(scope);
refreshToken.setUsername(userName);
refreshToken.setRefreshToken(RandomStringUtils.randomAlphanumeric(24));
refreshToken.setUsed(false);
refreshTokenRepository.saveAndFlush(refreshToken);
return refreshToken;
}
public OAuthToken createOAuthToken(AccessToken accessToken, RefreshToken refreshToken1) {
OAuthToken oAuthToken = new OAuthToken();
oAuthToken.setAccessToken(accessToken.getAssessToken());
oAuthToken.setRefreshToken(refreshToken1.getRefreshToken());
oAuthToken.setTokenType("Bearer");
oAuthToken.setScope(accessToken.getScope());
long expIn = ChronoUnit.SECONDS.between(LocalDateTime.now(), accessToken.getExpiryDate());
oAuthToken.setExpiresIn(expIn);
return oAuthToken;
}
} |
package nl.erwinvaneyk.communication;
import lombok.extern.slf4j.Slf4j;
import nl.erwinvaneyk.communication.exceptions.CommunicationException;
import nl.erwinvaneyk.communication.rmi.RMISocket;
import nl.erwinvaneyk.core.NodeAddress;
import nl.erwinvaneyk.core.NodeState;
import nl.erwinvaneyk.core.logging.LogNode;
import java.util.HashSet;
import java.util.Set;
import static java.util.stream.Collectors.toSet;
// TODO: separate from rmi
@Slf4j
public class ConnectorImpl implements Connector {
private final NodeState me;
public ConnectorImpl(NodeState me) {
this.me = me;
}
@Override
public void sendMessage(Message message, NodeAddress destination) throws CommunicationException {
RMISocket socket = new RMISocket(destination);
socket.sendMessage(message);
}
@Override
public Message sendRequest(Message message, NodeAddress destination) throws CommunicationException {
RMISocket socket = new RMISocket(destination);
return socket.sendRequest(message);
}
@Override
public Set<NodeAddress> broadcast(Message message) {
Set<NodeAddress> nodes = new HashSet<>(me.getConnectedNodes());
nodes.add(me.getAddress());
return broadcast(message, nodes);
}
public Set<NodeAddress> broadcast(Message message, String identifierFilter) {
String regex = "(.*)" + identifierFilter + "(.*)";
Set<NodeAddress> nodes = me.getConnectedNodes().stream()
.filter(n -> n.getIdentifier().matches(regex))
.collect(toSet());
if(me.getAddress().getIdentifier().matches(regex))
nodes.add(me.getAddress());
return broadcast(message, nodes);
}
private Set<NodeAddress> broadcast(Message message, Set<NodeAddress> nodes) {
nodes.stream().forEach(address -> {
try {
sendMessage(message, address);
} catch (CommunicationException e) {
e.printStackTrace();
}
});
return nodes;
}
@Override
public void log(Message message) {
if(me.getConnectedNodes().stream().anyMatch(node -> LogNode.NODE_TYPE.equals(node.getType()))) {
broadcast(message, LogNode.NODE_TYPE);
} else {
log.debug("No logger: " + message);
}
}
} |
package no.ntnu.okse.core.messaging;
import no.ntnu.okse.Application;
import no.ntnu.okse.core.AbstractCoreService;
import no.ntnu.okse.core.CoreService;
import no.ntnu.okse.core.event.TopicChangeEvent;
import no.ntnu.okse.core.event.listeners.TopicChangeListener;
import no.ntnu.okse.core.topic.Topic;
import no.ntnu.okse.core.topic.TopicService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
public class MessageService extends AbstractCoreService implements TopicChangeListener {
private static boolean _invoked = false;
private static MessageService _singleton;
private static Thread _serviceThread;
private LinkedBlockingQueue<Message> queue;
private ConcurrentHashMap<String, Message> latestMessages;
/**
* Private Constructor that recieves invocation from getInstance, enabling the singleton pattern for this class
*/
private MessageService() {
super(MessageService.class.getName());
init();
}
/**
* Private initializer method that flags invocation state as true, and sets up message queue
*/
protected void init() {
log.info("Initializing MessageService...");
queue = new LinkedBlockingQueue<>();
latestMessages = new ConcurrentHashMap<>();
_invoked = true;
}
/**
* The main invocation method of the MessageService. Instanciates a MessageService instance if needed,
* and returns the active instance.
* @return The MessageService instance
*/
public static MessageService getInstance() {
if (!_invoked) _singleton = new MessageService();
return _singleton;
}
/**
* This method boots ans starts the thread running the MessageService
*/
public void boot() {
if (!_running) {
log.info("Booting MessageService...");
_serviceThread = new Thread(() -> {
_running = true;
_singleton.run();
});
_serviceThread.setName("MessageService");
_serviceThread.start();
}
}
/**
* This method must contain the operations needed for ths class to register itself as a listener
* to the different objects it wants to listen to. This method will be called after all Core Services have
* been booted.
*/
@Override
public void registerListenerSupport() {
// Register self as a listener for topic events
TopicService.getInstance().addTopicChangeListener(this);
}
/**
* This method should be called from within the run-scope of the serverThread thread instance
*/
public void run() {
if (_invoked) {
log.info("MessageService booted successfully");
while (_running) {
try {
// Fetch the next job, will wait until a new message arrives
Message m = queue.take();
log.info("Recieved a message for distrubution: " + m);
// Do we have a system message?
if (m.isSystemMessage() && m.getTopic() == null) {
log.debug("Recieved message was a SystemMessage: " + m.getMessage());
// Check if we are to broadcast this system message
if (Application.BROADCAST_SYSTEM_MESSAGES_TO_SUBSCRIBERS) {
log.debug("System Message Broadcast set to TRUE, distributing system message...");
// Generate duplicate messages to all topics and iterate over them
generateMessageToAllTopics(m).stream().forEach(message -> {
// Fetch all protocol servers, and call sendMessage on each
CoreService.getInstance().getAllProtocolServers().forEach(s -> s.sendMessage(message));
// Flag the message as processed
message.setProcessed();
});
log.info("System message distribution completed");
}
// Set original message as processed.
m.setProcessed();
// Continue the run loop
continue;
}
HashSet<Topic> mappings = TopicService.getInstance().getAllMappingsAgainstTopic(m.getTopic());
if (mappings == null) {
log.debug("The topic: " + m.getTopic() + " has no mappings");
} else {
log.debug("Found the following mappings against topic: " + m.getTopic() + ": " + mappings);
generateMessageForAGivenTopicSet(m, mappings).forEach(duplicateMessage -> {
duplicateMessage.setAttribute("duplicate", m.getTopic());
if (m.getAttribute("duplicate") != null) {
if ( ! m.getTopic().equals(duplicateMessage.getAttribute("duplicate"))) {
distributeMessage(duplicateMessage);
} else {
log.debug("The message to topic: " + duplicateMessage.getTopic() + " is a duplicate against topic: " + m.getTopic() +", and will not be distributed");
}
} else {
distributeMessage(duplicateMessage);
}
});
}
// Tell the ExecutorService to execute the following job
CoreService.getInstance().execute(() -> {
// Add message to latestMessages cache
latestMessages.put(m.getTopic(), m);
// Fetch all registered protocol servers, and call the sendMessage() method on them
CoreService.getInstance().getAllProtocolServers().forEach(p -> {
// Fire the sendMessage on all servers
p.sendMessage(m);
});
// Set the message as processed, and store the completion time
LocalDateTime completedAt = m.setProcessed();
log.info("Message successfully distributed: " + m + " (Finished at: " + completedAt + ")");
});
} catch (InterruptedException e) {
log.error("Interrupted while attempting to fetch next Message from queue");
}
}
log.debug("MessageService serverThread exited main run loop");
} else {
log.error("Run method called before invocation of the MessageService getInstance method");
}
}
/**
* Graceful shutdown method
*/
@Override
public void stop() {
_running = false;
// Create a new message with topic = null, hence it will reside upon the config flag for system messages
// in the web admin if the message is distributed to all topics or just performed as a no-op.
Message m = new Message("The broker is shutting down.", null, null, Application.OKSE_SYSTEM_NAME);
// Set it to system message
m.setSystemMessage(true);
try {
queue.put(m);
} catch (InterruptedException e) {
log.error("Interrupted while trying to inject shutdown message to queue");
}
}
/**
* Adds a Message object into the message queue for distribution
* @param m The message object to be distributed
*/
public void distributeMessage(Message m) {
try {
this.queue.put(m);
} catch (InterruptedException e) {
log.error("Interrupted while trying to inject message into queue");
}
}
/**
* Retrieves the latest message sent on a specific topic
* @param topic The topic to retrieve the latest message for
* @return The message object for the specified topic, null if there has not been any messages yet
*/
public Message getLatestMessage(String topic) {
if (latestMessages.containsKey(topic)) return latestMessages.get(topic);
return null;
}
/**
* Check if the OKSE system is currently caching messages
* @return True if this setting is set to true, false otherwise
*/
public boolean isCachingMessages() {
return Application.CACHE_MESSAGES;
}
/**
* Takes in a message and a HashSet of topics and creates duplicate messages of
* the origin message, and returns it as a list.
* @param m The origin message
* @param topics A HashSet containing all the topics that the message topic is mapped against
* @return A containing the new message objects, to dispatch into the queue.
*/
public List<Message> generateMessageForAGivenTopicSet(Message m, HashSet<Topic> topics) {
ArrayList<Message> collector = new ArrayList<>();
topics.stream()
.forEach(t -> {
Message msg = new Message(m.getMessage(), t.getFullTopicString(), m.getPublisher(), m.getOriginProtocol());
collector.add(msg);
});
return collector;
}
/* Private helper methods */
/**
* Private helper method to duplicate an incoming message to be
* @param m The message to be duplicated to all topics
* @return A HashSet of the generated messages
*/
private HashSet<Message> generateMessageToAllTopics(Message m) {
// Initialize the collector
HashSet<Message> generated = new HashSet<>();
// Iterate over all topics and generate individual messages per topic
TopicService.getInstance().getAllTopics().stream().forEach(t -> {
// Create the message wrapper
Message msg = new Message(m.getMessage(), t.getFullTopicString(), m.getPublisher(), m.getOriginProtocol());
// Flag the generated message the same as the originating message
msg.setSystemMessage(m.isSystemMessage());
// Add the message to the collector
generated.add(msg);
});
return generated;
}
/* Begin observation methods */
@Override
public void topicChanged(TopicChangeEvent event) {
if (event.getType().equals(TopicChangeEvent.Type.DELETE)) {
// Fetch the raw topic string from the deleted topic
String rawTopicString = event.getData().getFullTopicString();
// If we have messages in cache for the topic in question, remove it to remove any remaining
// reference to the Topic node, so the garbage collector can do its job.
if (latestMessages.containsKey(rawTopicString)) {
latestMessages.remove(rawTopicString);
log.debug("Removed a message from cache due to its topic being deleted");
}
}
}
/* End observation methods */
} |
package org.biouno.unochoice.model;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.biouno.unochoice.util.Utils;
import org.jenkinsci.plugins.scriptler.ScriptlerManagement;
import org.jenkinsci.plugins.scriptler.config.Script;
import org.jenkinsci.plugins.scriptler.config.ScriptlerConfiguration;
import org.jenkinsci.plugins.scriptler.util.ScriptHelper;
import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.bind.JavaScriptMethod;
import hudson.Extension;
import hudson.Util;
import jenkins.model.Jenkins;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* A scriptler script.
*
* @author Bruno P. Kinoshita
* @since 0.1
*/
public class ScriptlerScript extends AbstractScript {
/*
* Serial UID.
*/
private static final long serialVersionUID = -6600327523009436354L;
private final String scriptlerScriptId;
// Map is not serializable, but LinkedHashMap is. Ignore static analysis errors
private final Map<String, String> parameters;
@DataBoundConstructor
public ScriptlerScript(String scriptlerScriptId, List<ScriptlerScriptParameter> parameters) {
super();
this.scriptlerScriptId = scriptlerScriptId;
this.parameters = new LinkedHashMap<String, String>();
if (parameters != null) {
for (ScriptlerScriptParameter parameter : parameters) {
this.parameters.put(parameter.getName(), parameter.getValue());
}
}
}
/**
* @return the scriptlerScriptId
*/
public String getScriptlerScriptId() {
return scriptlerScriptId;
}
/**
* @return the parameters
*/
public Map<String, String> getParameters() {
return parameters;
}
@Override
public Object eval() {
return eval(null);
}
/*
* (non-Javadoc)
* @see org.biouno.unochoice.model.Script#eval(java.util.Map)
*/
@Override
public Object eval(Map<String, String> parameters) {
final Map<String, String> envVars = Utils.getSystemEnv();
Map<String, String> evaledParameters = new LinkedHashMap<String, String>(envVars);
// if we have any parameter that came from UI, let's eval and use them
if (parameters != null && !parameters.isEmpty()) {
// fill our map with the given parameters
evaledParameters.putAll(parameters);
// and now try to expand env vars
for (String key : this.getParameters().keySet()) {
String value = this.getParameters().get(key);
value = Util.replaceMacro((String) value, parameters);
evaledParameters.put(key, value);
}
} else {
evaledParameters.putAll(this.getParameters());
}
return this.toGroovyScript().eval(evaledParameters);
}
/**
* Converts this scriptler script to a GroovyScript.
*
* @return a GroovyScript
*/
public GroovyScript toGroovyScript() {
final Script scriptler = ScriptHelper.getScript(getScriptlerScriptId(), true);
return new GroovyScript(new SecureGroovyScript(scriptler.script, false, null), null);
}
@Extension(optional = true)
public static class DescriptorImpl extends ScriptDescriptor {
static {
// make sure this class fails to load during extension discovery if scriptler isn't present
ScriptlerManagement.getScriptlerHomeDirectory();
}
/*
* (non-Javadoc)
*
* @see hudson.model.Descriptor#getDisplayName()
*/
@Override
public String getDisplayName() {
return "Scriptler Script";
}
@Override
public AbstractScript newInstance(StaplerRequest req, JSONObject jsonObject) throws FormException {
ScriptlerScript script = null;
String scriptScriptId = jsonObject.getString("scriptlerScriptId");
if (scriptScriptId != null && !scriptScriptId.trim().equals("")) {
List<ScriptlerScriptParameter> parameters = new ArrayList<ScriptlerScriptParameter>();
final JSONObject defineParams = jsonObject.getJSONObject("defineParams");
if (defineParams != null && !defineParams.isNullObject()) {
JSONObject argsObj = defineParams.optJSONObject("parameters");
if (argsObj == null) {
JSONArray argsArrayObj = defineParams.optJSONArray("parameters");
if (argsArrayObj != null) {
for (int i = 0; i < argsArrayObj.size(); i++) {
JSONObject obj = argsArrayObj.getJSONObject(i);
String name = obj.getString("name");
String value = obj.getString("value");
if (name != null && !name.trim().equals("") && value != null) {
ScriptlerScriptParameter param = new ScriptlerScriptParameter(name, value);
parameters.add(param);
}
}
}
} else {
String name = argsObj.getString("name");
String value = argsObj.getString("value");
if (name != null && !name.trim().equals("") && value != null) {
ScriptlerScriptParameter param = new ScriptlerScriptParameter(name, value);
parameters.add(param);
}
}
}
script = new ScriptlerScript(scriptScriptId, parameters);
}
return script;
}
private ScriptlerManagement getScriptler() {
return Jenkins.getInstance().getExtensionList(ScriptlerManagement.class).get(0);
}
private ScriptlerConfiguration getConfig() {
return getScriptler().getConfiguration();
}
/**
* gets the argument description to be displayed on the screen when selecting a config in the dropdown
*
* @param scriptlerScriptId
* the config id to get the arguments description for
* @return the description
*/
@JavaScriptMethod
public JSONArray getParameters(String scriptlerScriptId) {
final Script script = getConfig().getScriptById(scriptlerScriptId);
if (script != null && script.getParameters() != null) {
return JSONArray.fromObject(script.getParameters());
}
return null;
}
}
} |
package org.dasein.cloud.google.network;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.dc.Region;
import org.dasein.cloud.google.Google;
import org.dasein.cloud.google.GoogleMethod;
import org.dasein.cloud.google.GoogleOperationType;
import org.dasein.cloud.google.capabilities.GCEVPNCapabilities;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.network.AbstractVPNSupport;
import org.dasein.cloud.network.IPVersion;
import org.dasein.cloud.network.VPN;
import org.dasein.cloud.network.VPNCapabilities;
import org.dasein.cloud.network.VPNConnection;
import org.dasein.cloud.network.VPNConnectionState;
import org.dasein.cloud.network.VPNGateway;
import org.dasein.cloud.network.VPNGatewayCreateOptions;
import org.dasein.cloud.network.VPNGatewayState;
import org.dasein.cloud.network.VPNProtocol;
import org.dasein.cloud.network.VPNState;
import org.dasein.cloud.network.VpnCreateOptions;
import org.dasein.cloud.util.APITrace;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.ForwardingRule;
import com.google.api.services.compute.model.ForwardingRuleList;
import com.google.api.services.compute.model.Network;
import com.google.api.services.compute.model.Operation;
import com.google.api.services.compute.model.Route;
import com.google.api.services.compute.model.RouteList;
import com.google.api.services.compute.model.TargetVpnGateway;
import com.google.api.services.compute.model.TargetVpnGatewayList;
import com.google.api.services.compute.model.VpnTunnel;
import com.google.api.services.compute.model.VpnTunnelList;
public class VPNSupport extends AbstractVPNSupport<Google> {
private Google provider;
private VPNCapabilities capabilities;
protected VPNSupport(Google provider) {
super(provider);
this.provider = provider;
}
@Override
public String[] mapServiceAction(ServiceAction action) {
// TODO Auto-generated method stub
return null;
}
@Override
public void attachToVLAN(String providerVpnId, String providerVlanId) throws CloudException, InternalException {
throw new OperationNotSupportedException("vlans are integral in GCE VPNS and are attached by createVPN");
}
@Override
public VPN createVPN(VpnCreateOptions vpnLaunchOptions) throws CloudException, InternalException {
APITrace.begin(provider, "createVPN");
VPN vpn = new VPN();
try {
vpn.setName(vpnLaunchOptions.getName());
vpn.setDescription(vpnLaunchOptions.getDescription());
Compute gce = getProvider().getGoogleCompute();
try {
GoogleMethod method = new GoogleMethod(getProvider());
TargetVpnGateway vpnGatewayContent = new TargetVpnGateway();
vpnGatewayContent.setName(vpnLaunchOptions.getName());
vpnGatewayContent.setDescription(vpnLaunchOptions.getDescription());
Network net = gce.networks().get(getContext().getAccountNumber(), vpnLaunchOptions.getProviderVlanId()).execute();
vpnGatewayContent.setNetwork(net.getSelfLink());
Operation op = gce.targetVpnGateways().insert(getContext().getAccountNumber(), getContext().getRegionId(), vpnGatewayContent).execute();
method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null);
vpn.setName(vpnLaunchOptions.getName());
vpn.setDescription(vpnLaunchOptions.getDescription());
vpn.setProtocol(vpnLaunchOptions.getProtocol());
vpn.setProviderVpnId(vpnLaunchOptions.getProviderVlanId());
String ipAddress = getProvider().getNetworkServices().getIpAddressSupport().request(IPVersion.IPV4);
vpn.setProviderVpnIP(getProvider().getNetworkServices().getIpAddressSupport().getIpAddress(ipAddress).getRawAddress().getIpAddress());
createForwardingRule(vpnLaunchOptions.getName(), "-rule-esp", vpn.getProviderVpnIp(), "ESP", null);
createForwardingRule(vpnLaunchOptions.getName(), "-rule-udp500", vpn.getProviderVpnIp(), "UDP", "500");
createForwardingRule(vpnLaunchOptions.getName(), "-rule-udp4500", vpn.getProviderVpnIp(), "UDP", "4500");
} catch ( Exception e ) {
throw new CloudException(e);
}
} finally {
APITrace.end();
}
return vpn;
}
@Override
public void deleteVPN(String providerVpnId) throws CloudException, InternalException {
APITrace.begin(provider, "deleteVPN");
try {
Compute gce = getProvider().getGoogleCompute();
try {
GoogleMethod method = new GoogleMethod(getProvider());
Operation op = null;
TargetVpnGateway v = gce.targetVpnGateways().get(getContext().getAccountNumber(), getContext().getRegionId(), providerVpnId).execute();
RouteList routes = gce.routes().list(getContext().getAccountNumber()).execute();
if ((null != routes) && (null != routes.getItems())) {
for (Route route : routes.getItems()) {
if ((null != route.getNextHopVpnTunnel()) &&
(route.getName().replaceAll(".*/", "").equals(providerVpnId))) {
op = gce.routes().delete(getContext().getAccountNumber(), route.getName()).execute();
method.getOperationComplete(getContext(), op, GoogleOperationType.GLOBAL_OPERATION, null, null);
}
}
}
for (String forwardingRule : v.getForwardingRules()) {
ForwardingRule fr = gce.forwardingRules().get(getContext().getAccountNumber(), getContext().getRegionId(), forwardingRule.replaceAll(".*/", "")).execute();
String ipAddress = fr.getIPAddress();
op = gce.forwardingRules().delete(getContext().getAccountNumber(), getContext().getRegionId(), forwardingRule.replaceAll(".*/", "")).execute();
method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null);
try {
String ipAddressName = getProvider().getNetworkServices().getIpAddressSupport().getIpAddressIdFromIP(ipAddress, getContext().getRegionId());
getProvider().getNetworkServices().getIpAddressSupport().releaseFromPool(ipAddressName);
} catch (InternalException e) { } // NOP if it already got freed.
}
op = gce.targetVpnGateways().delete(getContext().getAccountNumber(), getContext().getRegionId(), providerVpnId).execute();
method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null);
} catch (IOException e ) {
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
private void createForwardingRule(@Nonnull String targetVpnGatewayId, @Nonnull String ruleName, @Nonnull String ipAddress, @Nonnull String protocol, @Nullable String portRange) throws CloudException, InternalException {
GoogleMethod method = new GoogleMethod(getProvider());
Compute gce = getProvider().getGoogleCompute();
ForwardingRule frContent = new ForwardingRule();
frContent.setName(targetVpnGatewayId + ruleName);
frContent.setDescription(targetVpnGatewayId + ruleName);
frContent.setIPAddress(ipAddress);
frContent.setIPProtocol(protocol);
if (protocol.equalsIgnoreCase("UDP")) {
frContent.setPortRange(portRange);
}
frContent.setTarget(gce.getBaseUrl() + getContext().getAccountNumber() + "/regions/" + getContext().getRegionId() +"/targetVpnGateways/" + targetVpnGatewayId);
Operation op;
try {
op = gce.forwardingRules().insert(getContext().getAccountNumber(), getContext().getRegionId(), frContent ).execute();
} catch (Exception e ) {
throw new CloudException(e);
}
method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null);
}
@Override
public @Nonnull VPNGateway createVPNGateway(@Nonnull VPNGatewayCreateOptions vpnGatewayCreateOptions) throws CloudException, InternalException {
APITrace.begin(provider, "createVPNGateway");
try {
GoogleMethod method = new GoogleMethod(getProvider());
Compute gce = getProvider().getGoogleCompute();
Operation op = null;
VpnTunnel content = new VpnTunnel();
content.setName(vpnGatewayCreateOptions.getName());
content.setDescription(vpnGatewayCreateOptions.getDescription());
if (VPNProtocol.IKE_V1 == vpnGatewayCreateOptions.getProtocol()) {
content.setIkeVersion(1);
} else if (VPNProtocol.IKE_V2 == vpnGatewayCreateOptions.getProtocol()) {
content.setIkeVersion(2);
}
content.setPeerIp(vpnGatewayCreateOptions.getEndpoint());
content.setSharedSecret(vpnGatewayCreateOptions.getSharedSecret());
content.setTargetVpnGateway(gce.getBaseUrl() + getContext().getAccountNumber() + "/regions/" + getContext().getRegionId() +"/targetVpnGateways/" + vpnGatewayCreateOptions.getVpnName());
op = gce.vpnTunnels().insert(getContext().getAccountNumber(), getContext().getRegionId(), content).execute();
method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null);
createRoute(vpnGatewayCreateOptions.getName(), vpnGatewayCreateOptions.getVlanName(), vpnGatewayCreateOptions.getDescription(), vpnGatewayCreateOptions.getCidr(), getContext().getRegionId());
VpnTunnel vpnAfter = gce.vpnTunnels().get(getContext().getAccountNumber(), getContext().getRegionId(), vpnGatewayCreateOptions.getName()).execute();
return toVPNGateway(vpnAfter);
} catch ( Exception e ) {
throw new CloudException(e);
} finally {
APITrace.end();
}
}
@Override
public void connectToGateway(String providerVpnId, String toGatewayId) throws CloudException, InternalException {
throw new OperationNotSupportedException("connectToGateway in GCE VPNS is performed by createVPNGateway");
}
private void createRoute(String vpnName, String name, String description, String cidr, String providerRegionId) throws CloudException, InternalException {
GoogleMethod method = new GoogleMethod(getProvider());
Compute gce = getProvider().getGoogleCompute();
Operation op = null;
Route routeContent = new Route();
routeContent.setName(name);
routeContent.setDescription(description);
routeContent.setNetwork(gce.getBaseUrl() + getContext().getAccountNumber() + "/global/networks/" + name);
routeContent.setPriority(1000L);
routeContent.setDestRange(cidr);
routeContent.setNextHopVpnTunnel(gce.getBaseUrl() + getContext().getAccountNumber() + "/regions/" + providerRegionId +"/vpnTunnels/" + vpnName);
try {
op = gce.routes().insert(getContext().getAccountNumber(), routeContent ).execute();
} catch (IOException e) {
throw new CloudException(e);
}
method.getOperationComplete(getContext(), op, GoogleOperationType.GLOBAL_OPERATION, null, null);
}
@Override
public void disconnectFromGateway(String providerVpnId, String fromGatewayId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Gateway are not supported by GCE VPN's");
}
@Override
public void deleteVPNGateway(String providerVPNGatewayId) throws CloudException, InternalException {
APITrace.begin(provider, "deleteVPNGateway");
try {
Compute gce = getProvider().getGoogleCompute();
Operation op = null;
GoogleMethod method = new GoogleMethod(getProvider());
op = gce.vpnTunnels().delete(getContext().getAccountNumber(), getContext().getRegionId(), providerVPNGatewayId).execute();
method.getOperationComplete(getContext(), op, GoogleOperationType.REGION_OPERATION, getContext().getRegionId(), null);
} catch ( IOException e ) {
throw new CloudException(e);
} finally {
APITrace.end();
}
}
private VPNGateway toVPNGateway(VpnTunnel vpnTunnel) {
VPNGateway vpnGateway = new VPNGateway();
vpnGateway.setName(vpnTunnel.getName());
vpnGateway.setDescription(vpnTunnel.getDescription());
vpnGateway.setProviderRegionId(vpnTunnel.getRegion().replaceAll(".*/", ""));
vpnGateway.setEndpoint(vpnTunnel.getPeerIp());
if (1 == vpnTunnel.getIkeVersion()) {
vpnGateway.setProtocol(VPNProtocol.IKE_V1);
} else if (2 == vpnTunnel.getIkeVersion()) {
vpnGateway.setProtocol(VPNProtocol.IKE_V2);
}
String status = vpnTunnel.getStatus();
if (status.equals("WAITING_FOR_FULL_CONFIG")) {
vpnGateway.setCurrentState(VPNGatewayState.PENDING);
} else {
vpnGateway.setCurrentState(VPNGatewayState.AVAILABLE);
}
return vpnGateway;
}
@Override
public void detachFromVLAN(String providerVpnId, String providerVlanId) throws CloudException, InternalException {
throw new OperationNotSupportedException("vlans are integral in GCE VPNS and are detatched by deleteVPN");
}
@Override
public VPNCapabilities getCapabilities() throws CloudException, InternalException {
if (capabilities == null) {
capabilities = new GCEVPNCapabilities(provider);
}
return capabilities;
}
@Override
public VPNGateway getGateway(String gatewayId) throws CloudException, InternalException {
Compute gce = getProvider().getGoogleCompute();
VpnTunnel vpnAfter;
try {
vpnAfter = gce.vpnTunnels().get(getContext().getAccountNumber(), getContext().getRegionId(), gatewayId).execute();
} catch ( IOException e ) {
throw new CloudException(e);
}
return toVPNGateway(vpnAfter);
}
@Override
public VPN getVPN(String providerTargetVPNGatewayId) throws CloudException, InternalException {
APITrace.begin(provider, "getVPN");
try {
Compute gce = getProvider().getGoogleCompute();
Collection<Region> regions = getProvider().getDataCenterServices().listRegions();
for (Region region : regions) {
TargetVpnGatewayList tunnels = gce.targetVpnGateways().list(getContext().getAccountNumber(), region.getName()).execute();
if ((null != tunnels) && (null != tunnels.getItems())) {
List<TargetVpnGateway> targetVpnGatewayItems = tunnels.getItems();
for (TargetVpnGateway targetVpnGateway : targetVpnGatewayItems) {
if (providerTargetVPNGatewayId.equals(targetVpnGateway.getName())) {
return toVPN(targetVpnGateway);
}
}
}
}
return null;
} catch (IOException e) {
throw new CloudException(e);
} finally {
APITrace.end();
}
}
public VPN toVPN(TargetVpnGateway targetVpnGateway) {
VPN vpn = new VPN();
vpn.setName(targetVpnGateway.getName());
vpn.setDescription(targetVpnGateway.getDescription());
vpn.setProviderVpnId(targetVpnGateway.getId().toString());
return vpn;
}
@Override
public Iterable<VPNConnection> listGatewayConnections(String toGatewayId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Gateway are not supported by GCE VPN's");
}
@Override
public Iterable<ResourceStatus> listGatewayStatus() throws CloudException, InternalException {
throw new OperationNotSupportedException("Gateway are not supported by GCE VPN's");
}
@Override
public Iterable<VPNGateway> listGateways() throws CloudException, InternalException {
throw new OperationNotSupportedException("Gateway are not supported by GCE VPN's");
}
@Override
public Iterable<VPNGateway> listGatewaysWithBgpAsn(String bgpAsn) throws CloudException, InternalException {
throw new OperationNotSupportedException("GCE VPNS do not support bgpAsn");
}
@Override
public Iterable<VPNConnection> listVPNConnections(String toVpnId) throws CloudException, InternalException {
APITrace.begin(provider, "listVPNConnections");
VPN vpn = getVPN(toVpnId);
List<VPNConnection> vpnConnections = new ArrayList<VPNConnection>();
try {
Compute gce = getProvider().getGoogleCompute();
Collection<Region> regions = getProvider().getDataCenterServices().listRegions();
for (Region region : regions) {
VpnTunnelList tunnels;
try {
tunnels = gce.vpnTunnels().list(getContext().getAccountNumber(), region.getName()).execute();
} catch ( IOException e ) {
throw new CloudException(e);
}
if ((null != tunnels) && (null != tunnels.getItems())) {
for (VpnTunnel vpnTunnel : tunnels.getItems()) {
if (toVpnId.equals(vpnTunnel.getTargetVpnGateway().replaceAll(".*/", ""))) {
VPNConnection vpnConnection = new VPNConnection();
if (vpnTunnel.getIkeVersion() == 1) {
vpnConnection.setProtocol(VPNProtocol.IKE_V1);
} else if (vpnTunnel.getIkeVersion() == 2) {
vpnConnection.setProtocol(VPNProtocol.IKE_V2);
}
if (vpnTunnel.getStatus().equals("ESTABLISHED")) {
vpnConnection.setCurrentState(VPNConnectionState.AVAILABLE);
} else {
vpnConnection.setCurrentState(VPNConnectionState.PENDING);
}
vpnConnection.setProviderGatewayId(vpnTunnel.getPeerIp());
vpnConnection.setProviderVpnConnectionId(vpnTunnel.getName());
vpnConnection.setProviderVpnId(vpn.getName());
vpnConnections.add(vpnConnection);
}
}
}
}
} finally {
APITrace.end();
}
return vpnConnections;
}
@Override
public Iterable<ResourceStatus> listVPNStatus() throws CloudException, InternalException {
APITrace.begin(provider, "listVPNStatus");
List<ResourceStatus> statusList = new ArrayList<ResourceStatus>();
try {
Compute gce = getProvider().getGoogleCompute();
Collection<Region> regions = getProvider().getDataCenterServices().listRegions();
for (Region region : regions) {
VpnTunnelList tunnels = null;
try {
tunnels = gce.vpnTunnels().list(getContext().getAccountNumber(), region.getName()).execute();
} catch ( IOException e ) {
throw new CloudException(e);
}
if ((null != tunnels) && (null != tunnels.getItems())) {
for (VpnTunnel tunnel : tunnels.getItems()) {
if (tunnel.getStatus().equals("ESTABLISHED")) {
ResourceStatus status = new ResourceStatus(tunnel.getName(), VPNState.AVAILABLE);
statusList.add(status);
} else {
ResourceStatus status = new ResourceStatus(tunnel.getName(), VPNState.PENDING);
statusList.add(status);
}
}
}
}
} finally {
APITrace.end();
}
return statusList;
}
@Override
public Iterable<VPN> listVPNs() throws CloudException, InternalException {
APITrace.begin(provider, "listVPNs");
List<VPN> vpns = new ArrayList<VPN>();
try {
Compute gce = getProvider().getGoogleCompute();
Collection<Region> regions = getProvider().getDataCenterServices().listRegions();
for (Region region : regions) {
VpnTunnelList tunnels = gce.vpnTunnels().list(getContext().getAccountNumber(), region.getName()).execute();
if (null != tunnels.getItems()) {
for (VpnTunnel tunnel : tunnels.getItems()) {
VPN vpn = new VPN();
vpn.setName(tunnel.getName());
vpn.setDescription(tunnel.getDescription());
vpn.setProviderVpnId(tunnel.getId().toString());
if (1 == tunnel.getIkeVersion()) {
vpn.setProtocol(VPNProtocol.IKE_V1);
} else if (2 == tunnel.getIkeVersion()) {
vpn.setProtocol(VPNProtocol.IKE_V2);
}
if (tunnel.getStatus().equals("ESTABLISHED")) {
vpn.setCurrentState(VPNState.AVAILABLE);
} else {
vpn.setCurrentState(VPNState.PENDING); // TODO does it have more states?
}
TargetVpnGateway gateway = gce.targetVpnGateways().get(getContext().getAccountNumber(), region.getName(), tunnel.getTargetVpnGateway().replaceAll(".*/", "")).execute();
String[] networks = {gateway.getNetwork().replaceAll(".*/", "")};
vpn.setProviderVlanIds(networks);
ForwardingRuleList frl = gce.forwardingRules().list(getContext().getAccountNumber(), region.getName()).execute();
if (null != frl.getItems()) {
for (ForwardingRule fr : frl.getItems()) {
if (fr.getTarget().equals(gateway.getSelfLink())) {
vpn.setProviderVpnIP(fr.getIPAddress());
}
}
}
vpns.add(vpn);
}
}
}
} catch ( Exception e ) {
throw new CloudException(e);
} finally {
APITrace.end();
}
return vpns;
}
@Override
public Iterable<VPNProtocol> listSupportedVPNProtocols() throws CloudException, InternalException {
return getCapabilities().listSupportedVPNProtocols();
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(provider, "isSubscribed");
try {
listVPNs();
return true;
} catch (Exception e) {
return false;
} finally {
APITrace.end();
}
}
@Deprecated
@Override
public Requirement getVPNDataCenterConstraint() throws CloudException, InternalException {
return Requirement.NONE;
}
} |
package org.embulk.decoder;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.embulk.decoder.CommonsCompressDecoderPlugin.PluginTask;
import org.embulk.spi.util.FileInputInputStream;
import org.embulk.spi.util.InputStreamFileInput.Provider;
class CommonsCompressProvider implements Provider {
private static final String AUTO_DETECT_FORMAT = "";
private final FileInputInputStream files;
private final boolean formatAutoDetection;
private Iterator<InputStream> inputStreamIterator;
private String[] formats;
private final boolean decompressConcatenated;
private final String matchName;
CommonsCompressProvider(PluginTask task, FileInputInputStream files) {
this.files = files;
this.formatAutoDetection = task == null
|| CommonsCompressUtil.isAutoDetect(task.getFormat());
if (!this.formatAutoDetection) {
formats = CommonsCompressUtil.toFormats(task.getFormat());
if (formats == null) {
throw new RuntimeException("Failed to get a format.");
}
}
this.decompressConcatenated = task == null
|| task.getDecompressConcatenated();
this.matchName = (task == null)? "" : task.getMatchName();
}
@Override
public InputStream openNext() throws IOException {
while (true) {
if (inputStreamIterator == null) {
if (!files.nextFile()) {
return null;
}
inputStreamIterator = formatAutoDetection ? createInputStreamIterator(files)
: createInputStreamIterator(formats, 0, files);
} else {
if (inputStreamIterator.hasNext()) {
InputStream in = inputStreamIterator.next();
if (in == null) {
inputStreamIterator = null;
} else {
return in;
}
} else {
inputStreamIterator = null;
}
}
}
}
@Override
public void close() throws IOException {
inputStreamIterator = null;
if (files != null) {
files.close();
}
}
boolean isFormatAutoDetection() {
return formatAutoDetection;
}
String[] getFormats() {
return formats;
}
Iterator<InputStream> createInputStreamIterator(InputStream in)
throws IOException {
// It is required to support mark to detect a file format.
in = in.markSupported() ? in : new BufferedInputStream(in);
try {
return new ArchiveInputStreamIterator(
createArchiveInputStream(AUTO_DETECT_FORMAT, in),
this.matchName
);
} catch (IOException | ArchiveException e) {
// ArchiveStreamFactory set mark and reset the stream.
// So, we can use the same stream to check compressor.
try {
return toIterator(createCompressorInputStream(AUTO_DETECT_FORMAT, in));
} catch (CompressorException e2) {
throw new IOException("Failed to detect a file format.", e2);
}
}
}
/**
* Create iterator to list InputStream for each archived/compressed file.
*
* This can handle like the following formats:
* 1 archived format which defined in ArchiveStreamFactory(e.g. tar)
* 1 archived format and 1 compressor format defined in CompressorStreamFactory.(e.g. tar.bz2)
* 1 compressor format defined in CompressorStreamFactory.(e.g. bz2)
* (Actually, compressor formats can use two or more times in this code.
* But it is not common case.)
*/
Iterator<InputStream> createInputStreamIterator(String[] inputFormats,
int pos, InputStream in) throws IOException {
if (pos >= inputFormats.length) {
return toIterator(in);
}
try {
String format = inputFormats[pos];
if (CommonsCompressUtil.isArchiveFormat(format)) {
return new ArchiveInputStreamIterator(
createArchiveInputStream(format, in),
this.matchName);
} else if (CommonsCompressUtil.isCompressorFormat(format)) {
return createInputStreamIterator(inputFormats, pos + 1,
createCompressorInputStream(format, in));
}
throw new IOException("Unsupported format is configured. format:"
+ format);
} catch (ArchiveException | CompressorException e) {
throw new IOException(e);
}
}
/**
* Create a new ArchiveInputStream to read an archive file based on a format
* parameter.
*
* If format is not set, this method tries to detect file format
* automatically. In this case, BufferedInputStream is used to wrap
* FileInputInputStream instance. BufferedInputStream may read a data
* partially when calling files.nextFile(). However, it doesn't matter
* because the partial read data should be discarded. And then this method
* is called again to create a new ArchiveInputStream.
*
* @return a new ArchiveInputStream instance.
*/
ArchiveInputStream createArchiveInputStream(String format, InputStream in)
throws IOException, ArchiveException {
ArchiveStreamFactory factory = new ArchiveStreamFactory();
if (CommonsCompressUtil.isAutoDetect(format)) {
in = in.markSupported() ? in : new BufferedInputStream(in);
try {
return factory.createArchiveInputStream(in);
} catch (ArchiveException e) {
throw new IOException(
"Failed to detect a file format. Please try to set a format explicitly.",
e);
}
} else {
return factory.createArchiveInputStream(format, in);
}
}
CompressorInputStream createCompressorInputStream(String format,
InputStream in) throws IOException, CompressorException {
CompressorStreamFactory factory = new CompressorStreamFactory();
factory.setDecompressConcatenated(decompressConcatenated);
if (CommonsCompressUtil.isAutoDetect(format)) {
in = in.markSupported() ? in : new BufferedInputStream(in);
try {
return factory.createCompressorInputStream(in);
} catch (CompressorException e) {
throw new IOException(
"Failed to detect a file format. Please try to set a format explicitly.",
e);
}
} else {
return factory.createCompressorInputStream(format, in);
}
}
private Iterator<InputStream> toIterator(InputStream in) {
List<InputStream> list = new ArrayList<InputStream>(1);
list.add(in);
return list.iterator();
}
} |
package org.embulk.filter.to_csv;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import org.embulk.config.Config;
import org.embulk.config.ConfigDefault;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.config.TaskSource;
import org.embulk.spi.Column;
import org.embulk.spi.ColumnVisitor;
import org.embulk.spi.Exec;
import org.embulk.spi.FilterPlugin;
import org.embulk.spi.Page;
import org.embulk.spi.PageBuilder;
import org.embulk.spi.PageOutput;
import org.embulk.spi.PageReader;
import org.embulk.spi.Schema;
import org.embulk.spi.time.Timestamp;
import org.embulk.spi.time.TimestampFormatter;
import org.embulk.spi.type.Type;
import org.embulk.spi.type.Types;
import org.embulk.spi.util.Newline;
import org.embulk.spi.util.Timestamps;
import org.msgpack.value.Value;
import org.slf4j.Logger;
import java.util.Map;
public class ToCsvFilterPlugin
implements FilterPlugin
{
public enum QuotePolicy
{
ALL("ALL"),
MINIMAL("MINIMAL"),
NONE("NONE");
private final String string;
QuotePolicy(String string)
{
this.string = string;
}
public String getString()
{
return string;
}
}
public interface TimestampColumnOption
extends Task, TimestampFormatter.TimestampColumnOption
{
}
public interface PluginTask
extends Task, TimestampFormatter.Task
{
@Config("column_name")
@ConfigDefault("\"payload\"")
String getColumnName();
@Config("header_line")
@ConfigDefault("false")
boolean getHeaderLine();
@Config("delimiter")
@ConfigDefault("\",\"")
char getDelimiterChar();
@Config("quote")
@ConfigDefault("\"\\\"\"")
char getQuoteChar();
@Config("quote_policy")
@ConfigDefault("\"MINIMAL\"")
QuotePolicy getQuotePolicy();
@Config("escape")
@ConfigDefault("null")
Optional<Character> getEscapeChar();
@Config("null_string")
@ConfigDefault("\"\"")
String getNullString();
@Config("newline_in_field")
@ConfigDefault("\"LF\"")
Newline getNewlineInField();
@Config("column_options")
@ConfigDefault("{}")
Map<String, TimestampColumnOption> getColumnOptions();
}
private final Logger logger = Exec.getLogger(ToCsvFilterPlugin.class);
private final static int INDEX = 0;
private final static Type TYPE = Types.STRING;
@Override
public void transaction(ConfigSource config, Schema inputSchema,
FilterPlugin.Control control)
{
PluginTask task = config.loadConfig(PluginTask.class);
// validate column_options
for (String columnName : task.getColumnOptions().keySet()) {
inputSchema.lookupColumn(columnName); // throws SchemaConfigException
}
Schema outputSchema = new Schema(ImmutableList.of(new Column(INDEX, task.getColumnName(), TYPE)));
logger.debug("output schema: {}", outputSchema);
control.run(task.dump(), outputSchema);
}
@Override
public PageOutput open(TaskSource taskSource, final Schema inputSchema,
final Schema outputSchema, final PageOutput output)
{
final PluginTask task = taskSource.loadTask(PluginTask.class);
final TimestampFormatter[] timestampFormatters = Timestamps.newTimestampColumnFormatters(task, inputSchema, task.getColumnOptions());
final char delimiter = task.getDelimiterChar();
final QuotePolicy quotePolicy = task.getQuotePolicy();
final char quote = task.getQuoteChar() != '\0' ? task.getQuoteChar() : '"';
final char escape = task.getEscapeChar().or(quotePolicy == QuotePolicy.NONE ? '\\' : quote);
final String nullString = task.getNullString();
final String newlineInField = task.getNewlineInField().getString();
final boolean writeHeaderLine = task.getHeaderLine();
return new PageOutput() {
private boolean shouldWriteHeaderLine = writeHeaderLine;
private final PageBuilder pageBuilder = new PageBuilder(Exec.getBufferAllocator(), outputSchema, output);
private final PageReader pageReader = new PageReader(inputSchema);
private final Column outputColumn = outputSchema.getColumn(INDEX);
private final String delimiterString = String.valueOf(delimiter);
private final StringBuilder lineBuilder = new StringBuilder();
private final ColumnVisitor visitor = new ColumnVisitor() {
@Override
public void booleanColumn(Column column)
{
addDelimiter(column);
if (!pageReader.isNull(column)) {
addValue(Boolean.toString(pageReader.getBoolean(column)));
} else {
addNullString();
}
}
@Override
public void longColumn(Column column)
{
addDelimiter(column);
if (!pageReader.isNull(column)) {
addValue(Long.toString(pageReader.getLong(column)));
} else {
addNullString();
}
}
@Override
public void doubleColumn(Column column)
{
addDelimiter(column);
if (!pageReader.isNull(column)) {
addValue(Double.toString(pageReader.getDouble(column)));
} else {
addNullString();
}
}
@Override
public void stringColumn(Column column)
{
addDelimiter(column);
if (!pageReader.isNull(column)) {
addValue(pageReader.getString(column));
} else {
addNullString();
}
}
@Override
public void timestampColumn(Column column)
{
addDelimiter(column);
if (!pageReader.isNull(column)) {
Timestamp value = pageReader.getTimestamp(column);
addValue(timestampFormatters[column.getIndex()].format(value));
} else {
addNullString();
}
}
@Override
public void jsonColumn(Column column)
{
addDelimiter(column);
if (!pageReader.isNull(column)) {
Value value = pageReader.getJson(column);
addValue(value.toJson());
} else {
addNullString();
}
}
private void addDelimiter(Column column)
{
if (column.getIndex() != 0) {
lineBuilder.append(delimiterString);
}
}
private void addValue(String v)
{
lineBuilder.append(setEscapeAndQuoteValue(v, delimiter, quotePolicy, quote, escape, newlineInField, nullString));
}
private void addNullString()
{
lineBuilder.append(nullString);
}
};
@Override
public void add(Page page)
{
writeHeader();
pageReader.setPage(page);
while (pageReader.nextRecord()) {
pageReader.getSchema().visitColumns(visitor);
addRecord();
}
}
@Override
public void finish()
{
pageBuilder.finish();
}
@Override
public void close()
{
pageBuilder.close();
}
private void addRecord()
{
pageBuilder.setString(outputColumn, lineBuilder.toString());
pageBuilder.addRecord();
clearLineBuilder();
}
private void clearLineBuilder()
{
lineBuilder.setLength(0);
}
private void writeHeader()
{
if (!shouldWriteHeaderLine) {
return;
}
for (Column column : pageReader.getSchema().getColumns()) {
if (column.getIndex() != 0) {
lineBuilder.append(delimiterString);
}
lineBuilder.append(setEscapeAndQuoteValue(column.getName(), delimiter, quotePolicy, quote, escape, newlineInField, nullString));
}
addRecord();
shouldWriteHeaderLine = false;
}
};
}
private String setEscapeAndQuoteValue(String v, char delimiter, QuotePolicy policy, char quote, char escape, String newline, String nullString)
{
StringBuilder escapedValue = new StringBuilder();
char previousChar = ' ';
boolean isRequireQuote = (policy == QuotePolicy.ALL || policy == QuotePolicy.MINIMAL && v.equals(nullString));
for (int i = 0; i < v.length(); i++) {
char c = v.charAt(i);
if (policy != QuotePolicy.NONE && c == quote) {
escapedValue.append(escape);
escapedValue.append(c);
isRequireQuote = true;
} else if (c == '\r') {
if (policy == QuotePolicy.NONE) {
escapedValue.append(escape);
}
escapedValue.append(newline);
isRequireQuote = true;
} else if (c == '\n') {
if (previousChar != '\r') {
if (policy == QuotePolicy.NONE) {
escapedValue.append(escape);
}
escapedValue.append(newline);
isRequireQuote = true;
}
} else if (c == delimiter) {
if (policy == QuotePolicy.NONE) {
escapedValue.append(escape);
}
escapedValue.append(c);
isRequireQuote = true;
} else {
escapedValue.append(c);
}
previousChar = c;
}
if (policy != QuotePolicy.NONE && isRequireQuote) {
return setQuoteValue(escapedValue.toString(), quote);
} else {
return escapedValue.toString();
}
}
private String setQuoteValue(String v, char quote)
{
return String.valueOf(quote) + v + quote;
}
} |
package org.jenkinsci.plugins.p4.console;
import com.perforce.p4java.server.callback.ICommandCallback;
import hudson.model.TaskListener;
import java.util.logging.Logger;
public class P4Logging implements ICommandCallback {
private static Logger logger = Logger.getLogger(P4Logging.class.getName());
private final TaskListener listener;
private static int MAX_LINE = 80;
public P4Logging(TaskListener listener) {
this.listener = listener;
}
public void issuingServerCommand(int key, String commandString) {
logger.finest("issuingServerCommand: (" + key + ") " + commandString);
if (commandString.length() > MAX_LINE) {
String cmd = commandString.substring(0, MAX_LINE);
cmd = cmd + "___";
log("(p4):cmd:" + "... p4 " + cmd);
} else {
log("(p4):cmd:" + "... p4 " + commandString);
}
log("p4 " + commandString + "\n");
}
public void completedServerCommand(int key, long millisecsTaken) {
logger.finest("completedServerCommand: (" + key + ") in " + millisecsTaken + "ms");
}
public void receivedServerInfoLine(int key, String infoLine) {
}
public void receivedServerErrorLine(int key, String errorLine) {
}
public void receivedServerMessage(int key, int genericCode,
int severityCode, String message) {
}
public TaskListener getListener() {
return listener;
}
private void log(String msg) {
if (listener == null) {
return;
}
listener.getLogger().println(msg);
}
} |
package org.jfrog.hudson;
import hudson.EnvVars;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Cause;
import jenkins.model.Jenkins;
import org.apache.commons.lang.StringUtils;
import org.jfrog.build.api.Agent;
import org.jfrog.build.api.Build;
import org.jfrog.build.api.BuildAgent;
import org.jfrog.build.api.BuildInfoProperties;
import org.jfrog.build.api.BuildRetention;
import org.jfrog.build.api.BuildType;
import org.jfrog.build.api.LicenseControl;
import org.jfrog.build.api.builder.BuildInfoBuilder;
import org.jfrog.build.api.builder.PromotionStatusBuilder;
import org.jfrog.build.api.release.Promotion;
import org.jfrog.build.client.ArtifactoryBuildInfoClient;
import org.jfrog.build.client.IncludeExcludePatterns;
import org.jfrog.build.client.PatternMatcher;
import org.jfrog.hudson.action.ActionableHelper;
import org.jfrog.hudson.release.ReleaseAction;
import org.jfrog.hudson.util.BuildRetentionFactory;
import org.jfrog.hudson.util.ExtractorUtils;
import org.jfrog.hudson.util.IncludesExcludes;
import org.jfrog.hudson.util.IssuesTrackerHelper;
import java.io.IOException;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
/**
* Handles build info creation and deployment
*
* @author Shay Yaakov
*/
public class AbstractBuildInfoDeployer {
private BuildInfoAwareConfigurator configurator;
protected AbstractBuild build;
protected BuildListener listener;
protected ArtifactoryBuildInfoClient client;
private EnvVars env;
public AbstractBuildInfoDeployer(BuildInfoAwareConfigurator configurator, AbstractBuild build,
BuildListener listener, ArtifactoryBuildInfoClient client) throws IOException, InterruptedException {
this.configurator = configurator;
this.build = build;
this.listener = listener;
this.client = client;
this.env = build.getEnvironment(listener);
}
protected Build createBuildInfo(String buildAgentName, String buildAgentVersion, BuildType buildType) {
BuildInfoBuilder builder = new BuildInfoBuilder(
ExtractorUtils.sanitizeBuildName(build.getParent().getFullName()))
.number(build.getNumber() + "").type(buildType)
.buildAgent(new BuildAgent(buildAgentName, buildAgentVersion))
.agent(new Agent("hudson", build.getHudsonVersion()));
String buildUrl = ActionableHelper.getBuildUrl(build);
if (StringUtils.isNotBlank(buildUrl)) {
builder.url(buildUrl);
}
Calendar startedTimestamp = build.getTimestamp();
builder.startedDate(startedTimestamp.getTime());
long duration = System.currentTimeMillis() - startedTimestamp.getTimeInMillis();
builder.durationMillis(duration);
String artifactoryPrincipal = configurator.getArtifactoryServer().getResolvingCredentials().getUsername();
if (StringUtils.isBlank(artifactoryPrincipal)) {
artifactoryPrincipal = "";
}
builder.artifactoryPrincipal(artifactoryPrincipal);
String userCause = ActionableHelper.getUserCausePrincipal(build);
if (userCause != null) {
builder.principal(userCause);
}
Cause.UpstreamCause parent = ActionableHelper.getUpstreamCause(build);
if (parent != null) {
String parentProject = ExtractorUtils.sanitizeBuildName(parent.getUpstreamProject());
int parentNumber = parent.getUpstreamBuild();
builder.parentName(parentProject);
builder.parentNumber(parentNumber + "");
if (StringUtils.isBlank(userCause)) {
builder.principal("auto");
}
}
String revision = ExtractorUtils.getVcsRevision(env);
if (StringUtils.isNotBlank(revision)) {
builder.vcsRevision(revision);
}
addBuildInfoProperties(builder);
LicenseControl licenseControl = new LicenseControl(configurator.isRunChecks());
if (configurator.isRunChecks()) {
if (StringUtils.isNotBlank(configurator.getViolationRecipients())) {
licenseControl.setLicenseViolationsRecipientsList(configurator.getViolationRecipients());
}
if (StringUtils.isNotBlank(configurator.getScopes())) {
licenseControl.setScopesList(configurator.getScopes());
}
}
licenseControl.setIncludePublishedArtifacts(configurator.isIncludePublishArtifacts());
licenseControl.setAutoDiscover(configurator.isLicenseAutoDiscovery());
builder.licenseControl(licenseControl);
BuildRetention buildRetention = new BuildRetention(configurator.isDiscardBuildArtifacts());
if (configurator.isDiscardOldBuilds()) {
buildRetention = BuildRetentionFactory.createBuildRetention(build, configurator.isDiscardBuildArtifacts());
}
builder.buildRetention(buildRetention);
if ((Jenkins.getInstance().getPlugin("jira") != null) && configurator.isEnableIssueTrackerIntegration()) {
new IssuesTrackerHelper(build, listener, configurator.isAggregateBuildIssues(),
configurator.getAggregationBuildStatus()).setIssueTrackerInfo(builder);
}
// add staging status if it is a release build
ReleaseAction release = ActionableHelper.getLatestAction(build, ReleaseAction.class);
if (release != null) {
String stagingRepoKey = release.getStagingRepositoryKey();
if (StringUtils.isBlank(stagingRepoKey)) {
stagingRepoKey = configurator.getRepositoryKey();
}
builder.addStatus(new PromotionStatusBuilder(Promotion.STAGED)
.timestampDate(startedTimestamp.getTime())
.comment(release.getStagingComment())
.repository(stagingRepoKey)
.ciUser(userCause).user(artifactoryPrincipal).build());
}
Build buildInfo = builder.build();
// for backwards compatibility for Artifactory 2.2.3
if (parent != null) {
buildInfo.setParentBuildId(parent.getUpstreamProject());
}
return buildInfo;
}
private void addBuildInfoProperties(BuildInfoBuilder builder) {
if (configurator.isIncludeEnvVars()) {
IncludesExcludes envVarsPatterns = configurator.getEnvVarsPatterns();
if (envVarsPatterns != null) {
IncludeExcludePatterns patterns = new IncludeExcludePatterns(envVarsPatterns.getIncludePatterns(),
envVarsPatterns.getExcludePatterns());
// First add all build related variables
addBuildVariables(builder, patterns);
// Then add env variables
addEnvVariables(builder, patterns);
// And finally add system variables
addSystemVariables(builder, patterns);
}
}
}
private void addBuildVariables(BuildInfoBuilder builder, IncludeExcludePatterns patterns) {
Map<String, String> buildVariables = build.getBuildVariables();
for (Map.Entry<String, String> entry : buildVariables.entrySet()) {
String varKey = entry.getKey();
if (PatternMatcher.pathConflicts(varKey, patterns)) {
continue;
}
builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + varKey, entry.getValue());
}
}
private void addEnvVariables(BuildInfoBuilder builder, IncludeExcludePatterns patterns) {
for (Map.Entry<String, String> entry : env.entrySet()) {
String varKey = entry.getKey();
if (PatternMatcher.pathConflicts(varKey, patterns)) {
continue;
}
builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + varKey, entry.getValue());
}
}
private void addSystemVariables(BuildInfoBuilder builder, IncludeExcludePatterns patterns) {
Properties systemProperties = System.getProperties();
Enumeration<?> enumeration = systemProperties.propertyNames();
while (enumeration.hasMoreElements()) {
String propertyKey = (String) enumeration.nextElement();
if (PatternMatcher.pathConflicts(propertyKey, patterns)) {
continue;
}
builder.addProperty(propertyKey, systemProperties.getProperty(propertyKey));
}
}
} |
package org.jtrfp.trcl.beh;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.obj.Player;
public class LoopingPositionBehavior extends Behavior {
private static final double THRESHOLD = TR.mapCartOffset;
@Override
public void tick(long timeInMillis){
// Loop correction
double [] oldPos = getParent().getPosition();
boolean _transient=false;
if (getParent().supportsLoop()){
if (oldPos[0] > THRESHOLD)
{oldPos[0]-=TR.mapWidth;_transient=true;}
if (oldPos[2] > THRESHOLD)
{oldPos[2]-=TR.mapWidth;_transient=true;}
if (oldPos[0] < -THRESHOLD)
{oldPos[0]+=TR.mapWidth;_transient=true;}
if (oldPos[2] < -THRESHOLD)
{oldPos[2]+=TR.mapWidth;_transient=true;}
if(_transient)getParent().notifyPositionChange();
}//end if(LOOP)
}//end _tick(...)
}//end LoopingPositionBehavior |
package org.minimalj.frontend.impl.web;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;
import java.util.Locale;
import java.util.Locale.LanguageRange;
import java.util.Map;
import java.util.logging.Logger;
import org.minimalj.application.Application;
import org.minimalj.application.Configuration;
import org.minimalj.frontend.impl.json.JsonFrontend;
import org.minimalj.frontend.impl.json.JsonSessionManager;
import org.minimalj.util.resources.Resources;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Response.Status;
public class MjWebDaemon extends NanoHTTPD {
private static final Logger logger = Logger.getLogger(MjWebDaemon.class.getName());
private JsonSessionManager sessionManager = new JsonSessionManager();
public MjWebDaemon(int port, boolean secure) {
super(port);
if (secure) {
try {
// note 1: to first read the property MjKeystorePassphrase and then convert it to char[]
// makes the whole char[] story senseless. But how to do it else? Maybe specify a filename
// and then read it byte by byte.
// note 2: nanohttpd implies that keypass and storepass are the same passwords. I don't
// know if this is a good idea.
// note 3: example to generate the store (todo: move to documentation)
// keytool.exe -keystore mjdevkeystore.jks -keyalg RSA -keysize 3072 -genkeypair -dname "cn=localhost, ou=MJ, o=Minimal-J, c=CH" -storepass mjdev1 -keypass mjdev1
// keytool.exe -keystore mjdevkeystore.jks -storepass mjdev1 -keypass mjdev1 -export -file mj.cer
String keyAndTrustStoreClasspathPath = Configuration.get("MjKeystore"); // in example '/mjdevkeystore.jks'
char[] passphrase = Configuration.get("MjKeystorePassphrase").toCharArray(); // ub example 'mjdev1'
makeSecure(makeSSLSocketFactory(keyAndTrustStoreClasspathPath, passphrase), null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms,
Map<String, String> files) {
return serve(sessionManager, uri, method, headers, parms, files);
}
static Response serve(JsonSessionManager sessionManager, String uriString, Method method, Map<String, String> headers, Map<String, String> parms,
Map<String, String> files) {
URI uri = URI.create(uriString);
String path = uri.getPath();
if (path.equals("/ajax_request.xml")) {
String data = files.get("postData");
String result = sessionManager.handle(data);
return newFixedLengthResponse(Status.OK, "text/xml", result);
} else if (path.equals("/application.png")) {
return newChunkedResponse(Status.OK, "png", Application.getInstance().getIcon());
} else if (path.contains(".")) {
if (path.contains("..")) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/html", uri + " bad request");
}
int index = uriString.lastIndexOf('.');
if (index > -1 && index < uriString.length() - 1) {
String postfix = uriString.substring(index + 1);
String mimeType = Resources.getMimeType(postfix);
if (mimeType != null) {
InputStream inputStream = MjWebDaemon.class.getResourceAsStream(uriString);
if (inputStream != null) {
return newChunkedResponse(Status.OK, mimeType, inputStream);
}
}
}
return newFixedLengthResponse(Status.NOT_FOUND, "text/html", uri + " not found");
} else {
String htmlTemplate = JsonFrontend.getHtmlTemplate();
Locale locale = getLocale(headers.get("accept-language"));
String html = JsonFrontend.fillPlaceHolder(htmlTemplate, locale, path);
return newFixedLengthResponse(Status.OK, "text/html", html);
}
}
private static Locale getLocale(String userLocale) {
final List<LanguageRange> ranges = Locale.LanguageRange.parse(userLocale);
if (ranges != null) {
for (LanguageRange languageRange : ranges) {
final String localeString = languageRange.getRange();
final Locale locale = Locale.forLanguageTag(localeString);
return locale;
}
}
return null;
}
} |
package org.minimalj.frontend.page;
import java.util.Collections;
import java.util.List;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.TableActionListener;
public abstract class TableDetailPage<T> extends TablePage<T> implements TableActionListener<T> {
private Page detailPage;
public TableDetailPage() {
super();
}
// better: createDetailPage
protected abstract Page getDetailPage(T mainObject);
protected Page getDetailPage(List<T> selectedObjects) {
if (selectedObjects == null || selectedObjects.size() != 1) {
return null;
} else {
return getDetailPage(selectedObjects.get(selectedObjects.size() - 1));
}
}
@Override
public void action(T selectedObject) {
showDetail(selectedObject);
}
@SuppressWarnings("unchecked")
protected void showDetail(T object) {
if (detailPage instanceof ChangeableDetailPage) {
((ChangeableDetailPage<T>) detailPage).setObjects(Collections.singletonList(object));
setDetailPage(detailPage);
} else {
Page newDetailPage = getDetailPage(object);
setDetailPage(newDetailPage);
}
}
@SuppressWarnings("unchecked")
@Override
public void selectionChanged(List<T> selectedObjects) {
super.selectionChanged(selectedObjects);
boolean detailVisible = isDetailVisible();
if (detailVisible && !selectedObjects.isEmpty()) {
if (detailPage instanceof ChangeableDetailPage) {
((ChangeableDetailPage<T>) detailPage).setObjects(selectedObjects);
} else {
Page newDetailPage = getDetailPage(selectedObjects);
setDetailPage(newDetailPage);
}
}
}
protected void setDetailPage(Page newDetailPage) {
if (newDetailPage != null) {
Frontend.showDetail(TableDetailPage.this, newDetailPage);
} else if (detailPage != null) {
Frontend.hideDetail(detailPage);
}
detailPage = newDetailPage;
}
protected boolean isDetailVisible() {
return detailPage != null && Frontend.isDetailShown(detailPage);
}
public interface ChangeableDetailPage<T> {
public void setObjects(List<T> objects);
}
} |
package org.owasp.esapi.reference;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.ValidationErrorList;
import org.owasp.esapi.ValidationRule;
import org.owasp.esapi.Validator;
import org.owasp.esapi.errors.IntrusionException;
import org.owasp.esapi.errors.ValidationAvailabilityException;
import org.owasp.esapi.errors.ValidationException;
import org.owasp.esapi.reference.validation.CreditCardValidationRule;
import org.owasp.esapi.reference.validation.DateValidationRule;
import org.owasp.esapi.reference.validation.HTMLValidationRule;
import org.owasp.esapi.reference.validation.IntegerValidationRule;
import org.owasp.esapi.reference.validation.NumberValidationRule;
import org.owasp.esapi.reference.validation.StringValidationRule;
public class DefaultValidator implements org.owasp.esapi.Validator {
private static volatile Validator instance = null;
public static Validator getInstance() {
if ( instance == null ) {
synchronized ( Validator.class ) {
if ( instance == null ) {
instance = new DefaultValidator();
}
}
}
return instance;
}
/** A map of validation rules */
private Map<String, ValidationRule> rules = new HashMap<String, ValidationRule>();
/** The encoder to use for canonicalization */
private Encoder encoder = null;
/** The encoder to use for file system */
private static Validator fileValidator = null;
/** Initialize file validator with an appropriate set of codecs */
static {
List<String> list = new ArrayList<String>();
list.add( "HTMLEntityCodec" );
list.add( "PercentCodec" );
Encoder fileEncoder = new DefaultEncoder( list );
fileValidator = new DefaultValidator( fileEncoder );
}
/**
* Default constructor uses the ESAPI standard encoder for canonicalization.
*/
public DefaultValidator() {
this.encoder = ESAPI.encoder();
}
/**
* Construct a new DefaultValidator that will use the specified
* Encoder for canonicalization.
*
* @param encoder
*/
public DefaultValidator( Encoder encoder ) {
this.encoder = encoder;
}
/**
* Add a validation rule to the registry using the "type name" of the rule as the key.
*/
public void addRule( ValidationRule rule ) {
rules.put( rule.getTypeName(), rule );
}
/**
* Get a validation rule from the registry with the "type name" of the rule as the key.
*/
public ValidationRule getRule( String name ) {
return rules.get( name );
}
public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidInput( context, input, type, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException {
StringValidationRule rvr = new StringValidationRule( type, encoder );
Pattern p = ESAPI.securityConfiguration().getValidationPattern( type );
if ( p != null ) {
rvr.addWhitelistPattern( p );
} else {
rvr.addWhitelistPattern( type );
}
rvr.setMaximumLength(maxLength);
rvr.setAllowNull(allowNull);
return rvr.getValid(context, input);
}
public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInput(context, input, type, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
// TODO - optimize so that invalid input is not canonicalized twice
return encoder.canonicalize(input);
}
/**
* {@inheritDoc}
*/
public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException {
try {
getValidDate( context, input, format, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException {
DateValidationRule dvr = new DateValidationRule( "SimpleDate", encoder, format);
dvr.setAllowNull(allowNull);
return dvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDate(context, input, format, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return null
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidSafeHTML( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*
* This implementation relies on the OWASP AntiSamy project.
*/
public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException {
HTMLValidationRule hvr = new HTMLValidationRule( "safehtml", encoder );
hvr.setMaximumLength(maxLength);
hvr.setAllowNull(allowNull);
return hvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidSafeHTML(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*/
public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException {
try {
getValidCreditCard( context, input, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
CreditCardValidationRule ccvr = new CreditCardValidationRule( "creditcard", encoder );
ccvr.setAllowNull(allowNull);
return ccvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidCreditCard(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
// TODO - optimize so that invalid input is not canonicalized twice
return encoder.canonicalize(input);
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws IntrusionException {
try {
getValidDirectoryPath( context, input, parent, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws ValidationException, IntrusionException {
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context );
}
File dir = new File( input );
// check dir exists and parent exists and dir is inside parent
if ( !dir.exists() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, does not exist: context=" + context + ", input=" + input );
}
if ( !dir.isDirectory() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not a directory: context=" + context + ", input=" + input );
}
if ( !parent.exists() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent does not exist: context=" + context + ", input=" + input + ", parent=" + parent );
}
if ( !parent.isDirectory() ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent is not a directory: context=" + context + ", input=" + input + ", parent=" + parent );
}
if ( !dir.getCanonicalPath().startsWith(parent.getCanonicalPath() ) ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not inside specified parent: context=" + context + ", input=" + input + ", parent=" + parent );
}
// check canonical form matches input
String canonicalPath = dir.getCanonicalPath();
String canonical = fileValidator.getValidInput( context, canonicalPath, "DirectoryName", 255, false);
if ( !canonical.equals( input ) ) {
throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
return canonical;
} catch (Exception e) {
throw new ValidationException( context + ": Invalid directory name", "Failure to validate directory path: context=" + context + ", input=" + input, e, context );
}
}
/**
* {@inheritDoc}
*/
public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDirectoryPath(context, input, parent, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException {
return isValidFileName( context, input, ESAPI.securityConfiguration().getAllowedFileExtensions(), allowNull );
}
/**
* {@inheritDoc}
*/
public boolean isValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws IntrusionException {
try {
getValidFileName( context, input, allowedExtensions, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public String getValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException {
if ((allowedExtensions == null) || (allowedExtensions.isEmpty())) {
throw new ValidationException( "Internal Error", "You called getValidFileName with an empty or null list of allowed Extensions, therefor no files can be uploaded" );
}
String canonical = "";
// detect path manipulation
try {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context );
}
// do basic validation
canonical = new File(input).getCanonicalFile().getName();
getValidInput( context, input, "FileName", 255, true );
File f = new File(canonical);
String c = f.getCanonicalPath();
String cpath = c.substring(c.lastIndexOf(File.separator) + 1);
// the path is valid if the input matches the canonical path
if (!input.equals(cpath)) {
throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context );
}
} catch (IOException e) {
throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context );
}
// verify extensions
Iterator<String> i = allowedExtensions.iterator();
while (i.hasNext()) {
String ext = i.next();
if (input.toLowerCase().endsWith(ext.toLowerCase())) {
return canonical;
}
}
throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+allowedExtensions+")", "Invalid file name does not have valid extension ( "+allowedExtensions+"): context=" + context+", input=" + input, context );
}
/**
* {@inheritDoc}
*/
public String getValidFileName(String context, String input, List<String> allowedParameters, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileName(context, input, allowedParameters, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
// TODO - optimize so that invalid input is not canonicalized twice
try {
return new File(input).getCanonicalFile().getName();
} catch (IOException e) {
// TODO = consider logging canonicalization error?
return input;
}
}
/**
* {@inheritDoc}
*/
public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException {
try {
getValidNumber(context, input, minValue, maxValue, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException {
Double minDoubleValue = new Double(minValue);
Double maxDoubleValue = new Double(maxValue);
return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull);
}
/**
* {@inheritDoc}
*/
public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidNumber(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return null
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException {
try {
getValidDouble( context, input, minValue, maxValue, allowNull );
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException {
NumberValidationRule nvr = new NumberValidationRule( "number", encoder, minValue, maxValue );
nvr.setAllowNull(allowNull);
return nvr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidDouble(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return null
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException {
try {
getValidInteger( context, input, minValue, maxValue, allowNull);
return true;
} catch( ValidationException e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException {
IntegerValidationRule ivr = new IntegerValidationRule( "number", encoder, minValue, maxValue );
ivr.setAllowNull(allowNull);
return ivr.getValid(context, input);
}
/**
* {@inheritDoc}
*/
public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidInteger(context, input, minValue, maxValue, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return null;
}
/**
* {@inheritDoc}
*/
public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException {
try {
getValidFileContent( context, input, maxBytes, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* {@inheritDoc}
*/
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context );
}
long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize();
if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context );
if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context );
return input;
}
/**
* {@inheritDoc}
*/
public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidFileContent(context, input, maxBytes, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*
* <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath
* is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real
* path (/private/etc), not the symlink (/etc).</p>
*/
public boolean isValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException {
return( isValidFileName( context, filename, allowNull ) &&
isValidDirectoryPath( context, directorypath, parent, allowNull ) &&
isValidFileContent( context, content, maxBytes, allowNull ) );
}
/**
* {@inheritDoc}
*/
public void assertValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException {
getValidFileName( context, filename, allowedExtensions, allowNull );
getValidDirectoryPath( context, directorypath, parent, allowNull );
getValidFileContent( context, content, maxBytes, allowNull );
}
/**
* {@inheritDoc}
*/
public void assertValidFileUpload(String context, String filepath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
assertValidFileUpload(context, filepath, filename, parent, content, maxBytes, allowedExtensions, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
/**
* {@inheritDoc}
*
* Returns true if input is a valid list item.
*/
public boolean isValidListItem(String context, String input, List<String> list) {
try {
getValidListItem( context, input, list);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input
* will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidListItem(String context, String input, List<String> list) throws ValidationException, IntrusionException {
if (list.contains(input)) return input;
throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context );
}
/**
* ValidationErrorList variant of getValidListItem
*
* @param errors
*/
public String getValidListItem(String context, String input, List<String> list, ValidationErrorList errors) throws IntrusionException {
try {
return getValidListItem(context, input, list);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*/
public boolean isValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> requiredNames, Set<String> optionalNames) {
try {
assertValidHTTPRequestParameterSet( context, request, requiredNames, optionalNames);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Validates that the parameters in the current request contain all required parameters and only optional ones in
* addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* Uses current HTTPRequest
*/
public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional) throws ValidationException, IntrusionException {
Set<String> actualNames = request.getParameterMap().keySet();
// verify ALL required parameters are present
Set<String> missing = new HashSet<String>(required);
missing.removeAll(actualNames);
if (missing.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context );
}
// verify ONLY optional + required parameters are present
Set<String> extra = new HashSet<String>(actualNames);
extra.removeAll(required);
extra.removeAll(optional);
if (extra.size() > 0) {
throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context );
}
}
/**
* ValidationErrorList variant of assertIsValidHTTPRequestParameterSet
*
* Uses current HTTPRequest saved in ESAPI Authenticator
* @param errors
*/
public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional, ValidationErrorList errors) throws IntrusionException {
try {
assertValidHTTPRequestParameterSet(context, request, required, optional);
} catch (ValidationException e) {
errors.addError(context, e);
}
}
public boolean isValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* @throws IntrusionException
*/
public char[] getValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
if (isEmpty(input)) {
if (allowNull) return null;
throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context );
}
if (input.length > maxLength) {
throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + new String( input ), context);
}
for (int i = 0; i < input.length; i++) {
if (input[i] <= 0x20 || input[i] >= 0x7E ) {
throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + new String( input ), context);
}
}
return input;
}
/**
* ValidationErrorList variant of getValidPrintable
*
* @param errors
*/
public char[] getValidPrintable(String context, char[] input,int maxLength, boolean allowNull, ValidationErrorList errors)
throws IntrusionException {
try {
return getValidPrintable(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*
* Returns true if input is valid printable ASCII characters (32-126).
*/
public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException {
try {
getValidPrintable( context, input, maxLength, allowNull);
return true;
} catch( Exception e ) {
return false;
}
}
/**
* Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*
* @throws IntrusionException
*/
public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException {
try {
String canonical = encoder.canonicalize(input);
return new String( getValidPrintable( context, canonical.toCharArray(), maxLength, allowNull) );
//TODO - changed this to base Exception since we no longer need EncodingException
//TODO - this is a bit lame: we need to re-think this function.
} catch (Exception e) {
throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context);
}
}
/**
* ValidationErrorList variant of getValidPrintable
*
* @param errors
*/
public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidPrintable(context, input, maxLength, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* Returns true if input is a valid redirect location.
*/
public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException {
return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull);
}
/**
* Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack
* will generate a descriptive IntrusionException.
*/
public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException {
return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull);
}
/**
* ValidationErrorList variant of getValidRedirectLocation
*
* @param errors
*/
public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException {
try {
return getValidRedirectLocation(context, input, allowNull);
} catch (ValidationException e) {
errors.addError(context, e);
}
// error has been added to list, so return original input
return input;
}
/**
* {@inheritDoc}
*
* This implementation reads until a newline or the specified number of
* characters.
*
* @param in
* @param max
*/
public String safeReadLine(InputStream in, int max) throws ValidationException {
if (max <= 0) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream");
}
StringBuilder sb = new StringBuilder();
int count = 0;
int c;
try {
while (true) {
c = in.read();
if ( c == -1 ) {
if (sb.length() == 0) {
return null;
}
break;
}
if (c == '\n' || c == '\r') {
break;
}
count++;
if (count > max) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")");
}
sb.append((char) c);
}
return sb.toString();
} catch (IOException e) {
throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e);
}
}
/**
* Helper function to check if a String is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(String input) {
return (input==null || input.trim().length() == 0);
}
/**
* Helper function to check if a byte array is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(byte[] input) {
return (input==null || input.length == 0);
}
/**
* Helper function to check if a char array is empty
*
* @param input string input value
* @return boolean response if input is empty or not
*/
private final boolean isEmpty(char[] input) {
return (input==null || input.length == 0);
}
} |
package org.skife.jdbi.v2;
import org.skife.jdbi.v2.tweak.ContainerFactory;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
class ContainerFactoryRegistry
{
private final Map<Class<?>, ContainerFactory<?>> cache = new ConcurrentHashMap<Class<?>, ContainerFactory<?>>();
private final List<ContainerFactory> factories = new CopyOnWriteArrayList<ContainerFactory>();
ContainerFactoryRegistry()
{
factories.add(new ListContainerFactory());
factories.add(new SetContainerFactory());
factories.add(new SortedSetContainerFactory());
factories.add(new UnwrappedSingleValueFactory());
}
ContainerFactoryRegistry(ContainerFactoryRegistry parent)
{
cache.putAll(parent.cache);
factories.addAll(parent.factories);
}
void register(ContainerFactory<?> factory)
{
factories.add(factory);
cache.clear();
}
public ContainerFactoryRegistry createChild()
{
return new ContainerFactoryRegistry(this);
}
public ContainerBuilder createBuilderFor(Class<?> type)
{
if (cache.containsKey(type)) {
return cache.get(type).newContainerBuilderFor(type);
}
for (int i = factories.size(); i > 0; i
ContainerFactory factory = factories.get(i - 1);
if (factory.accepts(type)) {
cache.put(type, factory);
return factory.newContainerBuilderFor(type);
}
}
throw new IllegalStateException("No container builder available for " + type.getName());
}
static class SortedSetContainerFactory implements ContainerFactory<SortedSet<?>> {
public boolean accepts(Class<?> type)
{
return type.equals(SortedSet.class);
}
public ContainerBuilder<SortedSet<?>> newContainerBuilderFor(Class<?> type)
{
return new ContainerBuilder<SortedSet<?>>()
{
private SortedSet<Object> s = new TreeSet<Object>();
public ContainerBuilder<SortedSet<?>> add(Object it)
{
s.add(it);
return this;
}
public SortedSet<?> build()
{
return s;
}
};
}
}
static class SetContainerFactory implements ContainerFactory<Set<?>>
{
public boolean accepts(Class<?> type)
{
return Set.class.equals(type) || LinkedHashSet.class.equals(type);
}
public ContainerBuilder<Set<?>> newContainerBuilderFor(Class<?> type)
{
return new ContainerBuilder<Set<?>>()
{
private Set<Object> s = new LinkedHashSet<Object>();
public ContainerBuilder<Set<?>> add(Object it)
{
s.add(it);
return this;
}
public Set<?> build()
{
return s;
}
};
}
}
static class ListContainerFactory implements ContainerFactory<List<?>>
{
public boolean accepts(Class<?> type)
{
return type.equals(List.class) || type.equals(Collection.class) || type.equals(Iterable.class);
}
public ContainerBuilder<List<?>> newContainerBuilderFor(Class<?> type)
{
return new ListContainerBuilder();
}
}
} |
package org.xtx.ut4converter.export;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.xtx.ut4converter.MapConverter;
import org.xtx.ut4converter.UTGames.UnrealEngine;
import org.xtx.ut4converter.t3d.T3DRessource.Type;
import org.xtx.ut4converter.tools.Installation;
import org.xtx.ut4converter.ucore.MaterialInfo;
import org.xtx.ut4converter.ucore.UPackage;
import org.xtx.ut4converter.ucore.UPackageRessource;
public class UModelExporter extends UTPackageExtractor {
public static final String program = "umodel.exe";
public UModelExporter(MapConverter mapConverter) {
super(mapConverter);
}
@Override
public Set<File> extract(UPackageRessource ressource, boolean forceExport) throws Exception {
// Ressource ever extracted, we skip ...
if ((!forceExport && ressource.isExported()) || ressource.getUnrealPackage().getName().equals("null") || (!forceExport && ressource.getUnrealPackage().isExported())) {
return null;
}
String command = getExporterPath() + " -export -sounds -groups \"" + ressource.getUnrealPackage().getFileContainer(mapConverter) + "\"";
command += " -out=\"" + mapConverter.getTempExportFolder() + "\"";
command += " -path=\"" + mapConverter.getUserConfig().getGameConfigByGame(mapConverter.getInputGame()).getPath() + "\"";
List<String> logLines = new ArrayList<>();
logger.log(Level.INFO, "Exporting " + ressource.getUnrealPackage().getFileContainer(mapConverter).getName() + " with " + getName());
logger.log(Level.FINE, command);
Installation.executeProcess(command, logLines);
ressource.getUnrealPackage().setExported(true);
for (String logLine : logLines) {
logger.log(Level.FINE, logLine);
if (logLine.startsWith("Exporting") && !logLine.startsWith("Exporting objects")) {
parseRessourceExported(logLine, ressource.getUnrealPackage());
}
}
return null;
}
/**
* From umodel batch log lines get exported files and extra info about
* package ressources
*
* @param logLine
* Log line from umodel
* @param unrealPackage
* Current unreal package being exported with umodel
*/
private void parseRessourceExported(String logLine, UPackage unrealPackage) {
// Exporting Texture bdr02BA to
// Z:\\TEMP\\umodel_win32/UmodelExport/BarrensArchitecture/Borders
// Exporting StaticMesh trophy1 to
// Z:\\TEMP\\umodel_win32/UmodelExport/2k4Trophies/AllTrophies
String split[] = logLine.split(" to ");
String split2[] = split[0].split("\\ "); // Exporting Texture bdr02BA
// S_ASC_Arch2_SM_StonePillar_02
// bdr02BA
String name = split2[2];
// Z:\\TEMP\\umodel_win32\\UmodelExport/ASC_Arch2/SM/Mesh
String exportFolder = split[1];
int startIdx = exportFolder.lastIndexOf(unrealPackage.getName()) + unrealPackage.getName().length() + 1;
String group = null;
// Some ressources does not have group info
if (exportFolder.length() >= startIdx) {
// <xxx>CTF-Strident\Temp/LT_Deco/BSP/Materials -> BSP/Materials
group = exportFolder.substring(exportFolder.indexOf(unrealPackage.getName()) + unrealPackage.getName().length() + 1, exportFolder.length());
// BSP/Materials -> BSP.Materials
group = group.replaceAll("\\/", ".");
}
// StaticMesh3
String typeStr = split2[1];
Type type = Type.UNKNOWN;
if (typeStr.toLowerCase().contains("texture")) {
type = Type.TEXTURE;
}
else if (typeStr.toLowerCase().contains("staticmesh")) {
type = Type.STATICMESH;
}
else if (typeStr.toLowerCase().contains("sound")) {
type = Type.SOUND;
}
File exportedFile = null;
boolean isMaterial = false;
final String BASE_EXPORT_FILE = exportFolder + File.separator + name;
if (type == Type.STATICMESH) {
exportedFile = new File(BASE_EXPORT_FILE + ".pskx");
} else if (type == Type.TEXTURE) {
exportedFile = new File(BASE_EXPORT_FILE + ".tga");
}
// UMODEL does produce .mat files
// TODO handle .mat files for conversion
// either replace with Diffuse Texture or find out some library that can
// do the merging "diffuse + normal" stuff
else if (typeStr.toLowerCase().contains("material")) {
exportedFile = new File(BASE_EXPORT_FILE + ".mat");
isMaterial = true;
} else if (type == Type.SOUND) {
if (mapConverter.getInputGame().engine.version <= 2) {
exportedFile = new File(BASE_EXPORT_FILE + ".wav");
}
else if (mapConverter.getInputGame().engine.version == 3) {
exportedFile = new File(BASE_EXPORT_FILE + ".ogg");
}
}
String ressourceName;
if (group != null) {
ressourceName = unrealPackage.getName() + "." + group + "." + name;
} else {
ressourceName = unrealPackage.getName() + "." + name;
}
UPackageRessource uRessource = unrealPackage.findRessource(ressourceName);
if (uRessource != null) {
if (isMaterial && uRessource.getMaterialInfo() == null) {
uRessource.setMaterialInfo(getMatInfo(uRessource, exportedFile));
}
uRessource.setExportedFile(exportedFile);
uRessource.parseNameAndGroup(ressourceName); // for texture db that
// don't have group
// we retrieve the
// group ...
if(unrealPackage.isMapPackage(mapConverter.getMapPackageName())){
uRessource.setIsUsedInMap(true);
}
uRessource.setType(type);
} else {
uRessource = new UPackageRessource(mapConverter, ressourceName, unrealPackage, exportedFile, this);
uRessource.setType(type);
if (isMaterial) {
uRessource.setMaterialInfo(getMatInfo(uRessource, exportedFile));
// replace material with diffuse texture if possible
if (uRessource.getMaterialInfo() != null && uRessource.getMaterialInfo().getDiffuse() != null) {
// export diffuse texture if not ever done
uRessource.export(UTPackageExtractor.getExtractor(mapConverter, uRessource));
uRessource.replaceWith(uRessource.getMaterialInfo().getDiffuse());
}
}
}
}
private MaterialInfo getMatInfo(UPackageRessource parentRessource, File matFile) {
MaterialInfo mi = new MaterialInfo();
/**
* Diffuse=T_HU_Deco_SM_Machinery04Alt_D
* Normal=T_HU_Deco_SM_Machinery04Alt_N
* Specular=T_HU_Deco_SM_Machinery04Alt_S
* Emissive=T_HU_Deco_SM_Machinery04Alt_E
*/
try (FileReader fr = new FileReader(matFile); BufferedReader bfr = new BufferedReader(fr)) {
String line = null;
while ((line = bfr.readLine()) != null) {
String spl[] = line.split("\\=");
// Diffuse
String type = spl[0];
// T_HU_Deco_SM_Machinery04Alt_D
String matName = spl[1];
// guessing package name the material comes from
String pakName = parentRessource.getUnrealPackage().getName();
// .mat file does not only give ressource name not where it
// belong to
// we assume it belong to parent ressource which should work for
// 75%+ of cases ...
if (mapConverter.getUt3PackageFileFromName(pakName) == null) {
continue;
}
UPackageRessource uRessource = mapConverter.getUPackageRessource(matName, pakName, Type.TEXTURE);
if (uRessource != null) {
uRessource.setIsUsedInMap(parentRessource.isUsedInMap());
switch (type) {
case "Diffuse":
mi.setDiffuse(uRessource);
break;
case "Normal":
mi.setNormal(uRessource);
break;
case "Specular":
mi.setSpecular(uRessource);
break;
case "Emissive":
mi.setEmissive(uRessource);
break;
case "SpecPower":
mi.setSpecPower(uRessource);
break;
case "Opacity":
mi.setOpacity(uRessource);
break;
default:
logger.warning("Unhandled type " + type + " Value:" + matName);
break;
}
}
}
} catch (IOException exception) {
logger.log(Level.WARNING, "Could not get material info from " + parentRessource.getFullName());
}
return mi;
}
@Override
public File getExporterPath() {
return Installation.getUModelPath(mapConverter);
}
@Override
public boolean supportLinux() {
// false for the moment but might be possible to activate in some future
return false;
}
@Override
public String getName() {
return "umodel";
}
@Override
public UnrealEngine[] getSupportedEngines() {
return new UnrealEngine[] { UnrealEngine.UE1, UnrealEngine.UE2, UnrealEngine.UE3, UnrealEngine.UE4 };
}
} |
package ru.parallel.octotron.core.attributes;
import ru.parallel.octotron.core.primitive.exception.ExceptionModelFail;
import ru.parallel.octotron.core.primitive.exception.ExceptionParseError;
import ru.parallel.utils.JavaUtils;
import java.text.DecimalFormat;
public class Value
{
private static class Undefined
{
private Undefined() {}
public static final Undefined value = new Undefined();
@Override
public final String toString()
{
return "undefined";
}
}
private static class Invalid
{
private Invalid() {}
public static final Invalid value = new Invalid();
@Override
public final String toString()
{
return "invalid";
}
}
private final Object value;
private final Class<?> my_class;
private Value(Object value, Class<?> my_class)
{
this.value = value;
this.my_class = my_class;
}
public Value(Value value)
{
this.value = value.value;
this.my_class = value.my_class;
}
public static final Value undefined = new Value(Undefined.value, Undefined.class);
public static final Value invalid = new Value(Invalid.value, Invalid.class);
public boolean IsDefined()
{
return !equals(undefined);
}
public boolean IsValid()
{
return !equals(invalid);
}
/**
* tries to convert unchecked Object to the checked Value
* if it is a value already - does nothing
* */
public static Value Construct(Object value)
{
if(value == null)
throw new ExceptionModelFail("Value can not be null");
if(value instanceof Value)
return (Value) value;
else if(value instanceof Long)
return new Value(value, Long.class);
else if(value instanceof Integer)
return new Value(((Integer)value).longValue(), Long.class);
else if(value instanceof Double)
return new Value(value, Double.class);
else if(value instanceof Float)
return new Value(((Float)value).doubleValue(), Double.class);
else if(value instanceof Boolean)
return new Value(value, Boolean.class);
else if(value instanceof String)
return new Value(value, String.class);
else
throw new ExceptionModelFail("unsupported value type: " + value + " : " + value.getClass().getName());
}
public Value(Long value)
{
this(value, value.getClass());
}
public Value(Double value)
{
this(value, value.getClass());
}
public Value(Boolean value)
{
this(value, value.getClass());
}
public Value(String value)
{
this(value, value.getClass());
}
public Value(Integer value)
{
this(value.longValue(), Long.class);
}
public Value(Float value)
{
this(value.doubleValue(), Double.class);
}
private static final DecimalFormat df = new DecimalFormat("0.00"); // TODO: is it ok?
public final String ValueToString()
{
if(my_class.equals(Long.class))
return value.toString();
else if(my_class.equals(Double.class))
return df.format(value);
if(my_class.equals(Boolean.class))
return value.toString();
else if(my_class.equals(String.class))
return JavaUtils.Quotify((String)value);
else if(my_class.equals(Undefined.class))
return JavaUtils.Quotify(value.toString());
else if(my_class.equals(Invalid.class))
return JavaUtils.Quotify(value.toString());
else
throw new ExceptionModelFail("unexpected value: " + value + " : " + my_class);
}
public static Value ValueFromStr(String value_str)
throws ExceptionParseError
{
int str_len = value_str.length();
if(str_len == 0)
throw new ExceptionParseError("can not get value from empty string");
char last_char = value_str.charAt(str_len - 1);
char first_char = value_str.charAt(0);
if(first_char == '"' && last_char == '"')
{
return new Value(value_str.substring(1, value_str.length() - 1));
}
try { return new Value(Long.parseLong(value_str)); }
catch(NumberFormatException ignore){}
try { return new Value(Double.parseDouble(value_str)); }
catch(NumberFormatException ignore){}
if(value_str.equals("true")) return new Value(true);
if(value_str.equals("false")) return new Value(false);
if(value_str.equals("True")) return new Value(true);
if(value_str.equals("False")) return new Value(false);
return new Value(value_str);
}
public final Class<?> GetClass()
{
return my_class;
}
public final String GetString()
{
CheckType(String.class);
return (String) value;
}
public final Long GetLong()
{
CheckType(Long.class);
return (Long) value;
}
public final Double GetDouble()
{
CheckType(Double.class);
return (Double) value;
}
public final Boolean GetBoolean()
{
CheckType(Boolean.class);
return (Boolean) value;
}
public final Double ToDouble()
{
if(my_class.equals(Double.class))
return GetDouble();
else if(my_class.equals(Long.class))
return GetLong().doubleValue();
else
{
String error = String.format("bad value type for casting to Double: %s[%s]"
, ValueToString(), my_class.toString());
throw new ExceptionModelFail(error);
}
}
public void CheckType(Value check_value)
{
if(!my_class.equals(check_value.my_class))
{
String error = String.format("mismatch types: %s[%s] and %s[%s]"
, value, my_class.getName()
, check_value.value, check_value.my_class.getName());
throw new ExceptionModelFail(error);
}
}
public void CheckType(Class<?> check_class)
{
if(!my_class.equals(check_class))
{
String error = String.format("mismatch types: %s[%s] and [%s]"
, value, my_class.getName()
, check_class);
throw new ExceptionModelFail(error);
}
}
@Override
public int hashCode()
{
return value.hashCode();
}
@Override
public final boolean equals(Object object)
{
if(!(object instanceof Value))
return false;
Value cmp = ((Value)object);
return value.equals(cmp.value);
}
public final boolean eq(Value new_value)
{
CheckType(new_value);
return equals(new_value);
}
public final boolean aeq(Value new_value, Value aprx)
{
CheckType(new_value);
if(my_class.equals(Double.class))
return GetDouble() > new_value.GetDouble() - aprx.GetDouble()
&& GetDouble() < new_value.GetDouble() + aprx.GetDouble();
else if(my_class.equals(Long.class))
return GetLong() > new_value.GetLong() - aprx.GetLong()
&& GetLong() < new_value.GetLong() + aprx.GetLong();
else
{
String error = String.format("bad value type type for approximate comparison: %s[%s]"
, ValueToString(), my_class.toString());
throw new ExceptionModelFail(error);
}
}
public final boolean ne(Value new_value)
{
return !eq(new_value);
}
public static final double EPSILON = 0.00001;
public final boolean gt(Value new_value)
{
CheckType(new_value);
if(my_class.equals(Double.class))
return GetDouble() > new_value.GetDouble() + EPSILON;
else if(my_class.equals(Long.class))
return GetLong() > new_value.GetLong();
else
{
String error = String.format("bad value type type for comparison: %s[%s]"
, ValueToString(), my_class.toString());
throw new ExceptionModelFail(error);
}
}
public final boolean lt(Value new_value)
{
CheckType(new_value);
if(my_class.equals(Double.class))
return GetDouble() < new_value.GetDouble() - EPSILON;
else if(my_class.equals(Long.class))
return GetLong() < new_value.GetLong();
else
{
String error = String.format("bad value type type for comparison: %s[%s]"
, ValueToString(), my_class.toString());
throw new ExceptionModelFail(error);
}
}
public final boolean ge(Value val)
{
return !lt(val);
}
public final boolean le(Value val)
{
return !gt(val);
}
public Object GetRaw()
{
return value;
}
} |
//@@author generated
package seedu.address.logic.commands;
import seedu.address.commons.core.EventsCenter;
import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.task.ReadOnlyTask;
/**
* Selects a person identified using it's last displayed index from the address book.
*/
public class SelectCommand extends Command {
public final int targetIndex;
public static final String COMMAND_WORD = "select";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Selects the task identified by the index number used in the last person listing.\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_SELECT_TASK_SUCCESS = "Selected task: %1$s";
public SelectCommand(int targetIndex) {
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute() throws CommandException {
UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
if (lastShownList.size() < targetIndex) {
throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
EventsCenter.getInstance().post(new JumpToListRequestEvent(targetIndex - 1));
return new CommandResult(String.format(MESSAGE_SELECT_TASK_SUCCESS, targetIndex));
}
@Override
public boolean isUndoable() {
return false;
}
} |
package seedu.geekeep.logic.commands;
import java.util.List;
import java.util.Optional;
import seedu.geekeep.commons.core.Messages;
import seedu.geekeep.commons.exceptions.IllegalValueException;
import seedu.geekeep.commons.util.CollectionUtil;
import seedu.geekeep.logic.commands.exceptions.CommandException;
import seedu.geekeep.model.tag.UniqueTagList;
import seedu.geekeep.model.task.DateTime;
import seedu.geekeep.model.task.Location;
import seedu.geekeep.model.task.ReadOnlyTask;
import seedu.geekeep.model.task.Task;
import seedu.geekeep.model.task.Title;
import seedu.geekeep.model.task.UniqueTaskList;
/**
* Edits the details of an existing task in the address book.
*/
public class UpdateCommand extends Command {
/**
* Stores the details to edit the task with. Each non-empty field value will replace the
* corresponding field value of the task.
*/
public static class EditTaskDescriptor {
private Optional<Title> title = Optional.empty();
private Optional<DateTime> endDateTime = Optional.empty();
private Optional<DateTime> startDateTime = Optional.empty();
private Optional<Location> location = Optional.empty();
private Optional<UniqueTagList> tags = Optional.empty();
public EditTaskDescriptor() {}
public EditTaskDescriptor(EditTaskDescriptor toCopy) {
this.title = toCopy.getTitle();
this.endDateTime = toCopy.getEndDateTime();
this.startDateTime = toCopy.getStartDateTime();
this.location = toCopy.getLocation();
this.tags = toCopy.getTags();
}
public Optional<DateTime> getEndDateTime() {
return endDateTime;
}
public Optional<Location> getLocation() {
return location;
}
public Optional<DateTime> getStartDateTime() {
return startDateTime;
}
public Optional<UniqueTagList> getTags() {
return tags;
}
public Optional<Title> getTitle() {
return title;
}
/**
* Returns true if at least one field is edited.
*/
public boolean isAnyFieldEdited() {
if (this.startDateTime == null || this.endDateTime == null) {
return true;
}
return CollectionUtil.isAnyPresent(this.title, this.location, this.tags,
this.startDateTime, this.endDateTime);
}
public void setEndDateTime(Optional<DateTime> endDateTime) {
this.endDateTime = endDateTime;
}
public void setLocation(Optional<Location> location) {
assert location != null;
this.location = location;
}
public void setStartDateTime(Optional<DateTime> startDateTime) {
this.startDateTime = startDateTime;
}
public void setTags(Optional<UniqueTagList> tags) {
assert tags != null;
this.tags = tags;
}
public void setTitle(Optional<Title> title) {
assert title != null;
this.title = title;
}
}
public static final String COMMAND_WORD = "update";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Updates the details of the task identified "
+ "by the index number used in the last task listing. "
+ "Existing values will be overwritten by the input values.\n"
+ "Parameters: INDEX (must be a positive integer) "
+ "[TITLE] [s/STARTING_TIME] [e/ENDING_TIME] [l/LOCATION] [t/TAG]...\n"
+ "Example: " + COMMAND_WORD + " 1 s/01-04-17 1630 e/01-04-17 1730";
public static final String MESSAGE_EDIT_TASK_SUCCESS = "Edited Task: %1$s";
public static final String MESSAGE_NOT_EDITED = "At least one field to edit must be provided.";
public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the task manager.";
private static Task createEditedTask(ReadOnlyTask taskToEdit,
EditTaskDescriptor editTaskDescriptor) throws IllegalValueException {
assert taskToEdit != null;
Title updatedTitle = editTaskDescriptor.getTitle().orElseGet(taskToEdit::getTitle);
DateTime updatedEndDateTime = null;
if (editTaskDescriptor.getEndDateTime() != null) {
updatedEndDateTime = editTaskDescriptor.getEndDateTime().orElseGet(taskToEdit::getEndDateTime);
}
DateTime updatedStartDateTime = null;
if (editTaskDescriptor.getStartDateTime() != null) {
updatedStartDateTime = editTaskDescriptor.getStartDateTime().orElseGet(taskToEdit::getStartDateTime);
}
Location updatedLocation = editTaskDescriptor.getLocation().orElseGet(taskToEdit::getLocation);
UniqueTagList updatedTags = editTaskDescriptor.getTags().orElseGet(taskToEdit::getTags);
return new Task(updatedTitle, updatedStartDateTime, updatedEndDateTime, updatedLocation, updatedTags);
}
private final int filteredTaskListIndex;
private final EditTaskDescriptor editTaskDescriptor;
/**
* @param filteredTaskListIndex the index of the task in the filtered task list to edit
* @param editTaskDescriptor details to edit the task with
*/
public UpdateCommand(int filteredTaskListIndex, EditTaskDescriptor editTaskDescriptor) {
assert filteredTaskListIndex > 0;
assert editTaskDescriptor != null;
// converts filteredTaskListIndex from one-based to zero-based.
this.filteredTaskListIndex = filteredTaskListIndex - 1;
this.editTaskDescriptor = new EditTaskDescriptor(editTaskDescriptor);
}
@Override
public CommandResult execute() throws CommandException {
List<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
if (filteredTaskListIndex >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
ReadOnlyTask taskToEdit = lastShownList.get(filteredTaskListIndex);
Task editedTask;
try {
editedTask = createEditedTask(taskToEdit, editTaskDescriptor);
} catch (IllegalValueException ive) {
throw new CommandException(ive.getMessage());
}
try {
model.updateTask(taskToEdit, editedTask);
} catch (UniqueTaskList.DuplicateTaskException dpe) {
throw new CommandException(MESSAGE_DUPLICATE_TASK);
} catch (IllegalValueException ive) {
throw new CommandException(ive.getMessage());
}
model.updateFilteredListToShowAll();
return new CommandResult(String.format(MESSAGE_EDIT_TASK_SUCCESS, taskToEdit));
}
} |
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyrl.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.*;
import wyautl.core.Automaton;
import wyautl.io.BinaryAutomataReader;
import wyautl.util.BigRational;
import wybs.io.BinaryInputStream;
import wybs.io.BinaryOutputStream;
import wyrl.core.Attribute;
import wyrl.core.Expr;
import wyrl.core.Pattern;
import wyrl.core.SpecFile;
import wyrl.core.Type;
import wyrl.core.Types;
import wyrl.core.SpecFile.RuleDecl;
import wyrl.util.*;
import static wyrl.core.Attribute.*;
import static wyrl.core.SpecFile.*;
public class NewJavaFileWriter {
private PrintWriter out;
private final HashMap<String, Type.Term> terms = new HashMap<String, Type.Term>();
public NewJavaFileWriter(Writer os) {
this.out = new PrintWriter(os);
}
public NewJavaFileWriter(OutputStream os) {
this.out = new PrintWriter(os);
}
public void write(SpecFile spec) throws IOException {
reset();
translate(spec, spec);
}
private void translate(SpecFile spec, SpecFile root) throws IOException {
PrintWriter saved = out;
if (root == spec) {
buildTerms(root);
if (!spec.pkg.equals("")) {
myOut("package " + spec.pkg + ";");
myOut("");
}
writeImports();
myOut("public final class " + spec.name + " {");
}
for (Decl d : spec.declarations) {
if (d instanceof IncludeDecl) {
IncludeDecl id = (IncludeDecl) d;
SpecFile file = id.file;
translate(file, root);
} else if (d instanceof TermDecl) {
translate((TermDecl) d);
} else if (d instanceof RewriteDecl) {
translate((RewriteDecl) d, root);
}
}
if (root == spec) {
writeSchema(spec);
writeTypeTests();
writePatterns(spec);
writeRuleArrays(spec);
writeMainMethod();
}
if (root == spec) {
myOut("}");
out.close();
}
out = saved;
}
public void buildTerms(SpecFile spec) {
for (SpecFile.Decl d : spec.declarations) {
if (d instanceof SpecFile.IncludeDecl) {
SpecFile.IncludeDecl id = (SpecFile.IncludeDecl) d;
buildTerms(id.file);
} else if (d instanceof SpecFile.TermDecl) {
SpecFile.TermDecl td = (SpecFile.TermDecl) d;
terms.put(td.type.name(), td.type);
}
}
}
/**
* Reset all global information before proceeding to write out another file.
*/
protected void reset() {
termCounter = 0;
reductionCounter = 0;
inferenceCounter = 0;
}
protected void writeImports() {
myOut("import java.io.*;");
myOut("import java.util.*;");
myOut("import java.math.BigInteger;");
myOut("import wyautl.util.BigRational;");
myOut("import wyautl.io.*;");
myOut("import wyautl.core.*;");
myOut("import wyautl.rw.*;");
myOut("import wyrl.core.*;");
myOut("import wyrl.util.Runtime;");
myOut("import wyrl.util.AbstractRewriteRule;");
myOut("import wyrl.util.Pair;");
myOut();
}
public void translate(TermDecl decl) {
myOut(1, "// term " + decl.type);
String name = decl.type.name();
myOut(1, "public final static int K_" + name + " = " + termCounter++
+ ";");
if (decl.type.element() == null) {
myOut(1, "public final static Automaton.Term " + name
+ " = new Automaton.Term(K_" + name + ");");
} else {
Type.Ref data = decl.type.element();
Type element = data.element();
if (element instanceof Type.Collection) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, int... r0) {");
if (element instanceof Type.Set) {
myOut(2, "int r1 = automaton.add(new Automaton.Set(r0));");
} else if (element instanceof Type.Bag) {
myOut(2, "int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2, "int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, List<Integer> r0) {");
if (element instanceof Type.Set) {
myOut(2, "int r1 = automaton.add(new Automaton.Set(r0));");
} else if (element instanceof Type.Bag) {
myOut(2, "int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2, "int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else if (element instanceof Type.Int) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, long r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, BigInteger r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else if (element instanceof Type.Real) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, long r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Real(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
myOut(1, "public final static int " + name
+ "(Automaton automaton, BigRational r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Real(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else if (element instanceof Type.Strung) {
// add two helpers
myOut(1, "public final static int " + name
+ "(Automaton automaton, String r0) {");
myOut(2, "int r1 = automaton.add(new Automaton.Strung(r0));");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r1));");
myOut(1, "}");
} else {
myOut(1, "public final static int " + name
+ "(Automaton automaton, " + type2JavaType(data)
+ " r0) {");
myOut(2, "return automaton.add(new Automaton.Term(K_" + name
+ ", r0));");
myOut(1, "}");
}
}
myOut();
}
private int termCounter = 0;
private int reductionCounter = 0;
private int inferenceCounter = 0;
public void translate(RewriteDecl decl, SpecFile file) {
register(decl.pattern);
boolean isReduction = decl instanceof ReduceDecl;
Type param = decl.pattern.attribute(Attribute.Type.class).type;
myOut(1, "// " + decl.pattern);
if (isReduction) {
myOut(1, "private final static class Reduction_" + reductionCounter
+ " extends AbstractRewriteRule implements ReductionRule {");
} else {
myOut(1, "private final static class Inference_" + inferenceCounter
+ " extends AbstractRewriteRule implements InferenceRule {");
}
// Constructor
myOut();
if (isReduction) {
myOut(2, "public Reduction_" + reductionCounter++
+ "(Pattern pattern) { super(pattern,SCHEMA); }");
} else {
myOut(2, "public Inference_" + inferenceCounter++
+ "(Pattern pattern) { super(pattern,SCHEMA); }");
}
// Probe
myOut();
myOut(2,
"public final void probe(Automaton automaton, int root, List<Activation> activations) {");
Environment environment = new Environment();
int thus = environment.allocate(param, "this");
myOut(3, "int r" + thus + " = root;");
int level = translatePatternMatch(3, decl.pattern, null, thus,
environment);
// Add the appropriate activation
indent(level);
out.print("int[] state = {");
for (int i = 0; i != environment.size(); ++i) {
Pair<Type, String> t = environment.get(i);
if (i != 0) {
out.print(", ");
}
if (t.first() == Type.T_VOID()) {
// In this case, we have allocated a temporary variable which
// should not be loaded into the activation state (because it
// will be out of scope).
out.print("0");
} else {
out.print("r" + i);
}
}
out.println("};");
myOut(level, "activations.add(new Activation(this,null,state));");
// close the pattern match
while (level > 2) {
myOut(--level, "}");
}
// Apply
myOut();
myOut(2,
"public final boolean apply(Automaton automaton, Object _state) {");
myOut(3, "int[] state = (int[]) _state;");
// first, unpack the state
myOut(3, "int thus = state[0];");
environment = new Environment();
thus = environment.allocate(param, "this");
translateStateUnpack(3, decl.pattern, thus, environment);
// second, translate the individual rules
for (RuleDecl rd : decl.rules) {
translate(3, rd, isReduction, environment, file);
}
myOut(3, "return false;");
myOut(2, "}");
myOut(1, "}"); // end class
}
/**
* Translate the test to see whether a pattern is accepted or not. A key
* requirement of this translation procedure is that it does not allocate
* *any* memory during the process.
*
* @param pattern
* The pattern being translated
* @param freeRegister
* The next available free register.
* @return The next available free register after this translation.
*/
protected int translatePatternMatch(int level, Pattern pattern,
Type declared, int source, Environment environment) {
if (pattern instanceof Pattern.Leaf) {
return translatePatternMatch(level, (Pattern.Leaf) pattern,
stripNominalsAndRefs(declared), source, environment);
} else if (pattern instanceof Pattern.Term) {
return translatePatternMatch(level, (Pattern.Term) pattern,
stripNominalsAndRefs(declared), source, environment);
} else if (pattern instanceof Pattern.BagOrSet) {
// I think the cast from declared to Type.Collection is guaranteed
// to be
// safe since we can't have e.g. a union of [int]|{int}
return translatePatternMatch(level, (Pattern.BagOrSet) pattern,
(Type.Collection) stripNominalsAndRefs(declared), source,
environment);
} else {
// I think the cast from declared to Type.List is guaranteed to be
// safe since we can't have e.g. a union of [int]|{int}
return translatePatternMatch(level, (Pattern.List) pattern,
(Type.List) stripNominalsAndRefs(declared), source, environment);
}
}
public int translatePatternMatch(int level, Pattern.Leaf pattern,
Type declared, int source, Environment environment) {
Type element = pattern.type().element();
if (element == Type.T_ANY() || element.isSubtype(declared)) {
// In this very special case, we don't need to do anything since
// we're guarantted to have a match based on the context.
System.err.println("SKIPPING LEAF");
return level;
} else {
int typeIndex = register(pattern.type);
myOut(level++, "if(Runtime.accepts(type" + typeIndex
+ ",automaton,automaton.get(r" + source + "), SCHEMA)) {");
return level;
}
}
public int translatePatternMatch(int level, Pattern.Term pattern,
Type declared, int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
// First, determine what we know about this term.
Type.Ref element = null;
if (declared instanceof Type.Term) {
// In this case, we are guaranteed to have a term at this point
// (and, in fact, it must match this pattern otherwise, we'd have a
// type error).
Type.Term tt = (Type.Term) declared;
element = tt.element();
} else {
// In this case, don't know much about the term we are matching.
// Furthermore, we need to check whether we have the right
// term.
myOut(level++, "if(s" + source + ".kind == K_" + pattern.name
+ ") {");
Type.Term concrete = terms.get(pattern.name);
element = concrete.element();
}
// Second, recursively check whether the data element matches
if (pattern.data != null) {
myOut(level, "Automaton.Term t" + source + " = (Automaton.Term) s"
+ source + ";");
int target = environment.allocate(Type.T_ANY(), pattern.variable);
myOut(level, "int r" + target + " = t" + source + ".contents;");
return translatePatternMatch(level, pattern.data,
element.element(), target, environment);
} else {
return level;
}
}
public int translatePatternMatch(int level, Pattern.List pattern,
Type.List declared, int source, Environment environment) {
if (pattern.unbounded) {
return translateUnboundedPatternMatch(level, pattern, declared,
source, environment);
} else {
return translateBoundedPatternMatch(level, pattern, declared,
source, environment);
}
}
public int translateBoundedPatternMatch(int level, Pattern.List pattern,
Type.List declared, int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
myOut(level, "Automaton.List l" + source + " = (Automaton.List) s"
+ source + ";");
// First, extract what we know about this list
Pair<Pattern, String>[] pattern_elements = pattern.elements;
Type[] declared_elements = declared.elements();
if (declared.unbounded()) {
// In this case, we have a fixed-size list pattern being matched
// against an unbounded list type. Therefore, we must check that the
// type being matched does indeed have the right size.
myOut(level++, "if(l" + source + ".size() == "
+ pattern_elements.length + ") {");
}
// Second, recursively check sub-elements.
// Don't visit final element, since this is the unbounded match.
for (int i = 0, j = 0; i != pattern_elements.length; ++i) {
Pair<Pattern, String> p = pattern_elements[i];
int element = environment.allocate(Type.T_ANY());
myOut(level, "int r" + element + " = l" + source + ".get(" + i
+ ");");
level = translatePatternMatch(level, p.first(), declared_elements[j],
element, environment);
// Increment j upto (but not past) the final declared element.
j = Math.min(j + 1, declared_elements.length - 1);
}
// Done.
return level;
}
public int translateUnboundedPatternMatch(int level, Pattern.List pattern,
Type.List declared, int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
myOut(level, "Automaton.List l" + source + " = (Automaton.List) s"
+ source + ";");
// First, extract what we know about this list
Pair<Pattern, String>[] pattern_elements = pattern.elements;
Type[] declared_elements = declared.elements();
if (pattern_elements.length != declared_elements.length) {
// In this case, we have an unbounded list pattern being matched
// against an unbounded list type, but the former required more
// elements than are guaranteed by the latter; therefore, we need to
// check there are enough elements.
myOut(level++, "if(l" + source + ".size() >= "
+ (pattern_elements.length - 1) + ") {");
}
// Second, recursively check sub-elements.
// Don't visit final element, since this is the unbounded match.
for (int i = 0, j = 0; i != (pattern_elements.length-1); ++i) {
Pair<Pattern, String> p = pattern_elements[i];
int element = environment.allocate(Type.T_ANY());
myOut(level, "int r" + element + " = l" + source + ".get(" + i
+ ");");
level = translatePatternMatch(level, p.first(), declared_elements[j],
element, environment);
// Increment j upto (but not past) the final declared element.
j = Math.min(j + 1, declared_elements.length - 1);
}
// Third, check all remaining elements against the unbounded match.
int lastPatternElementIndex = pattern_elements.length-1;
Pattern lastPatternElement = pattern_elements[lastPatternElementIndex].first();
Type lastDeclaredElement = declared_elements[declared_elements.length-1];
int element = environment.allocate(Type.T_VOID());
if(!willSkip(lastPatternElement,lastDeclaredElement)) {
// Only include the loop if we really need it. In many cases, this
// is not necessary because it's just matching against what we
// already can guarantee is true.
String idx = "i" + source;
myOut(level, "boolean m" + source + " = true;");
myOut(level++, "for(int " + idx + "=" + lastPatternElementIndex
+ "; " + idx + " < l" + source + ".size(); " + idx + "++) {");
myOut(level, "int r" + element + " = l" + source + ".get("
+ idx + ");");
int myLevel = level;
level = translatePatternMatch(level, lastPatternElement,
lastDeclaredElement, element, environment);
if (myLevel != level) {
myOut(level, "continue;");
myOut(--level, "} else { m" + source + "=false; break; }");
}
while (level >= myLevel) {
myOut(--level, "}");
}
myOut(level++, "if(m" + source + ") {");
}
// done
return level;
}
public int translatePatternMatch(int level, Pattern.BagOrSet pattern,
Type.Collection declared, int source, Environment environment) {
if (pattern.unbounded) {
return translateUnboundedPatternMatch(level, pattern, declared,
source, environment);
} else {
return translateBoundedPatternMatch(level, pattern, declared,
source, environment);
}
}
public int translateBoundedPatternMatch(int level, Pattern.BagOrSet pattern,
Type.Collection declared, int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
myOut(level, "Automaton.Collection c" + source
+ " = (Automaton.Collection) s" + source + ";");
// First, extract what we know about this set or bag
Pair<Pattern, String>[] elements = pattern.elements;
Type[] declared_elements = declared.elements();
if (declared.unbounded()) {
// In this case, we have a fixed-size list pattern being matched
// against an unbounded list type. Therefore, we must check that the
// type being matched does indeed have the right size.
myOut(level++, "if(c" + source + ".size() == " + elements.length
+ ") {");
}
// Second, recursively check sub-elements.
// What we do here is construct a series of nested for-loops (one for
// each pattern element) which goes through each element of the source
// collection and attempts to match the element. In doing this, we must
// ensure that no previously matched elements are matched again.
int[] indices = new int[elements.length];
for (int i = 0, j = 0; i != elements.length; ++i) {
Pattern pat = elements[i].first();
int index = environment.allocate(Type.T_ANY());
String idx = "i" + index;
indices[i] = index;
// Construct the for-loop for this element
myOut(level++, "for(int " + idx + "=0;" + idx + "!=c" + source
+ ".size();++" + idx + ") {");
// Check that the current element from the source collection is not
// already matched. If this is the first pattern element (i.e. i ==
// 0), then we don't need to do anything since nothing could have
// been matched yet.
if (i != 0) {
indent(level);
out.print("if(");
// check against earlier indices
for (int k = 0; k < i; ++k) {
if (k != 0) {
out.print(" || ");
}
out.print(idx + " == i" + indices[k]);
}
out.println(") { continue; }");
}
myOut(level, "int r" + index + " = c" + source + ".get(" + idx
+ ");");
level = translatePatternMatch(level, pat, declared_elements[j], index, environment);
// Increment j upto (but not past) the final declared element.
j = Math.min(j + 1, declared_elements.length - 1);
}
// Done.
return level;
}
public int translateUnboundedPatternMatch(int level, Pattern.BagOrSet pattern,
Type.Collection declared, int source, Environment environment) {
myOut(level, "Automaton.State s" + source + " = automaton.get(r"
+ source + ");");
myOut(level, "Automaton.Collection c" + source
+ " = (Automaton.Collection) s" + source + ";");
// First, extract what we know about this set or bag
Pair<Pattern, String>[] pattern_elements = pattern.elements;
Type[] declared_elements = declared.elements();
if (pattern_elements.length != declared_elements.length) {
// In this case, we have an unbounded list pattern being matched
// against an unbounded list type, but the former required more
// elements than are guaranteed by the latter; therefore, we need to
// check there are enough elements.
myOut(level++, "if(c" + source + ".size() >= "
+ (pattern_elements.length - 1) + ") {");
}
// Second, recursively check sub-elements.
// What we do here is construct a series of nested for-loops (one for
// each pattern element) which goes through each element of the source
// collection and attempts to match the element. In doing this, we must
// ensure that no previously matched elements are matched again.
// Furthermore, in the case of an unbounded match (i.e. where the
// pattern has a generic match against all remaining elements), then we
// simply go through all unmatched elements making sure they match the
// required pattern.
int[] indices = new int[pattern_elements.length];
for (int i = 0, j = 0; i != pattern_elements.length - 1; ++i) {
Pattern pat = pattern_elements[i].first();
int index = environment.allocate(Type.T_ANY());
String idx = "i" + index;
indices[i] = index;
// Construct the for-loop for this element
myOut(level++, "for(int " + idx + "=0;" + idx + "!=c" + source
+ ".size();++" + idx + ") {");
// Check that the current element from the source collection is not
// already matched. If this is the first pattern element (i.e. i ==
// 0), then we don't need to do anything since nothing could have
// been matched yet.
if (i != 0) {
indent(level);
out.print("if(");
// check against earlier indices
for (int k = 0; k < i; ++k) {
if (k != 0) {
out.print(" || ");
}
out.print(idx + " == i" + indices[k]);
}
out.println(") { continue; }");
}
myOut(level, "int r" + index + " = c" + source + ".get(" + idx
+ ");");
level = translatePatternMatch(level, pat, declared_elements[j], index, environment);
// Increment j upto (but not past) the final declared element.
j = Math.min(j + 1, declared_elements.length - 1);
}
// Third, check all remaining elements against the unbounded match.
int lastPatternElementIndex = pattern_elements.length-1;
Pattern lastPatternElement = pattern_elements[lastPatternElementIndex].first();
Type lastDeclaredElement = declared_elements[declared_elements.length-1];
int index = environment.allocate(Type.T_VOID());
if(!willSkip(lastPatternElement,lastDeclaredElement)) {
// Only include the loop if we really need it. In many cases, this
// is not necessary because it's just matching against what we
// already can guarantee is true.
String idx = "i" + index;
myOut(level, "boolean m" + source + "_" + lastPatternElementIndex + " = true;");
// Construct the for-loop for this element
myOut(level++, "for(int " + idx + "=0;" + idx + "!=c" + source
+ ".size();++" + idx + ") {");
// Check that the current element from the source collection is not
// already matched. If this is the first pattern element (i.e. i ==
// 0), then we don't need to do anything since nothing could have
// been matched yet.
if (lastPatternElementIndex != 0) {
indent(level);
out.print("if(");
// check against earlier indices
for (int j = 0; j < lastPatternElementIndex; ++j) {
if (j != 0) {
out.print(" || ");
}
out.print(idx + " == i" + indices[j]);
}
out.println(") { continue; }");
}
myOut(level, "int r" + index + " = c" + source + ".get(" + idx
+ ");");
int myLevel = level;
level = translatePatternMatch(level, lastPatternElement,
lastDeclaredElement, index, environment);
// In the case that pattern is unbounded, we match all non-matched
// items against the last pattern element. This time, we construct a
// loop which sets a flag if it finds one that doesn't match and
// exits early.
if (myLevel != level) {
myOut(level, "continue;");
myOut(--level, "} else { m" + source + "_"
+ lastPatternElementIndex + "=false; break; }");
}
while (level >= myLevel) {
myOut(--level, "}");
}
myOut(level++, "if(m" + source + "_" + lastPatternElementIndex + ") {");
}
// Done.
return level;
}
/**
* The purpose of this method is to determine whether or not the given
* pattern actually needs to be matched in any way.
*
* @param pattern
* @param declared
* @return
*/
protected boolean willSkip(Pattern pattern, Type declared) {
if (pattern instanceof Pattern.Leaf) {
Pattern.Leaf leaf = (Pattern.Leaf) pattern;
Type element = leaf.type().element();
declared = stripNominalsAndRefs(declared);
if (element == Type.T_ANY() || element.isSubtype(declared)) {
// In this very special case, we don't need to do anything since
// we're guarantted to have a match based on the context.
System.err.println("SKIPPING LOOP");
return true;
}
}
return false;
}
/**
* Here, we simply read out all of the registers from the state. We also
* assign named variables so they can be used subsequently.
*
* @param level
* @param pattern
* @param environment
*/
protected void translateStateUnpack(int level, Pattern pattern, int source,
Environment environment) {
if (pattern instanceof Pattern.Leaf) {
translateStateUnpack(level, (Pattern.Leaf) pattern, source,
environment);
} else if (pattern instanceof Pattern.Term) {
translateStateUnpack(level, (Pattern.Term) pattern, source,
environment);
} else if (pattern instanceof Pattern.BagOrSet) {
translateStateUnpack(level, (Pattern.BagOrSet) pattern, source,
environment);
} else {
translateStateUnpack(level, (Pattern.List) pattern, source,
environment);
}
}
protected void translateStateUnpack(int level, Pattern.Leaf pattern,
int source, Environment environment) {
// Don't need to do anything!!
}
protected void translateStateUnpack(int level, Pattern.Term pattern,
int source, Environment environment) {
if (pattern.data != null) {
int target = environment.allocate(Type.T_ANY(), pattern.variable);
if (pattern.variable != null) {
myOut(level, "int r" + target + " = state[" + target + "];");
}
translateStateUnpack(level, pattern.data, target, environment);
}
}
protected void translateStateUnpack(int level, Pattern.BagOrSet pattern,
int source, Environment environment) {
Pair<Pattern, String>[] elements = pattern.elements;
int[] indices = new int[elements.length];
for (int i = 0; i != elements.length; ++i) {
Pair<Pattern, String> p = elements[i];
String p_name = p.second();
if (pattern.unbounded && (i + 1) == elements.length) {
int index = environment.allocate(Type.T_VOID(), p_name);
if (p_name != null) {
String src = "s" + source;
myOut(level, "Automaton.Collection " + src
+ " = (Automaton.Collection) automaton.get(state["
+ source + "]);");
String array = src + "children";
myOut(level, "int[] " + array + " = new int[" + src
+ ".size() - " + i + "];");
String idx = "s" + source + "i";
String jdx = "s" + source + "j";
String tmp = "s" + source + "t";
myOut(level, "for(int " + idx + "=0, " + jdx + "=0; " + idx
+ " != " + src + ".size();++" + idx + ") {");
myOut(level + 1, "int " + tmp + " = " + src + ".get(" + idx
+ ");");
if (i != 0) {
indent(level + 1);
out.print("if(");
for (int j = 0; j < i; ++j) {
if (j != 0) {
out.print(" || ");
}
out.print(tmp + " == state[" + indices[j] + "]");
}
out.println(") { continue; }");
}
myOut(level + 1, array + "[" + jdx + "++] = " + tmp + ";");
myOut(level, "}");
if (pattern instanceof Pattern.Set) {
myOut(level, "Automaton.Set r" + index
+ " = new Automaton.Set(" + array + ");");
} else {
myOut(level, "Automaton.Bag r" + index
+ " = new Automaton.Bag(" + array + ");");
}
}
// NOTE: calling translate unpack here is strictly unnecessary
// because we cannot map an unbounded pattern to a single
// variable name.
} else {
int target = environment.allocate(Type.T_ANY(), p_name);
indices[i] = target;
if (p_name != null) {
myOut(level, "int r" + target + " = state[" + target + "];");
}
translateStateUnpack(level, p.first(), target, environment);
}
}
}
protected void translateStateUnpack(int level, Pattern.List pattern,
int source, Environment environment) {
Pair<Pattern, String>[] elements = pattern.elements;
for (int i = 0; i != elements.length; ++i) {
Pair<Pattern, String> p = elements[i];
String p_name = p.second();
if (pattern.unbounded && (i + 1) == elements.length) {
int target = environment.allocate(Type.T_VOID(), p_name);
if (p_name != null) {
myOut(level, "Automaton.List r" + target
+ " = ((Automaton.List) automaton.get(state["
+ source + "])).sublist(" + i + ");");
}
// NOTE: calling translate unpack here is strictly unnecessary
// because we cannot map an unbounded pattern to a single
// variable name.
} else {
int target = environment.allocate(Type.T_ANY(), p_name);
if (p_name != null) {
myOut(level, "int r" + target + " = state[" + target + "];");
}
translateStateUnpack(level, p.first(), target, environment);
}
}
}
public void register(Pattern p) {
if (p instanceof Pattern.Leaf) {
Pattern.Leaf pl = (Pattern.Leaf) p;
int typeIndex = register(pl.type);
} else if (p instanceof Pattern.Term) {
Pattern.Term pt = (Pattern.Term) p;
if (pt.data != null) {
register(pt.data);
}
} else if (p instanceof Pattern.Collection) {
Pattern.Collection pc = (Pattern.Collection) p;
for (Pair<Pattern, String> e : pc.elements) {
register(e.first());
}
}
}
public void translate(int level, RuleDecl decl, boolean isReduce,
Environment environment, SpecFile file) {
// TODO: can optimise this by translating lets within the conditionals
// in the case that the conditionals don't refer to those lets. This
// will then prevent unnecessary object creation.
for (Pair<String, Expr> let : decl.lets) {
String letVar = let.first();
Expr letExpr = let.second();
int result = translate(level, letExpr, environment, file);
environment.put(result, letVar);
}
if (decl.condition != null) {
int condition = translate(level, decl.condition, environment, file);
myOut(level++, "if(r" + condition + ") {");
}
int result = translate(level, decl.result, environment, file);
result = coerceFromValue(level, decl.result, result, environment);
myOut(level, "if(thus != r" + result + ") {");
myOut(level + 1, "automaton.rewrite(thus, r" + result + ");");
myOut(level + 1, "return true;");
myOut(level, "}");
if (decl.condition != null) {
myOut(--level, "}");
}
}
public void writeSchema(SpecFile spec) {
myOut(1,
"
myOut(1, "// Schema");
myOut(1,
"
myOut();
myOut(1,
"public static final Schema SCHEMA = new Schema(new Schema.Term[]{");
boolean firstTime = true;
for (TermDecl td : extractDecls(TermDecl.class, spec)) {
if (!firstTime) {
myOut(",");
}
firstTime = false;
myOut(2, "// " + td.type.toString());
indent(2);
writeSchema(td.type);
}
myOut();
myOut(1, "});");
myOut();
}
public void writeRuleArrays(SpecFile spec) {
myOut(1,
"
myOut(1, "// rules");
myOut(1,
"
myOut();
myOut(1,
"public static final InferenceRule[] inferences = new InferenceRule[]{");
int patternCounter = 0;
int inferCounter = 0;
for (Decl d : spec.declarations) {
if (d instanceof InferDecl) {
indent(2);
if (inferCounter != 0) {
out.println(",");
}
out.print("new Inference_" + inferCounter + "(pattern"
+ patternCounter + ")");
inferCounter++;
}
if (d instanceof RewriteDecl) {
patternCounter++;
}
}
myOut();
myOut(1, "};");
myOut(1,
"public static final ReductionRule[] reductions = new ReductionRule[]{");
patternCounter = 0;
int reduceCounter = 0;
for (Decl d : spec.declarations) {
if (d instanceof ReduceDecl) {
indent(2);
if (reduceCounter != 0) {
out.println(",");
}
out.print("new Reduction_" + reduceCounter + "(pattern"
+ patternCounter + ")");
reduceCounter++;
}
if (d instanceof RewriteDecl) {
patternCounter++;
}
}
myOut();
myOut(1, "};");
myOut();
}
protected void writeTypeTests() throws IOException {
myOut(1,
"
myOut(1, "// Types");
myOut(1,
"
myOut();
for (int i = 0; i != typeRegister.size(); ++i) {
Type t = typeRegister.get(i);
JavaIdentifierOutputStream jout = new JavaIdentifierOutputStream();
BinaryOutputStream bout = new BinaryOutputStream(jout);
bout.write(t.toBytes());
bout.close();
// FIXME: strip out nominal types (and any other unneeded types).
myOut(1, "
myOut(1, "private static Type type" + i + " = Runtime.Type(\""
+ jout.toString() + "\");");
}
myOut();
}
protected void writePatterns(SpecFile spec) throws IOException {
myOut(1,
"
myOut(1, "// Patterns");
myOut(1,
"
myOut();
int counter = 0;
for (Decl d : spec.declarations) {
if (d instanceof RewriteDecl) {
RewriteDecl rd = (RewriteDecl) d;
indent(1);
out.print("private final static Pattern pattern" + counter++
+ " = ");
translate(2, rd.pattern);
myOut(";");
}
}
}
public void translate(int level, Pattern p) {
if (p instanceof Pattern.Leaf) {
Pattern.Leaf pl = (Pattern.Leaf) p;
int typeIndex = register(pl.type);
out.print("new Pattern.Leaf(type" + typeIndex + ")");
} else if (p instanceof Pattern.Term) {
Pattern.Term pt = (Pattern.Term) p;
out.print("new Pattern.Term(\"" + pt.name + "\",");
if (pt.data != null) {
myOut();
indent(level);
translate(level + 1, pt.data);
out.println(",");
indent(level);
} else {
out.print("null,");
}
if (pt.variable != null) {
out.print("\"" + pt.variable + "\")");
} else {
out.print("null)");
}
} else if (p instanceof Pattern.Collection) {
Pattern.Collection pc = (Pattern.Collection) p;
String kind;
if (p instanceof Pattern.Set) {
kind = "Set";
} else if (p instanceof Pattern.Bag) {
kind = "Bag";
} else {
kind = "List";
}
out.print("new Pattern." + kind + "(" + pc.unbounded
+ ", new Pair[]{");
for (int i = 0; i != pc.elements.length; ++i) {
Pair<Pattern, String> e = pc.elements[i];
Pattern ep = e.first();
String es = e.second();
if (i != 0) {
out.println(", ");
} else {
out.println();
}
indent(level);
out.print("new Pair(");
translate(level + 1, ep);
if (es == null) {
out.print(",null)");
} else {
out.print(", \"" + es + "\")");
}
}
out.print("})");
}
}
private void writeSchema(Type.Term tt) {
Automaton automaton = tt.automaton();
BitSet visited = new BitSet(automaton.nStates());
writeSchema(automaton.getRoot(0), automaton, visited);
}
private void writeSchema(int node, Automaton automaton, BitSet visited) {
if (node < 0) {
// bypass virtual node
} else if (visited.get(node)) {
out.print("Schema.Any");
return;
} else {
visited.set(node);
}
// you can scratch your head over why this is guaranteed ;)
Automaton.Term state = (Automaton.Term) automaton.get(node);
switch (state.kind) {
case wyrl.core.Types.K_Void:
out.print("Schema.Void");
break;
case wyrl.core.Types.K_Any:
out.print("Schema.Any");
break;
case wyrl.core.Types.K_Bool:
out.print("Schema.Bool");
break;
case wyrl.core.Types.K_Int:
out.print("Schema.Int");
break;
case wyrl.core.Types.K_Real:
out.print("Schema.Real");
break;
case wyrl.core.Types.K_String:
out.print("Schema.String");
break;
case wyrl.core.Types.K_Not:
out.print("Schema.Not(");
writeSchema(state.contents, automaton, visited);
out.print(")");
break;
case wyrl.core.Types.K_Ref:
writeSchema(state.contents, automaton, visited);
break;
case wyrl.core.Types.K_Meta:
out.print("Schema.Meta(");
writeSchema(state.contents, automaton, visited);
out.print(")");
break;
case wyrl.core.Types.K_Nominal: {
// bypass the nominal marker
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
writeSchema(list.get(1), automaton, visited);
break;
}
case wyrl.core.Types.K_Or: {
out.print("Schema.Or(");
Automaton.Set set = (Automaton.Set) automaton.get(state.contents);
for (int i = 0; i != set.size(); ++i) {
if (i != 0) {
out.print(", ");
}
writeSchema(set.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Set: {
out.print("Schema.Set(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.Bag set = (Automaton.Bag) automaton.get(list.get(1));
for (int i = 0; i != set.size(); ++i) {
out.print(",");
writeSchema(set.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Bag: {
out.print("Schema.Bag(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.Bag bag = (Automaton.Bag) automaton.get(list.get(1));
for (int i = 0; i != bag.size(); ++i) {
out.print(",");
writeSchema(bag.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_List: {
out.print("Schema.List(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
// FIXME: need to deref unbounded bool here as well
out.print("true");
Automaton.List list2 = (Automaton.List) automaton.get(list.get(1));
for (int i = 0; i != list2.size(); ++i) {
out.print(",");
writeSchema(list2.get(i), automaton, visited);
}
out.print(")");
break;
}
case wyrl.core.Types.K_Term: {
out.print("Schema.Term(");
Automaton.List list = (Automaton.List) automaton
.get(state.contents);
Automaton.Strung str = (Automaton.Strung) automaton
.get(list.get(0));
out.print("\"" + str.value + "\"");
if (list.size() > 1) {
out.print(",");
writeSchema(list.get(1), automaton, visited);
}
out.print(")");
break;
}
default:
throw new RuntimeException("Unknown kind encountered: "
+ state.kind);
}
}
private <T extends Decl> ArrayList<T> extractDecls(Class<T> kind,
SpecFile spec) {
ArrayList r = new ArrayList();
extractDecls(kind, spec, r);
return r;
}
private <T extends Decl> void extractDecls(Class<T> kind, SpecFile spec,
ArrayList<T> decls) {
for (Decl d : spec.declarations) {
if (kind.isInstance(d)) {
decls.add((T) d);
} else if (d instanceof IncludeDecl) {
IncludeDecl id = (IncludeDecl) d;
extractDecls(kind, id.file, decls);
}
}
}
public int translate(int level, Expr code, Environment environment,
SpecFile file) {
if (code instanceof Expr.Constant) {
return translate(level, (Expr.Constant) code, environment, file);
} else if (code instanceof Expr.UnOp) {
return translate(level, (Expr.UnOp) code, environment, file);
} else if (code instanceof Expr.BinOp) {
return translate(level, (Expr.BinOp) code, environment, file);
} else if (code instanceof Expr.NaryOp) {
return translate(level, (Expr.NaryOp) code, environment, file);
} else if (code instanceof Expr.Constructor) {
return translate(level, (Expr.Constructor) code, environment, file);
} else if (code instanceof Expr.ListAccess) {
return translate(level, (Expr.ListAccess) code, environment, file);
} else if (code instanceof Expr.ListUpdate) {
return translate(level, (Expr.ListUpdate) code, environment, file);
} else if (code instanceof Expr.Variable) {
return translate(level, (Expr.Variable) code, environment, file);
} else if (code instanceof Expr.Substitute) {
return translate(level, (Expr.Substitute) code, environment, file);
} else if (code instanceof Expr.Comprehension) {
return translate(level, (Expr.Comprehension) code, environment,
file);
} else if (code instanceof Expr.TermAccess) {
return translate(level, (Expr.TermAccess) code, environment, file);
} else if (code instanceof Expr.Cast) {
return translate(level, (Expr.Cast) code, environment, file);
} else {
throw new RuntimeException("unknown expression encountered - "
+ code);
}
}
public int translate(int level, Expr.Cast code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first translate src expression, and coerce to a value
int src = translate(level, code.src, environment, file);
src = coerceFromRef(level, code.src, src, environment);
// TODO: currently we only support casting from integer to real!!
String body = "new Automaton.Real(r" + src + ".value)";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Constant code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
Object v = code.value;
String rhs;
if (v instanceof Boolean) {
rhs = v.toString();
} else if (v instanceof BigInteger) {
BigInteger bi = (BigInteger) v;
if (bi.bitLength() <= 64) {
rhs = "new Automaton.Int(" + bi.longValue() + ")";
} else {
rhs = "new Automaton.Int(\"" + bi.toString() + "\")";
}
} else if (v instanceof BigRational) {
BigRational br = (BigRational) v;
rhs = "new Automaton.Real(\"" + br.toString() + "\")";
if (br.isInteger()) {
long lv = br.longValue();
if (BigRational.valueOf(lv).equals(br)) {
// Yes, this will fit in a long value. Therefore, inline a
// long constant as this is faster.
rhs = "new Automaton.Real(" + lv + ")";
}
}
} else if (v instanceof String) {
rhs = "new Automaton.Strung(\"" + v + "\")";
} else {
throw new RuntimeException("unknown constant encountered (" + v
+ ")");
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + rhs + ";",
code.toString()));
return target;
}
public int translate(int level, Expr.UnOp code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int rhs = translate(level, code.mhs, environment, file);
rhs = coerceFromRef(level, code.mhs, rhs, environment);
String body;
switch (code.op) {
case LENGTHOF:
body = "r" + rhs + ".lengthOf()";
break;
case NUMERATOR:
body = "r" + rhs + ".numerator()";
break;
case DENOMINATOR:
body = "r" + rhs + ".denominator()";
break;
case NEG:
body = "r" + rhs + ".negate()";
break;
case NOT:
body = "!r" + rhs;
break;
default:
throw new RuntimeException("unknown unary expression encountered");
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.BinOp code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
Type lhs_t = code.lhs.attribute(Attribute.Type.class).type;
Type rhs_t = code.rhs.attribute(Attribute.Type.class).type;
int lhs = translate(level, code.lhs, environment, file);
String body;
if (code.op == Expr.BOp.IS && code.rhs instanceof Expr.Constant) {
// special case for runtime type tests
Expr.Constant c = (Expr.Constant) code.rhs;
Type test = (Type) c.value;
int typeIndex = register(test);
body = "Runtime.accepts(type" + typeIndex + ", automaton, r" + lhs
+ ", SCHEMA)";
} else if (code.op == Expr.BOp.AND) {
// special case to ensure short-circuiting of AND.
lhs = coerceFromRef(level, code.lhs, lhs, environment);
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + false
+ ";", code.toString()));
myOut(level++, "if(r" + lhs + ") {");
int rhs = translate(level, code.rhs, environment, file);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
myOut(level, "r" + target + " = r" + rhs + ";");
myOut(--level, "}");
return target;
} else {
int rhs = translate(level, code.rhs, environment, file);
// First, convert operands into values (where appropriate)
switch (code.op) {
case EQ:
case NEQ:
if (lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
// OK to do nothing here...
} else {
lhs = coerceFromRef(level, code.lhs, lhs, environment);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
}
break;
case APPEND:
// append is a tricky case as we have support the non-symmetic
// cases
// for adding a single element to the end or the beginning of a
// list.
lhs_t = Type.unbox(lhs_t);
rhs_t = Type.unbox(rhs_t);
if (lhs_t instanceof Type.Collection) {
lhs = coerceFromRef(level, code.lhs, lhs, environment);
} else {
lhs = coerceFromValue(level, code.lhs, lhs, environment);
}
if (rhs_t instanceof Type.Collection) {
rhs = coerceFromRef(level, code.rhs, rhs, environment);
} else {
rhs = coerceFromValue(level, code.rhs, rhs, environment);
}
break;
case IN:
lhs = coerceFromValue(level, code.lhs, lhs, environment);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
break;
default:
lhs = coerceFromRef(level, code.lhs, lhs, environment);
rhs = coerceFromRef(level, code.rhs, rhs, environment);
}
// Second, construct the body of the computation
switch (code.op) {
case ADD:
body = "r" + lhs + ".add(r" + rhs + ")";
break;
case SUB:
body = "r" + lhs + ".subtract(r" + rhs + ")";
break;
case MUL:
body = "r" + lhs + ".multiply(r" + rhs + ")";
break;
case DIV:
body = "r" + lhs + ".divide(r" + rhs + ")";
break;
case OR:
body = "r" + lhs + " || r" + rhs;
break;
case EQ:
if (lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
body = "r" + lhs + " == r" + rhs;
} else {
body = "r" + lhs + ".equals(r" + rhs + ")";
}
break;
case NEQ:
if (lhs_t instanceof Type.Ref && rhs_t instanceof Type.Ref) {
body = "r" + lhs + " != r" + rhs;
} else {
body = "!r" + lhs + ".equals(r" + rhs + ")";
}
break;
case LT:
body = "r" + lhs + ".compareTo(r" + rhs + ")<0";
break;
case LTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")<=0";
break;
case GT:
body = "r" + lhs + ".compareTo(r" + rhs + ")>0";
break;
case GTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")>=0";
break;
case APPEND:
if (lhs_t instanceof Type.Collection) {
body = "r" + lhs + ".append(r" + rhs + ")";
} else {
body = "r" + rhs + ".appendFront(r" + lhs + ")";
}
break;
case DIFFERENCE:
body = "r" + lhs + ".removeAll(r" + rhs + ")";
break;
case IN:
body = "r" + rhs + ".contains(r" + lhs + ")";
break;
case RANGE:
body = "Runtime.rangeOf(automaton,r" + lhs + ",r" + rhs + ")";
break;
default:
throw new RuntimeException(
"unknown binary operator encountered: " + code);
}
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.NaryOp code, Environment environment,
SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
String body = "new Automaton.";
if (code.op == Expr.NOp.LISTGEN) {
body += "List(";
} else if (code.op == Expr.NOp.BAGGEN) {
body += "Bag(";
} else {
body += "Set(";
}
List<Expr> arguments = code.arguments;
for (int i = 0; i != arguments.size(); ++i) {
if (i != 0) {
body += ", ";
}
Expr argument = arguments.get(i);
int reg = translate(level, argument, environment, file);
reg = coerceFromValue(level, argument, reg, environment);
body += "r" + reg;
}
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ");", code.toString()));
return target;
}
public int translate(int level, Expr.ListAccess code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int src = translate(level, code.src, environment, file);
int idx = translate(level, code.index, environment, file);
src = coerceFromRef(level, code.src, src, environment);
idx = coerceFromRef(level, code.index, idx, environment);
String body = "r" + src + ".indexOf(r" + idx + ")";
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.ListUpdate code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
int src = translate(level, code.src, environment, file);
int idx = translate(level, code.index, environment, file);
int value = translate(level, code.value, environment, file);
src = coerceFromRef(level, code.src, src, environment);
idx = coerceFromRef(level, code.index, idx, environment);
value = coerceFromValue(level, code.value, value, environment);
String body = "r" + src + ".update(r" + idx + ", r" + value + ")";
int target = environment.allocate(type);
myOut(level,
comment(type2JavaType(type) + " r" + target + " = " + body
+ ";", code.toString()));
return target;
}
public int translate(int level, Expr.Constructor code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
String body;
if (code.argument == null) {
body = code.name;
} else {
int arg = translate(level, code.argument, environment, file);
if (code.external) {
body = file.name + "$native." + code.name + "(automaton, r"
+ arg + ")";
} else {
arg = coerceFromValue(level, code.argument, arg, environment);
body = "new Automaton.Term(K_" + code.name + ", r" + arg + ")";
}
}
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Variable code,
Environment environment, SpecFile file) {
Integer operand = environment.get(code.var);
if (operand != null) {
return operand;
} else {
Type type = code.attribute(Attribute.Type.class).type;
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + code.var
+ ";");
return target;
}
}
public int translate(int level, Expr.Substitute code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first, translate all subexpressions and make sure they are
// references.
int src = translate(level, code.src, environment, file);
src = coerceFromValue(level, code.src, src, environment);
int original = translate(level, code.original, environment, file);
original = coerceFromValue(level, code.original, original, environment);
int replacement = translate(level, code.replacement, environment, file);
replacement = coerceFromValue(level, code.replacement, replacement,
environment);
// second, put in place the substitution
String body = "automaton.substitute(r" + src + ", r" + original + ", r"
+ replacement + ")";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.TermAccess code,
Environment environment, SpecFile file) {
Type type = code.attribute(Attribute.Type.class).type;
// first translate src expression, and coerce to a value
int src = translate(level, code.src, environment, file);
src = coerceFromRef(level, code.src, src, environment);
String body = "r" + src + ".contents";
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Comprehension expr,
Environment environment, SpecFile file) {
Type type = expr.attribute(Attribute.Type.class).type;
int target = environment.allocate(type);
// first, translate all source expressions
int[] sources = new int[expr.sources.size()];
for (int i = 0; i != sources.length; ++i) {
Pair<Expr.Variable, Expr> p = expr.sources.get(i);
int operand = translate(level, p.second(), environment, file);
operand = coerceFromRef(level, p.second(), operand, environment);
sources[i] = operand;
}
// TODO: initialise result set
myOut(level, "Automaton.List t" + target + " = new Automaton.List();");
int startLevel = level;
// initialise result register if needed
switch (expr.cop) {
case NONE:
myOut(level, type2JavaType(type) + " r" + target + " = true;");
myOut(level, "outer:");
break;
case SOME:
myOut(level, type2JavaType(type) + " r" + target + " = false;");
myOut(level, "outer:");
break;
}
// second, generate all the for loops
for (int i = 0; i != sources.length; ++i) {
Pair<Expr.Variable, Expr> p = expr.sources.get(i);
Expr.Variable variable = p.first();
Expr source = p.second();
Type.Collection sourceType = (Type.Collection) source
.attribute(Attribute.Type.class).type;
Type elementType = variable.attribute(Attribute.Type.class).type;
int index = environment.allocate(elementType, variable.var);
myOut(level++, "for(int i" + index + "=0;i" + index + "<r"
+ sources[i] + ".size();i" + index + "++) {");
String rhs = "r" + sources[i] + ".get(i" + index + ")";
// FIXME: need a more general test for a reference type
if (!(elementType instanceof Type.Ref)) {
rhs = "automaton.get(" + rhs + ");";
}
myOut(level, type2JavaType(elementType) + " r" + index + " = ("
+ type2JavaType(elementType) + ") " + rhs + ";");
}
if (expr.condition != null) {
int condition = translate(level, expr.condition, environment, file);
myOut(level++, "if(r" + condition + ") {");
}
switch (expr.cop) {
case SETCOMP:
case BAGCOMP:
case LISTCOMP:
int result = translate(level, expr.value, environment, file);
result = coerceFromValue(level, expr.value, result, environment);
myOut(level, "t" + target + ".add(r" + result + ");");
break;
case NONE:
myOut(level, "r" + target + " = false;");
myOut(level, "break outer;");
break;
case SOME:
myOut(level, "r" + target + " = true;");
myOut(level, "break outer;");
break;
}
// finally, terminate all the for loops
while (level > startLevel) {
myOut(--level, "}");
}
switch (expr.cop) {
case SETCOMP:
myOut(level, type2JavaType(type) + " r" + target
+ " = new Automaton.Set(t" + target + ".toArray());");
break;
case BAGCOMP:
myOut(level, type2JavaType(type) + " r" + target
+ " = new Automaton.Bag(t" + target + ".toArray());");
break;
case LISTCOMP:
myOut(level, type2JavaType(type) + " r" + target + " = t" + target
+ ";");
break;
}
return target;
}
protected void writeMainMethod() {
myOut();
myOut(1,
"
myOut(1, "// Main Method");
myOut(1,
"
myOut();
myOut(1, "public static void main(String[] args) throws IOException {");
myOut(2, "try {");
myOut(3,
"PrettyAutomataReader reader = new PrettyAutomataReader(System.in,SCHEMA);");
myOut(3,
"PrettyAutomataWriter writer = new PrettyAutomataWriter(System.out,SCHEMA);");
myOut(3, "Automaton automaton = reader.read();");
myOut(3, "System.out.print(\"PARSED: \");");
myOut(3, "print(automaton);");
myOut(3, "new SimpleRewriter(inferences,reductions).apply(automaton);");
myOut(3, "System.out.print(\"REWROTE: \");");
myOut(3, "print(automaton);");
// myOut(3,
// "System.out.println(\"(Reductions=\" + numReductions + \", Inferences=\" + numInferences + \", Misinferences=\" + numMisinferences + \", steps = \" + numSteps + \")\");");
myOut(2, "} catch(PrettyAutomataReader.SyntaxError ex) {");
myOut(3, "System.err.println(ex.getMessage());");
myOut(2, "}");
myOut(1, "}");
myOut(1, "");
myOut(1, "static void print(Automaton automaton) {");
myOut(2, "try {");
myOut(3,
"PrettyAutomataWriter writer = new PrettyAutomataWriter(System.out,SCHEMA);");
myOut(3, "writer.write(automaton);");
myOut(3, "writer.flush();");
myOut(3, "System.out.println();");
myOut(2,
"} catch(IOException e) { System.err.println(\"I/O error printing automaton\"); }");
myOut(1, "}");
}
public String comment(String code, String comment) {
int nspaces = 30 - code.length();
String r = "";
for (int i = 0; i < nspaces; ++i) {
r += " ";
}
return code + r + " // " + comment;
}
/**
* Convert a Wyrl type into its equivalent Java type.
*
* @param type
* @return
*/
public String type2JavaType(Type type) {
return type2JavaType(type, true);
}
/**
* Convert a Wyrl type into its equivalent Java type. The user specifies
* whether primitive types are allowed or not. If not then, for example,
* <code>Type.Int</code> becomes <code>int</code>; otherwise, it becomes
* <code>Integer</code>.
*
* @param type
* @return
*/
public String type2JavaType(Type type, boolean primitives) {
if (type instanceof Type.Any) {
return "Object";
} else if (type instanceof Type.Int) {
return "Automaton.Int";
} else if (type instanceof Type.Real) {
return "Automaton.Real";
} else if (type instanceof Type.Bool) {
return "boolean";
} else if (type instanceof Type.Strung) {
return "Automaton.Strung";
} else if (type instanceof Type.Term) {
return "Automaton.Term";
} else if (type instanceof Type.Ref) {
if (primitives) {
return "int";
} else {
return "Integer";
}
} else if (type instanceof Type.Nominal) {
Type.Nominal nom = (Type.Nominal) type;
return type2JavaType(nom.element(), primitives);
} else if (type instanceof Type.Or) {
return "Object";
} else if (type instanceof Type.List) {
return "Automaton.List";
} else if (type instanceof Type.Bag) {
return "Automaton.Bag";
} else if (type instanceof Type.Set) {
return "Automaton.Set";
}
throw new RuntimeException("unknown type encountered: " + type);
}
public int coerceFromValue(int level, Expr expr, int register,
Environment environment) {
Type type = expr.attribute(Attribute.Type.class).type;
if (type instanceof Type.Ref) {
return register;
} else {
Type.Ref refType = Type.T_REF(type);
int result = environment.allocate(refType);
String src = "r" + register;
if (refType.element() instanceof Type.Bool) {
// special thing needed for bools
src = src + " ? Automaton.TRUE : Automaton.FALSE";
}
myOut(level, type2JavaType(refType) + " r" + result
+ " = automaton.add(" + src + ");");
return result;
}
}
public int coerceFromRef(int level, SyntacticElement elem, int register,
Environment environment) {
Type type = elem.attribute(Attribute.Type.class).type;
if (type instanceof Type.Ref) {
Type.Ref refType = (Type.Ref) type;
Type element = refType.element();
int result = environment.allocate(element);
String cast = type2JavaType(element);
String body = "automaton.get(r" + register + ")";
// special case needed for booleans
if (element instanceof Type.Bool) {
body = "((Automaton.Bool)" + body + ").value";
} else {
body = "(" + cast + ") " + body;
}
myOut(level, cast + " r" + result + " = " + body + ";");
return result;
} else {
return register;
}
}
protected Type stripNominalsAndRefs(Type t) {
if (t instanceof Type.Nominal) {
Type.Nominal n = (Type.Nominal) t;
return stripNominalsAndRefs(n.element());
} else if (t instanceof Type.Ref) {
Type.Ref n = (Type.Ref) t;
return stripNominalsAndRefs(n.element());
} else {
return t;
}
}
protected void myOut() {
myOut(0, "");
}
protected void myOut(int level) {
myOut(level, "");
}
protected void myOut(String line) {
myOut(0, line);
}
protected void myOut(int level, String line) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
out.println(line);
}
protected void indent(int level) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
}
private HashMap<Type, Integer> registeredTypes = new HashMap<Type, Integer>();
private ArrayList<Type> typeRegister = new ArrayList<Type>();
private int register(Type t) {
// t.automaton().minimise();
// t.automaton().canonicalise();
// Types.reduce(t.automaton());
Integer i = registeredTypes.get(t);
if (i == null) {
int r = typeRegister.size();
registeredTypes.put(t, r);
typeRegister.add(t);
return r;
} else {
return i;
}
}
private static final class Environment {
private final HashMap<String, Integer> var2idx;
private final ArrayList<Pair<Type, String>> idx2var;
public Environment() {
this.var2idx = new HashMap<String, Integer>();
this.idx2var = new ArrayList<Pair<Type, String>>();
}
private Environment(HashMap<String, Integer> var2idx,
ArrayList<Pair<Type, String>> idx2var) {
this.var2idx = var2idx;
this.idx2var = idx2var;
}
public int size() {
return idx2var.size();
}
public int allocate(Type t) {
int idx = idx2var.size();
idx2var.add(new Pair<Type, String>(t, null));
return idx;
}
public int allocate(Type t, String v) {
int idx = idx2var.size();
idx2var.add(new Pair<Type, String>(t, v));
var2idx.put(v, idx);
return idx;
}
public Integer get(String v) {
return var2idx.get(v);
}
public Pair<Type, String> get(int idx) {
return idx2var.get(idx);
}
public void put(int idx, String v) {
var2idx.put(v, idx);
idx2var.set(idx,
new Pair<Type, String>(idx2var.get(idx).first(), v));
}
public Environment clone() {
return new Environment((HashMap) var2idx.clone(),
(ArrayList) idx2var.clone());
}
public String toString() {
return var2idx.toString();
}
}
} |
package acmi.l2.clientmod.decompiler;
import acmi.l2.clientmod.io.UnrealPackageReadOnly;
import acmi.l2.clientmod.unreal.core.*;
import acmi.l2.clientmod.unreal.core.Class;
import acmi.l2.clientmod.unreal.core.Enum;
import acmi.l2.clientmod.unreal.core.Function;
import acmi.l2.clientmod.unreal.core.Object;
import acmi.l2.clientmod.unreal.objectfactory.ObjectFactory;
import javafx.util.Pair;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static acmi.l2.clientmod.decompiler.Util.*;
public class Decompiler {
static Object instantiate(UnrealPackageReadOnly.ExportEntry entry, ObjectFactory objectFactory) {
String objClass = entry.getObjectClass() == null ? "Core.Class" : entry.getObjectClass().getObjectFullName();
if (objClass.equals("Core.Class") ||
objClass.equals("Core.State") ||
objClass.equals("Core.Function") ||
objClass.equals("Core.Struct")) {
return objectFactory.getClassLoader().getStruct(entry.getObjectFullName());
} else {
return objectFactory.apply(entry);
}
}
public static CharSequence decompile(Class clazz, ObjectFactory objectFactory, int indent) {
StringBuilder sb = new StringBuilder();
String name = clazz.getEntry().getObjectName().getName();
String superName = clazz.getEntry().getObjectSuperClass() != null ?
clazz.getEntry().getObjectSuperClass().getObjectName().getName() : null;
sb.append("class ").append(name);
if (superName != null)
sb.append(" extends ").append(superName);
//TODO flags
sb.append(";");
if (clazz.getChild() != null) {
sb.append(newLine());
sb.append(newLine(indent)).append(decompileFields(clazz, objectFactory, indent));
}
//TODO defaultproperties
return sb;
}
public static CharSequence decompileFields(Struct struct, ObjectFactory objectFactory, int indent) {
Stream.Builder<CharSequence> fields = Stream.builder();
for (Field field : (Iterable<Field>) () -> new ChildIterator(struct, objectFactory)) {
if (field instanceof Const) {
fields.add(decompileConst((Const) field, objectFactory, indent) + ";");
} else if (field instanceof Enum) {
if (!struct.getClass().equals(Struct.class))
fields.add(decompileEnum((Enum) field, objectFactory, indent) + ";");
} else if (field instanceof Property) {
if (field instanceof DelegateProperty)
continue;
fields.add(decompileProperty((Property) field, struct, objectFactory, indent) + ";");
} else if (field instanceof State) {
fields.add(decompileState((State) field, objectFactory, indent));
} else if (field instanceof Function) {
fields.add(decompileFunction((Function) field, objectFactory, indent));
} else if (field instanceof Struct) {
fields.add(decompileStruct((Struct) field, objectFactory, indent) + ";");
} else {
fields.add(field.toString());
}
}
return fields.build().collect(Collectors.joining(newLine(indent)));
}
public static CharSequence decompileConst(Const c, ObjectFactory objectFactory, int indent) {
StringBuilder sb = new StringBuilder();
sb.append("const ")
.append(c.getEntry().getObjectName().getName())
.append(" =")
.append(c.constant);
return sb;
}
public static CharSequence decompileEnum(Enum e, ObjectFactory objectFactory, int indent) {
StringBuilder sb = new StringBuilder();
sb.append("enum ").append(e.getEntry().getObjectName().getName())
.append(newLine(indent)).append("{")
.append(newLine(indent + 1)).append(e.getValues().stream().collect(Collectors.joining("," + newLine(indent + 1))))
.append(newLine(indent)).append("}");
return sb;
}
public static CharSequence decompileProperty(Property property, Struct parent, ObjectFactory objectFactory, int indent) {
StringBuilder sb = new StringBuilder();
sb.append("var");
CharSequence type = getType(property, objectFactory, true);
if (parent.getClass().equals(Struct.class)) {
if (property instanceof ByteProperty &&
((ByteProperty) property).enumType != 0) {
UnrealPackageReadOnly.Entry enumLocalEntry = ((ByteProperty) property).getEnumType();
UnrealPackageReadOnly.ExportEntry enumEntry = objectFactory.getClassLoader()
.getExportEntry(enumLocalEntry.getObjectFullName(), e -> e.getObjectClass() != null && e.getObjectClass().getObjectFullName().equalsIgnoreCase("Core.Enum"));
Enum en = (Enum) objectFactory.apply(enumEntry);
type = decompileEnum(en, objectFactory, indent);
}
//FIXME array<enum>
}
sb.append(" ").append(type).append(" ");
sb.append(property.getEntry().getObjectName().getName());
if (property.arrayDimension > 1)
sb.append("[").append(property.arrayDimension).append("]");
return sb;
}
private static final List<Pair<Predicate<Property>, java.util.function.Function<Property, String>>> MODIFIERS = Arrays.asList(
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Edit), p -> "(" + (p.getEntry().getObjectPackage().getObjectName().getName().equalsIgnoreCase(p.getCategory()) ? "" : p.getCategory()) + ")"),
new Pair<>(p -> UnrealPackageReadOnly.ObjectFlag.getFlags(p.getEntry().getObjectFlags()).contains(UnrealPackageReadOnly.ObjectFlag.Private), p -> "private"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Const), p -> "const"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Input), p -> "input"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.ExportObject), p -> "export"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.OptionalParm), p -> "optional"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.OutParm), p -> "out"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.SkipParm), p -> "skip"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.CoerceParm), p -> "coerce"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Native), p -> "native"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Transient), p -> "transient"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Config), p -> p.getPropertyFlags().contains(Property.CPF.GlobalConfig) ? null : "config"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Localized), p -> "localized"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Travel), p -> "travel"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.EditConst), p -> "editconst"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.GlobalConfig), p -> "globalconfig"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.EditInline), p -> p.getPropertyFlags().contains(Property.CPF.EditInlineUse) ? null : "editinline"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.EdFindable), p -> "edfindable"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.EditInlineUse), p -> "editinlineuse"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.Deprecated), p -> "deprecated"),
new Pair<>(p -> p.getPropertyFlags().contains(Property.CPF.EditInlineNotify), p -> "editinlinenotify")
);
public static CharSequence getType(Property property, ObjectFactory objectFactory, boolean includeModifiers) {
StringBuilder sb = new StringBuilder();
if (includeModifiers) {
MODIFIERS.stream()
.filter(p -> p.getKey().test(property))
.map(p -> p.getValue().apply(property))
.forEach(m -> sb.append(m).append(" "));
}
if (property instanceof ByteProperty) {
if (((ByteProperty) property).enumType != 0) {
UnrealPackageReadOnly.Entry enumLocalEntry = ((ByteProperty) property).getEnumType();
sb.append(enumLocalEntry.getObjectName().getName());
} else {
sb.append("byte");
}
} else if (property instanceof IntProperty) {
sb.append("int");
} else if (property instanceof BoolProperty) {
sb.append("bool");
} else if (property instanceof FloatProperty) {
sb.append("float");
} else if (property instanceof ObjectProperty) {
sb.append(((ObjectProperty) property).getObjectType().getObjectName().getName());
} else if (property instanceof NameProperty) {
sb.append("name");
} else if (property instanceof ArrayProperty) {
ArrayProperty arrayProperty = (ArrayProperty) property;
Property innerProperty = (Property) objectFactory.apply(objectFactory.getClassLoader().getExportEntry(arrayProperty.getInner().getObjectFullName(), e -> true));
sb.append("array<").append(getType(innerProperty, objectFactory, false)).append(">");
} else if (property instanceof StructProperty) {
sb.append(((StructProperty) property).getStructType().getObjectName().getName());
} else if (property instanceof StrProperty) {
sb.append("string");
}
return sb;
}
public static CharSequence decompileStruct(Struct struct, ObjectFactory objectFactory, int indent) {
StringBuilder sb = new StringBuilder();
sb.append("struct ").append(struct.getEntry().getObjectName().getName());
sb.append(newLine(indent)).append("{");
sb.append(newLine(indent + 1)).append(decompileFields(struct, objectFactory, indent + 1));
sb.append(newLine(indent)).append("}");
return sb;
}
public static CharSequence decompileFunction(Function function, ObjectFactory objectFactory, int indent) {
StringBuilder sb = new StringBuilder();
sb.append("//function_").append(function.getFriendlyName()); //TODO
return sb;
}
public static CharSequence decompileState(State state, ObjectFactory objectFactory, int indent) {
StringBuilder sb = new StringBuilder();
sb.append("state ");
sb.append(state.getEntry().getObjectName().getName());
if (state.getEntry().getObjectSuperClass() != null) {
sb.append(" extends ").append(state.getEntry().getObjectSuperClass().getObjectName().getName());
}
sb.append(newLine(indent)).append("{");
sb.append(newLine(indent + 1)).append(decompileFields(state, objectFactory, indent + 1));
sb.append(newLine(indent)).append("}");
return sb;
}
} |
package com.plugin.gcm;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.media.RingtoneManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import com.google.android.gcm.GCMBaseIntentService;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
private static String packageName = null;
private static float devicePixelRatio = 1.0f;
private static int LargeIconSize = 256;
private static int BigPictureSize = 640;
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: "+ regId);
JSONObject json;
try
{
json = new JSONObject().put("event", "registered");
json.put("regid", regId);
Log.v(TAG, "onRegistered: " + json.toString());
// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
// In this case this is the registration ID
PushPlugin.sendJavascript( json );
}
catch( JSONException e)
{
// No message to the user is sent, JSON failed
Log.e(TAG, "onRegistered: JSON exception");
}
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null)
{
// if we are in the foreground, just surface the payload, else post it to the statusbar
if (PushPlugin.isInForeground()) {
extras.putBoolean("foreground", true);
PushPlugin.sendExtras(extras);
}
else {
extras.putBoolean("foreground", false);
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
createNotification(context, extras);
}
}
}
}
public void createNotification(Context context, Bundle extras)
{
packageName = context.getPackageName();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
devicePixelRatio = metrics.density;
Log.d(TAG, "devicePixelRatio: "+ devicePixelRatio);
String appName = getAppName(this);
// which version of the push notifications are we dealing with? (for backwards compatibility)
int v = Integer.parseInt(extras.getString("v", "1"));
int notificationId = 0;
try {
Random rand = new Random();
notificationId = Integer.parseInt(extras.getString("notificationId", String.valueOf(rand.nextInt(1000))));
}
catch(NumberFormatException e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage());
}
catch(Exception e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage());
}
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
PendingIntent contentIntent = PendingIntent.getActivity(this, notificationId, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//int defaults = extras.getInt("defaults", (Notification.DEFAULT_ALL));
NotificationCompat.Builder notification =
new NotificationCompat.Builder(context)
// Set which notification properties will be inherited from system defaults.
//.setDefaults(defaults)
// Set the "ticker" text which is displayed in the status bar when the notification first arrives.
.setTicker(extras.getString("summary", extras.getString("title")))
// Set the first line of text in the platform notification template.
.setContentTitle(extras.getString("title"))
// Set the second line of text in the platform notification template.
.setContentText(
(v >= 2) ?
extras.getString("summary")
:
extras.getString("message")
)
// Set the third line of text in the platform notification template.
.setSubText(
(v >= 2) ?
null
:
extras.getString("summary")
)
// Supply a PendingIntent to be sent when the notification is clicked.
.setContentIntent(contentIntent)
// Set the large number at the right-hand side of the notification.
.setNumber(Integer.parseInt(extras.getString("badge", extras.getString("msgcnt", "0"))))
// A variant of setSmallIcon(int) that takes an additional level parameter for when the icon is a LevelListDrawable.
.setSmallIcon(getSmallIcon(extras.getString("smallIcon"), context.getApplicationInfo().icon))
// Add a large icon to the notification (and the ticker on some devices).
.setLargeIcon(
getLargeIcon(this,
(v >= 2) ?
extras.getString("avatar", "https://img.andygreen.com/image.cf?Width=" + LargeIconSize + "&Path=avatar.png")
:
extras.getString("icon")
)
)
// Vibrate constantly for the specified period of time.
.setVibrate(new long[] {
// The first value indicates the number of milliseconds to wait before turning the vibrator on.
75, // Off
// The next value indicates the number of milliseconds for which to keep the vibrator on before turning it off.
75,
// Subsequent values alternate between durations in milliseconds to turn the vibrator off or to turn the vibrator on.
100, // Off
100,
200 // Off
})
// Set the desired color for the indicator LED on the device, as well as the blink duty cycle (specified in milliseconds).
.setLights(getColor(extras.getString("led", "000000")), 500, 500)
// Make this notification automatically dismissed when the user touches it.
.setPriority(Notification.PRIORITY_DEFAULT)
.setAutoCancel(extras.getBoolean("autoCancel", true))
;
Uri sound = getSound(extras.getString("sound"));
if (sound != null) {
// Set the sound to play.
notification.setSound(sound);
}
if (Build.VERSION.SDK_INT >= 16) {
String message = (v >= 2) ? extras.getString("summary") : extras.getString("message");
String pictureUrl = (v >= 2) ? null : extras.getString("picture");
if (pictureUrl != null && pictureUrl.length() > 0) {
// Add a rich notification style to be applied at build time.
notification.setStyle(
new NotificationCompat.BigPictureStyle()
// Overrides ContentTitle in the big form of the template.
.setBigContentTitle(extras.getString("title"))
// Set the first line of text after the detail section in the big form of the template.
.setSummaryText(message)
// Override the large icon when the big notification is shown.
.bigLargeIcon(getLargeIcon(this, extras.getString("avatar", "https://img.andygreen.com/image.cf?Width=" + LargeIconSize + "&Path=avatar.png")))
// Provide the bitmap to be used as the payload for the BigPicture notification.
.bigPicture(getPicture(this, pictureUrl))
);
// remove the third line as this is confusing for BigPicture style.
notification.setSubText(null);
} else if (message != null && message.length() > 30) {
// Add a rich notification style to be applied at build time.
notification.setStyle(
new NotificationCompat.BigTextStyle()
// Overrides ContentTitle in the big form of the template.
.setBigContentTitle(extras.getString("title"))
// Provide the longer text to be displayed in the big form of the template in place of the content text.
.bigText(message)
// Set the first line of text after the detail section in the big form of the template.
.setSummaryText(
(v >= 2) ?
null
:
extras.getString("summary")
)
);
}
}
final Notification build = notification.build();
build.flags =
/*
// Use all default values (where applicable).
Notification.DEFAULT_ALL |
// Use the default notification lights.
Notification.DEFAULT_LIGHTS |
// Use the default notification sound.
Notification.DEFAULT_SOUND |
// Use the default notification vibrate.
Notification.DEFAULT_VIBRATE |
*/
// Set if you want the LED on for this notification.
Notification.FLAG_SHOW_LIGHTS |
// Notification should be canceled when it is clicked by the user.
Notification.FLAG_AUTO_CANCEL
;
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify((String) appName, notificationId, build);
}
/**
* Returns the path of the notification's sound file
*/
private static Uri getSound(String sound) {
if (sound != null) {
try {
int soundId = (Integer) RingtoneManager.class.getDeclaredField(sound).get(Integer.class);
return RingtoneManager.getDefaultUri(soundId);
} catch (Exception e) {
return Uri.parse(sound);
}
}
return null;
}
/**
* Returns the small icon's ID
*/
private static int getSmallIcon(String iconName, int iconId)
{
int resId = 0;
resId = getIconValue(packageName, iconName);
if (resId == 0) {
resId = getIconValue("android", iconName);
}
if (resId == 0) {
resId = getIconValue(packageName, "icon");
}
if (resId == 0) {
return iconId;
}
return resId;
}
/**
* Returns the icon's ID
*/
private static Bitmap getLargeIcon(Context context, String icon)
{
Bitmap bmp = null;
if (icon != null) {
if (icon.startsWith("http:
bmp = getIconFromURL(icon);
} else if (icon.startsWith("file:
bmp = getIconFromURI(context, icon);
} else {
bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + LargeIconSize + "&Height=" + LargeIconSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + icon);
}
if (bmp == null) {
bmp = getIconFromRes(context, icon);
}
} else {
bmp = BitmapFactory.decodeResource(context.getResources(), context.getApplicationInfo().icon);
}
return bmp;
}
/**
* Returns the bitmap
*/
private static Bitmap getPicture(Context context, String pictureUrl)
{
Bitmap bmp = null;
if (pictureUrl != null) {
if (pictureUrl.startsWith("http:
bmp = getIconFromURL(pictureUrl);
} else if (pictureUrl.startsWith("file:
bmp = getIconFromURI(context, pictureUrl);
} else {
bmp = getIconFromURL("https://img.andygreen.com/photo.cf?Width=" + BigPictureSize + "&Ratio=" + devicePixelRatio + "&Checksum=" + pictureUrl);
}
if (bmp == null) {
bmp = getIconFromRes(context, pictureUrl);
}
}
return bmp;
}
/**
* @return
* The notification color for LED
*/
private static int getColor(String hexColor)
{
int aRGB = Integer.parseInt(hexColor,16);
aRGB += 0xFF000000;
return aRGB;
}
private static String getAppName(Context context)
{
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String)appName;
}
/**
* Returns numerical icon Value
*
* @param {String} className
* @param {String} iconName
*/
private static int getIconValue (String className, String iconName) {
int icon = 0;
try {
Class<?> klass = Class.forName(className + ".R$drawable");
icon = (Integer) klass.getDeclaredField(iconName).get(Integer.class);
} catch (Exception e) {}
return icon;
}
/**
* Converts an resource to Bitmap.
*
* @param icon
* The resource name
* @return
* The corresponding bitmap
*/
private static Bitmap getIconFromRes (Context context, String icon) {
Resources res = context.getResources();
int iconId = 0;
iconId = getIconValue(packageName, icon);
if (iconId == 0) {
iconId = getIconValue("android", icon);
}
if (iconId == 0) {
iconId = android.R.drawable.ic_menu_info_details;
}
Bitmap bmp = BitmapFactory.decodeResource(res, iconId);
return bmp;
}
/**
* Converts an Image URL to Bitmap.
*
* @param src
* The external image URL
* @return
* The corresponding bitmap
*/
private static Bitmap getIconFromURL (String src) {
Bitmap bmp = null;
ThreadPolicy origMode = StrictMode.getThreadPolicy();
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bmp = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
StrictMode.setThreadPolicy(origMode);
return bmp;
}
/**
* Converts an Image URI to Bitmap.
*
* @param src
* The internal image URI
* @return
* The corresponding bitmap
*/
private static Bitmap getIconFromURI (Context context, String src) {
AssetManager assets = context.getAssets();
Bitmap bmp = null;
try {
String path = src.replace("file:/", "www");
InputStream input = assets.open(path);
bmp = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
} |
package com.plugin.gcm;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.content.pm.PackageManager;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.net.MalformedURLException;
import com.google.android.gcm.GCMBaseIntentService;
@SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super("GCMIntentService");
}
@Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: "+ regId);
JSONObject json;
try
{
json = new JSONObject().put("event", "registered");
json.put("regid", regId);
Log.v(TAG, "onRegistered: " + json.toString());
// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
// In this case this is the registration ID
PushPlugin.sendJavascript( json );
}
catch( JSONException e)
{
// No message to the user is sent, JSON failed
Log.e(TAG, "onRegistered: JSON exception");
}
}
@Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null)
{
// if we are in the foreground, just surface the payload, else post it to the statusbar
//xxx
Log.d(TAG, "COMPU: MESSAGE RECEVIED "+extras.getString("msgid"));
Log.d(TAG, "COMPU: " + PushPlugin.getDeliveryReceiptURL());
//xxx
if (PushPlugin.isInForeground()) {
extras.putBoolean("foreground", true);
PushPlugin.sendExtras(extras);
}
else {
extras.putBoolean("foreground", false);
HttpURLConnection urlConnection = null;
try {
// create connection
// URL urlToRequest = new URL(PushPlugin.getDeliveryReceiptURL()+"?i="+extras.getString("msgid"));
URL urlToRequest = new URL(extras.getString("ConfirmURL"));
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
//urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
//urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
// handle issues
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized (if service requires user login)
Log.d(TAG, "COMPU: HTTP_UNAUTH");
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
Log.d(TAG, "COMPU: HTTP_ERROR");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 1024 * 16);
StringBuffer builder = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
Log.d(TAG, "COMPU: RECEIPT "+builder.toString());
extras.putString("deliveryReceipt", builder.toString());
/*
// create JSON object from content
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
return new JSONObject(getResponseText(in));
*/
} catch (MalformedURLException e) {
// URL is invalid
Log.d(TAG, "COMPU: URL invalid");
extras.putString("deliveryReceipt", "{status: \"invurl\"}");
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
Log.d(TAG, "COMPU: Socket Timeout");
extras.putString("deliveryReceipt", "{status: \"timeout\"}");
} catch (IOException e) {
// could not read response body
// (could not create input stream)
Log.d(TAG, "COMPU: IO Exception");
extras.putString("deliveryReceipt", "{status: \"IOExp\"}");
/*
} catch (JSONException e) {
// response body is no valid JSON string
Log.d(TAG, "COMPU: URL invalid");
*/
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
PushPlugin.sendExtras(extras);
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
createNotification(context, extras);
}
}
}
}
public void createNotification(Context context, Bundle extras)
{
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
Log.d(TAG, "COMPU: launchForeground "+extras.getString("launchForeground"));
if (extras.getString("launchForeground") == "y") {
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
} else {
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
notificationIntent.putExtra("pushBundle", extras);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int defaults = Notification.DEFAULT_ALL;
if (extras.getString("defaults") != null) {
try {
defaults = Integer.parseInt(extras.getString("defaults"));
} catch (NumberFormatException e) {}
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setDefaults(defaults)
.setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle(extras.getString("title"))
.setTicker(extras.getString("title"))
.setContentIntent(contentIntent)
.setAutoCancel(true);
String message = extras.getString("message");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
String msgcnt = extras.getString("msgcnt");
if (msgcnt != null) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
int notId = 0;
try {
notId = Integer.parseInt(extras.getString("notId"));
}
catch(NumberFormatException e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage());
}
catch(Exception e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage());
}
mNotificationManager.notify((String) appName, notId, mBuilder.build());
}
private static String getAppName(Context context)
{
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String)appName;
}
@Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
} |
package plugin.google.maps;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class PluginMarker extends MyPlugin {
private enum Animation {
DROP,
BOUNCE
}
/**
* Create a marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void createMarker(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// Create an instance of Marker class
final MarkerOptions markerOptions = new MarkerOptions();
final JSONObject opts = args.getJSONObject(1);
if (opts.has("position")) {
JSONObject position = opts.getJSONObject("position");
markerOptions.position(new LatLng(position.getDouble("lat"), position.getDouble("lng")));
}
if (opts.has("title")) {
markerOptions.title(opts.getString("title"));
}
if (opts.has("snippet")) {
markerOptions.snippet(opts.getString("snippet"));
}
if (opts.has("visible")) {
if (opts.has("icon") && "".equals(opts.getString("icon")) == false) {
markerOptions.visible(false);
} else {
markerOptions.visible(opts.getBoolean("visible"));
}
}
if (opts.has("draggable")) {
markerOptions.draggable(opts.getBoolean("draggable"));
}
if (opts.has("rotation")) {
markerOptions.rotation((float)opts.getDouble("rotation"));
}
if (opts.has("flat")) {
markerOptions.flat(opts.getBoolean("flat"));
}
if (opts.has("opacity")) {
markerOptions.alpha((float) opts.getDouble("opacity"));
}
if (opts.has("zIndex")) {
// do nothing, API v2 has no zIndex :(
}
Marker marker = map.addMarker(markerOptions);
// Store the marker
String id = "marker_" + marker.getId();
this.objects.put(id, marker);
JSONObject properties = new JSONObject();
if (opts.has("styles")) {
properties.put("styles", opts.getJSONObject("styles"));
}
if (opts.has("disableAutoPan")) {
properties.put("disableAutoPan", opts.getBoolean("disableAutoPan"));
} else {
properties.put("disableAutoPan", false);
}
this.objects.put("marker_property_" + marker.getId(), properties);
// Prepare the result
final JSONObject result = new JSONObject();
result.put("hashCode", marker.hashCode());
result.put("id", id);
// Load icon
if (opts.has("icon")) {
Bundle bundle = null;
Object value = opts.get("icon");
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` of the `icon` property
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
// The `infoWindowAnchor` property for infowindow
if (opts.has("infoWindowAnchor")) {
value = opts.get("infoWindowAnchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("infoWindowAnchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (opts.has("animation")) {
bundle.putString("animation", opts.getString("animation"));
}
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker)object;
if (opts.has("visible")) {
try {
marker.setVisible(opts.getBoolean("visible"));
} catch (Exception e) {
e.printStackTrace();
}
} else {
marker.setVisible(true);
}
// Animation
String markerAnimation = null;
if (opts.has("animation")) {
try {
markerAnimation = opts.getString("animation");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (markerAnimation != null) {
PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker)object;
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
callbackContext.success(result);
}
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
String markerAnimation = null;
if (opts.has("animation")) {
markerAnimation = opts.getString("animation");
}
if (markerAnimation != null) {
// Execute animation
this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
// Return the result if does not specify the icon property.
callbackContext.success(result);
}
}
}
private void setDropAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final Handler handler = new Handler();
final long startTime = SystemClock.uptimeMillis();
final long duration = 100;
final Projection proj = this.map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point markerPoint = proj.toScreenLocation(markerLatLng);
final Point startPoint = new Point(markerPoint.x, 0);
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
private void setBounceAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final Handler handler = new Handler();
final long startTime = SystemClock.uptimeMillis();
final long duration = 2000;
final Projection proj = this.map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point startPoint = proj.toScreenLocation(markerLatLng);
startPoint.offset(0, -200);
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
private void setMarkerAnimation_(Marker marker, String animationType, PluginAsyncInterface callback) {
Animation animation = null;
try {
animation = Animation.valueOf(animationType.toUpperCase(Locale.US));
} catch (Exception e) {
e.printStackTrace();
}
if (animation == null) {
callback.onPostExecute(marker);
return;
}
switch(animation) {
case DROP:
this.setDropAnimation_(marker, callback);
break;
case BOUNCE:
this.setBounceAnimation_(marker, callback);
break;
default:
break;
}
}
@SuppressWarnings("unused")
private void setAnimation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
String animation = args.getString(2);
final Marker marker = this.getMarker(id);
this.setMarkerAnimation_(marker, animation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success();
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
}
/**
* Show the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void showInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.showInfoWindow();
this.sendNoResult(callbackContext);
}
/**
* Set rotation for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setRotation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float rotation = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setRotation", id, rotation, callbackContext);
}
/**
* Set opacity for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float alpha = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setAlpha", id, alpha, callbackContext);
}
/**
* Set zIndex for the marker (dummy code, not available on Android V2)
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setZIndex(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// nothing to do :(
// it's a shame google...
}
/**
* set position
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
LatLng position = new LatLng(args.getDouble(2), args.getDouble(3));
Marker marker = this.getMarker(id);
marker.setPosition(position);
this.sendNoResult(callbackContext);
}
/**
* Set flat for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setFlat(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
boolean isFlat = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setFlat", id, isFlat, callbackContext);
}
/**
* Set visibility for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
protected void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean visible = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setVisible", id, visible, callbackContext);
}
/**
* @param args
* @param callbackContext
* @throws JSONException
*/
protected void setDisableAutoPan(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean disableAutoPan = args.getBoolean(2);
String id = args.getString(1);
Marker marker = this.getMarker(id);
String propertyId = "marker_property_" + marker.getId();
JSONObject properties = null;
if (this.objects.containsKey(propertyId)) {
properties = (JSONObject)this.objects.get(propertyId);
} else {
properties = new JSONObject();
}
properties.put("disableAutoPan", disableAutoPan);
this.objects.put(propertyId, properties);
this.sendNoResult(callbackContext);
}
/**
* Set title for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setTitle(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String title = args.getString(2);
String id = args.getString(1);
this.setString("setTitle", id, title, callbackContext);
}
/**
* Set the snippet for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setSnippet(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String snippet = args.getString(2);
String id = args.getString(1);
this.setString("setSnippet", id, snippet, callbackContext);
}
/**
* Hide the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void hideInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.hideInfoWindow();
this.sendNoResult(callbackContext);
}
/**
* Return the position of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void getPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
LatLng position = marker.getPosition();
JSONObject result = new JSONObject();
result.put("lat", position.latitude);
result.put("lng", position.longitude);
callbackContext.success(result);
}
/**
* Return 1 if the InfoWindow of the marker is shown
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void isInfoWindowShown(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Boolean isInfoWndShown = marker.isInfoWindowShown();
callbackContext.success(isInfoWndShown ? 1 : 0);
}
/**
* Remove the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void remove(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
if (marker == null) {
callbackContext.success();
return;
}
marker.remove();
this.objects.remove(id);
String propertyId = "marker_property_" + id;
this.objects.remove(propertyId);
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIconAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setIconAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the InfoWindow of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setInfoWindowAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setInfoWindowAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set draggable for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setDraggable(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Boolean draggable = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setDraggable", id, draggable, callbackContext);
}
/**
* Set icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIcon(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Object value = args.get(2);
Bundle bundle = null;
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` for icon
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else if (String.class.isInstance(value)) {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (bundle != null) {
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
PluginMarker.this.sendNoResult(callbackContext);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
this.sendNoResult(callbackContext);
}
}
private void setIcon_(final Marker marker, final Bundle iconProperty, final PluginAsyncInterface callback) {
if (iconProperty.containsKey("iconHue")) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
float hue = iconProperty.getFloat("iconHue");
marker.setIcon(BitmapDescriptorFactory.defaultMarker(hue));
callback.onPostExecute(marker);
}
});
return;
}
String iconUrl = iconProperty.getString("url");
if (iconUrl.indexOf(":
iconUrl.startsWith("/") == false &&
iconUrl.startsWith("www/") == false &&
iconUrl.startsWith("data:image") == false) {
iconUrl = "./" + iconUrl;
}
if (iconUrl.indexOf("./") == 0) {
String currentPage = this.webView.getUrl();
currentPage = currentPage.replaceAll("[^\\/]*$", "");
iconUrl = iconUrl.replace("./", currentPage);
}
if (iconUrl == null) {
callback.onPostExecute(marker);
return;
}
if (iconUrl.indexOf("http") != 0) {
// Load icon from local file
AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
String iconUrl = iconProperty.getString("url");
Bitmap image = null;
if (iconUrl.indexOf("cdvfile:
CordovaResourceApi resourceApi = webView.getResourceApi();
iconUrl = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, iconUrl);
}
if (iconUrl.indexOf("data:image/") == 0 && iconUrl.indexOf(";base64,") > -1) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else if (iconUrl.indexOf("file:
iconUrl.indexOf("file:///android_asset/") == -1) {
iconUrl = iconUrl.replace("file:
File tmp = new File(iconUrl);
if (tmp.exists()) {
image = BitmapFactory.decodeFile(iconUrl);
} else {
if (PluginMarker.this.mapCtrl.isDebug) {
Log.w("GoogleMaps", "icon is not found (" + iconUrl + ")");
}
}
} else {
if (iconUrl.indexOf("file:///android_asset/") == 0) {
iconUrl = iconUrl.replace("file:///android_asset/", "");
}
if (iconUrl.indexOf("./") == 0) {
iconUrl = iconUrl.replace("./", "www/");
}
AssetManager assetManager = PluginMarker.this.cordova.getActivity().getAssets();
InputStream inputStream;
try {
inputStream = assetManager.open(iconUrl);
image = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
Log.w("GoogleMaps", "Unable to decode bitmap stream for icon " + iconUrl + ")");
e.printStackTrace();
return null;
}
}
if (image == null) {
return null;
}
Boolean isResized = false;
if (iconProperty.containsKey("size") == true) {
Object size = iconProperty.get("size");
if (Bundle.class.isInstance(size)) {
Bundle sizeInfo = (Bundle)size;
int width = sizeInfo.getInt("width", 0);
int height = sizeInfo.getInt("height", 0);
if (width > 0 && height > 0) {
isResized = true;
width = (int)Math.round(width * PluginMarker.this.density);
height = (int)Math.round(height * PluginMarker.this.density);
image = PluginUtil.resizeBitmap(image, width, height);
}
}
}
if (!isResized) {
image = PluginUtil.scaleBitmapForDevice(image);
}
return image;
}
@Override
protected void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
try {
//TODO: check image is valid?
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
PluginMarker.this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
callback.onPostExecute(marker);
} catch (java.lang.IllegalArgumentException e) {
Log.e("GoogleMapsPlugin","PluginMarker: Warning - marker method called when marker has been disposed, wait for addMarker callback before calling more methods on the marker (setIcon etc).");
//e.printStackTrace();
}
}
};
task.execute();
return;
}
if (iconUrl.indexOf("http") == 0) {
// Load icon from on the internet
int width = -1;
int height = -1;
if (iconProperty.containsKey("size") == true) {
Bundle sizeInfo = (Bundle) iconProperty.get("size");
width = sizeInfo.getInt("width", width);
height = sizeInfo.getInt("height", height);
}
AsyncLoadImage task = new AsyncLoadImage(width, height, new AsyncLoadImageInterface() {
@Override
public void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
PluginMarker.this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
image.recycle();
callback.onPostExecute(marker);
}
});
task.execute(iconUrl);
}
}
private void _setIconAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
private void _setInfoWindowAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setInfoWindowAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
} |
package plugin.google.maps;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaResourceApi;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Set;
public class PluginMarker extends MyPlugin implements MyPluginInterface {
private enum Animation {
DROP,
BOUNCE
}
private ArrayList<AsyncTask> iconLoadingTasks = new ArrayList<AsyncTask>();
@Override
public void initialize(CordovaInterface cordova, final CordovaWebView webView) {
super.initialize(cordova, webView);
}
@Override
public void onDestroy() {
super.onDestroy();
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Set<String> keySet = objects.keySet();
String[] objectIdArray = keySet.toArray(new String[keySet.size()]);
for (String objectId : objectIdArray) {
if (objects.containsKey(objectId)) {
if (objectId.startsWith("marker_") &&
!objectId.startsWith("marker_property_")) {
Marker marker = (Marker) objects.remove(objectId);
marker.remove();
} else {
Object object = objects.remove(objectId);
object = null;
}
}
}
objects.clear();
objects = null;
}
});
}
@Override
protected void clear() {
AsyncLoadImage[] tasks = iconLoadingTasks.toArray(new AsyncLoadImage[iconLoadingTasks.size()]);
for (int i = 0; i < tasks.length; i++) {
tasks[i].cancel(true);
}
iconLoadingTasks.clear();
super.clear();
}
/**
* Create a marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
public void create(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// Create an instance of Marker class
final MarkerOptions markerOptions = new MarkerOptions();
final JSONObject properties = new JSONObject();
final JSONObject opts = args.getJSONObject(1);
if (opts.has("position")) {
JSONObject position = opts.getJSONObject("position");
markerOptions.position(new LatLng(position.getDouble("lat"), position.getDouble("lng")));
}
if (opts.has("title")) {
markerOptions.title(opts.getString("title"));
}
if (opts.has("snippet")) {
markerOptions.snippet(opts.getString("snippet"));
}
if (opts.has("visible")) {
if (opts.has("icon") && !"".equals(opts.getString("icon"))) {
markerOptions.visible(false);
properties.put("isVisible", false);
} else {
markerOptions.visible(opts.getBoolean("visible"));
properties.put("isVisible", markerOptions.isVisible());
}
}
if (opts.has("draggable")) {
markerOptions.draggable(opts.getBoolean("draggable"));
}
if (opts.has("rotation")) {
markerOptions.rotation((float)opts.getDouble("rotation"));
}
if (opts.has("flat")) {
markerOptions.flat(opts.getBoolean("flat"));
}
if (opts.has("opacity")) {
markerOptions.alpha((float) opts.getDouble("opacity"));
}
if (opts.has("zIndex")) {
markerOptions.zIndex((float) opts.getDouble("zIndex"));
}
if (opts.has("styles")) {
properties.put("styles", opts.getJSONObject("styles"));
}
if (opts.has("disableAutoPan")) {
properties.put("disableAutoPan", opts.getBoolean("disableAutoPan"));
} else {
properties.put("disableAutoPan", false);
}
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final Marker marker = map.addMarker(markerOptions);
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
// Store the marker
String id = "marker_" + marker.getId();
self.objects.put(id, marker);
self.objects.put("marker_property_" + marker.getId(), properties);
// Prepare the result
final JSONObject result = new JSONObject();
result.put("hashCode", marker.hashCode());
result.put("id", id);
// Load icon
if (opts.has("icon")) {
// Case: have the icon property
Bundle bundle = null;
Object value = opts.get("icon");
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject) value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` of the `icon` property
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray) value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
// The `infoWindowAnchor` property for infowindow
if (opts.has("infoWindowAnchor")) {
value = opts.get("infoWindowAnchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray) value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("infoWindowAnchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray) value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else {
bundle = new Bundle();
bundle.putString("url", (String) value);
}
if (opts.has("animation")) {
bundle.putString("animation", opts.getString("animation"));
}
PluginMarker.this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(final Object object) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = (Marker) object;
if (opts.has("visible")) {
try {
marker.setVisible(opts.getBoolean("visible"));
} catch (JSONException e) {
}
} else {
marker.setVisible(true);
}
// Animation
String markerAnimation = null;
if (opts.has("animation")) {
try {
markerAnimation = opts.getString("animation");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (markerAnimation != null) {
PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker) object;
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
callbackContext.success(result);
}
}
});
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
// Case: no icon property
String markerAnimation = null;
if (opts.has("animation")) {
markerAnimation = opts.getString("animation");
}
if (markerAnimation != null) {
// Execute animation
PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
// Return the result if does not specify the icon property.
callbackContext.success(result);
}
}
} catch (Exception e) {
e.printStackTrace();
callbackContext.error("" + e.getMessage());
}
}
});
}
});
}
private void setDropAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final long startTime = SystemClock.uptimeMillis();
final long duration = 100;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler();
final Projection proj = map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point markerPoint = proj.toScreenLocation(markerLatLng);
final Point startPoint = new Point(markerPoint.x, 0);
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
});
}
private void setBounceAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final long startTime = SystemClock.uptimeMillis();
final long duration = 2000;
final Interpolator interpolator = new BounceInterpolator();
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler();
final Projection projection = map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point startPoint = projection.toScreenLocation(markerLatLng);
startPoint.offset(0, -200);
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = projection.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
});
}
private void setMarkerAnimation_(Marker marker, String animationType, PluginAsyncInterface callback) {
Animation animation = null;
try {
animation = Animation.valueOf(animationType.toUpperCase(Locale.US));
} catch (Exception e) {
e.printStackTrace();
}
if (animation == null) {
callback.onPostExecute(marker);
return;
}
switch(animation) {
case DROP:
this.setDropAnimation_(marker, callback);
break;
case BOUNCE:
this.setBounceAnimation_(marker, callback);
break;
default:
break;
}
}
public void setAnimation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String markerId = args.getString(0);
String animation = args.getString(1);
final Marker marker = this.getMarker(markerId);
this.setMarkerAnimation_(marker, animation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success();
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
}
/**
* Show the InfoWindow bound with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void showInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = getMarker(id);
if (marker != null) {
marker.showInfoWindow();
}
sendNoResult(callbackContext);
}
});
}
/**
* Set rotation for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setRotation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float rotation = (float)args.getDouble(1);
String id = args.getString(0);
this.setFloat("setRotation", id, rotation, callbackContext);
}
/**
* Set opacity for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float alpha = (float)args.getDouble(1);
String id = args.getString(0);
this.setFloat("setAlpha", id, alpha, callbackContext);
}
/**
* Set zIndex for the marker (dummy code, not available on Android V2)
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setZIndex(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float zIndex = (float)args.getDouble(1);
String id = args.getString(0);
Marker marker = getMarker(id);
this.setFloat("setZIndex", id, zIndex, callbackContext);
}
/**
* set position
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
final LatLng position = new LatLng(args.getDouble(1), args.getDouble(2));
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = getMarker(id);
if (marker != null) {
marker.setPosition(position);
}
sendNoResult(callbackContext);
}
});
}
/**
* Set flat for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setFlat(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
boolean isFlat = args.getBoolean(1);
String id = args.getString(0);
this.setBoolean("setFlat", id, isFlat, callbackContext);
}
/**
* Set visibility for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean isVisible = args.getBoolean(1);
String id = args.getString(0);
Marker marker = this.getMarker(id);
if (marker == null) {
this.sendNoResult(callbackContext);
return;
}
String propertyId = "marker_property_" + marker.getId();
JSONObject properties = null;
if (self.objects.containsKey(propertyId)) {
properties = (JSONObject)self.objects.get(propertyId);
} else {
properties = new JSONObject();
}
properties.put("isVisible", isVisible);
self.objects.put(propertyId, properties);
this.setBoolean("setVisible", id, isVisible, callbackContext);
}
/**
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setDisableAutoPan(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean disableAutoPan = args.getBoolean(1);
String id = args.getString(0);
Marker marker = this.getMarker(id);
if (marker == null) {
this.sendNoResult(callbackContext);
return;
}
String propertyId = "marker_property_" + marker.getId();
JSONObject properties = null;
if (self.objects.containsKey(propertyId)) {
properties = (JSONObject)self.objects.get(propertyId);
} else {
properties = new JSONObject();
}
properties.put("disableAutoPan", disableAutoPan);
self.objects.put(propertyId, properties);
this.sendNoResult(callbackContext);
}
/**
* Set title for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setTitle(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String title = args.getString(1);
String id = args.getString(0);
this.setString("setTitle", id, title, callbackContext);
}
/**
* Set the snippet for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setSnippet(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String snippet = args.getString(1);
String id = args.getString(0);
this.setString("setSnippet", id, snippet, callbackContext);
}
/**
* Hide the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void hideInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Marker marker = getMarker(id);
if (marker != null) {
marker.hideInfoWindow();
}
sendNoResult(callbackContext);
}
});
}
/**
* Remove the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void remove(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String id = args.getString(0);
final Marker marker = this.getMarker(id);
if (marker == null) {
callbackContext.success();
return;
}
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
marker.remove();
objects.remove(id);
String propertyId = "marker_property_" + id;
objects.remove(propertyId);
sendNoResult(callbackContext);
}
});
}
/**
* Set anchor for the icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setIconAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(1);
float anchorY = (float)args.getDouble(2);
String id = args.getString(0);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) self.objects.get("imageSize");
if (imageSize != null) {
this._setIconAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the InfoWindow of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setInfoWindowAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(1);
float anchorY = (float)args.getDouble(2);
String id = args.getString(0);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) self.objects.get("imageSize");
if (imageSize != null) {
this._setInfoWindowAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set draggable for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setDraggable(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Boolean draggable = args.getBoolean(1);
String id = args.getString(0);
this.setBoolean("setDraggable", id, draggable, callbackContext);
}
/**
* Set icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
public void setIcon(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(0);
Marker marker = this.getMarker(id);
Object value = args.get(1);
Bundle bundle = null;
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` for icon
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else if (String.class.isInstance(value)) {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (bundle != null) {
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
PluginMarker.this.sendNoResult(callbackContext);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
this.sendNoResult(callbackContext);
}
}
private void setIcon_(final Marker marker, final Bundle iconProperty, final PluginAsyncInterface callback) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (iconProperty.containsKey("iconHue")) {
float hue = iconProperty.getFloat("iconHue");
marker.setIcon(BitmapDescriptorFactory.defaultMarker(hue));
callback.onPostExecute(marker);
}
String iconUrl = iconProperty.getString("url");
if (iconUrl == null) {
callback.onPostExecute(marker);
return;
}
if (!iconUrl.contains(":
!iconUrl.startsWith("/") &&
!iconUrl.startsWith("www/") &&
!iconUrl.startsWith("data:image") &&
!iconUrl.startsWith("./") &&
!iconUrl.startsWith("../")) {
iconUrl = "./" + iconUrl;
}
if (iconUrl.startsWith("./") || iconUrl.startsWith("../")) {
iconUrl = iconUrl.replace("././", "./");
String currentPage = PluginMarker.this.webView.getUrl();
currentPage = currentPage.replaceAll("[^\\/]*$", "");
iconUrl = currentPage + "/" + iconUrl;
}
if (iconUrl == null) {
callback.onPostExecute(marker);
return;
}
iconProperty.putString("url", iconUrl);
cordova.getThreadPool().submit(new Runnable() {
@Override
public void run() {
String iconUrl = iconProperty.getString("url");
if (iconUrl.indexOf("http") != 0) {
// Load icon from local file
AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
String iconUrl = iconProperty.getString("url");
if (iconUrl == null) {
return null;
}
Bitmap image = null;
if (iconUrl.indexOf("cdvfile:
CordovaResourceApi resourceApi = webView.getResourceApi();
iconUrl = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, iconUrl);
}
if (iconUrl == null) {
return null;
}
if (iconUrl.indexOf("data:image/") == 0 && iconUrl.contains(";base64,")) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else if (iconUrl.indexOf("file:
!iconUrl.contains("file:///android_asset/")) {
iconUrl = iconUrl.replace("file:
File tmp = new File(iconUrl);
if (tmp.exists()) {
image = BitmapFactory.decodeFile(iconUrl);
} else {
//if (PluginMarker.this.mapCtrl.mPluginLayout.isDebug) {
Log.w("GoogleMaps", "icon is not found (" + iconUrl + ")");
}
} else {
//Log.d(TAG, "iconUrl = " + iconUrl);
if (iconUrl.indexOf("file:///android_asset/") == 0) {
iconUrl = iconUrl.replace("file:///android_asset/", "");
}
//Log.d(TAG, "iconUrl = " + iconUrl);
if (iconUrl.contains("./")) {
try {
boolean isAbsolutePath = iconUrl.startsWith("/");
File relativePath = new File(iconUrl);
iconUrl = relativePath.getCanonicalPath();
//Log.d(TAG, "iconUrl = " + iconUrl);
if (!isAbsolutePath) {
iconUrl = iconUrl.substring(1);
}
//Log.d(TAG, "iconUrl = " + iconUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
AssetManager assetManager = PluginMarker.this.cordova.getActivity().getAssets();
InputStream inputStream;
try {
inputStream = assetManager.open(iconUrl);
image = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
callback.onPostExecute(marker);
return null;
}
}
if (image == null) {
callback.onPostExecute(marker);
return null;
}
Boolean isResized = false;
if (iconProperty.containsKey("size")) {
Object size = iconProperty.get("size");
if (Bundle.class.isInstance(size)) {
Bundle sizeInfo = (Bundle)size;
int width = sizeInfo.getInt("width", 0);
int height = sizeInfo.getInt("height", 0);
if (width > 0 && height > 0) {
isResized = true;
width = (int)Math.round(width * PluginMarker.this.density);
height = (int)Math.round(height * PluginMarker.this.density);
image = PluginUtil.resizeBitmap(image, width, height);
}
}
}
if (!isResized) {
image = PluginUtil.scaleBitmapForDevice(image);
}
return image;
}
@Override
protected void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
try {
//TODO: check image is valid?
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
self.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor")) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor")) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
callback.onPostExecute(marker);
} catch (java.lang.IllegalArgumentException e) {
Log.e("GoogleMapsPlugin","PluginMarker: Warning - marker method called when marker has been disposed, wait for addMarker callback before calling more methods on the marker (setIcon etc).");
//e.printStackTrace();
}
}
};
task.execute();
iconLoadingTasks.add(task);
return;
}
if (iconUrl.indexOf("http") == 0) {
// Load icon from on the internet
int width = -1;
int height = -1;
if (iconProperty.containsKey("size")) {
Bundle sizeInfo = (Bundle) iconProperty.get("size");
width = sizeInfo.getInt("width", width);
height = sizeInfo.getInt("height", height);
}
AsyncLoadImage task = new AsyncLoadImage(width, height, new AsyncLoadImageInterface() {
@Override
public void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
try {
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
self.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor")) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor")) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
image.recycle();
callback.onPostExecute(marker);
} catch (Exception e) {
//e.printStackTrace();
try {
marker.remove();
} catch (Exception ignore) {
ignore = null;
}
callback.onError(e.getMessage() + "");
}
}
});
task.execute(iconUrl);
iconLoadingTasks.add(task);
}
}
});
}
});
}
private void _setIconAnchor(final Marker marker, double anchorX, double anchorY, final int imageWidth, final int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
final double fAnchorX = anchorX;
final double fAnchorY = anchorY;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
marker.setAnchor((float)(fAnchorX / imageWidth), (float)(fAnchorY / imageHeight));
}
});
}
private void _setInfoWindowAnchor(final Marker marker, double anchorX, double anchorY, final int imageWidth, final int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
final double fAnchorX = anchorX;
final double fAnchorY = anchorY;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
marker.setInfoWindowAnchor((float)(fAnchorX / imageWidth), (float)(fAnchorY / imageHeight));
}
});
}
} |
package plugin.google.maps;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class PluginMarker extends MyPlugin {
private enum Animation {
DROP,
BOUNCE
}
/**
* Create a marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void createMarker(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
// Create an instance of Marker class
final MarkerOptions markerOptions = new MarkerOptions();
final JSONObject opts = args.getJSONObject(1);
if (opts.has("position")) {
JSONObject position = opts.getJSONObject("position");
markerOptions.position(new LatLng(position.getDouble("lat"), position.getDouble("lng")));
}
if (opts.has("title")) {
markerOptions.title(opts.getString("title"));
}
if (opts.has("snippet")) {
markerOptions.snippet(opts.getString("snippet"));
}
if (opts.has("visible")) {
if (opts.has("icon") && "".equals(opts.getString("icon")) == false) {
markerOptions.visible(false);
} else {
markerOptions.visible(opts.getBoolean("visible"));
}
}
if (opts.has("draggable")) {
markerOptions.draggable(opts.getBoolean("draggable"));
}
if (opts.has("rotation")) {
markerOptions.rotation((float)opts.getDouble("rotation"));
}
if (opts.has("flat")) {
markerOptions.flat(opts.getBoolean("flat"));
}
if (opts.has("opacity")) {
markerOptions.alpha((float) opts.getDouble("opacity"));
}
Marker marker = map.addMarker(markerOptions);
// Store the marker
String id = "marker_" + marker.getId();
this.objects.put(id, marker);
JSONObject properties = new JSONObject();
if (opts.has("styles")) {
properties.put("styles", opts.getJSONObject("styles"));
}
if (opts.has("disableAutoPan")) {
properties.put("disableAutoPan", opts.getBoolean("disableAutoPan"));
} else {
properties.put("disableAutoPan", false);
}
this.objects.put("marker_property_" + marker.getId(), properties);
// Prepare the result
final JSONObject result = new JSONObject();
result.put("hashCode", marker.hashCode());
result.put("id", id);
// Load icon
if (opts.has("icon")) {
Bundle bundle = null;
Object value = opts.get("icon");
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` of the `icon` property
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
// The `infoWindowAnchor` property for infowindow
if (opts.has("infoWindowAnchor")) {
value = opts.get("infoWindowAnchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("infoWindowAnchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (opts.has("animation")) {
bundle.putString("animation", opts.getString("animation"));
}
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker)object;
if (opts.has("visible")) {
try {
marker.setVisible(opts.getBoolean("visible"));
} catch (JSONException e) {}
} else {
marker.setVisible(true);
}
// Animation
String markerAnimation = null;
if (opts.has("animation")) {
try {
markerAnimation = opts.getString("animation");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (markerAnimation != null) {
PluginMarker.this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
Marker marker = (Marker)object;
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
callbackContext.success(result);
}
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
String markerAnimation = null;
if (opts.has("animation")) {
markerAnimation = opts.getString("animation");
}
if (markerAnimation != null) {
// Execute animation
this.setMarkerAnimation_(marker, markerAnimation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success(result);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
// Return the result if does not specify the icon property.
callbackContext.success(result);
}
}
}
private void setDropAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final Handler handler = new Handler();
final long startTime = SystemClock.uptimeMillis();
final long duration = 100;
final Projection proj = this.map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point markerPoint = proj.toScreenLocation(markerLatLng);
final Point startPoint = new Point(markerPoint.x, 0);
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
private void setBounceAnimation_(final Marker marker, final PluginAsyncInterface callback) {
final Handler handler = new Handler();
final long startTime = SystemClock.uptimeMillis();
final long duration = 2000;
final Projection proj = this.map.getProjection();
final LatLng markerLatLng = marker.getPosition();
final Point startPoint = proj.toScreenLocation(markerLatLng);
startPoint.offset(0, -200);
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
LatLng startLatLng = proj.fromScreenLocation(startPoint);
long elapsed = SystemClock.uptimeMillis() - startTime;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * markerLatLng.longitude + (1 - t) * startLatLng.longitude;
double lat = t * markerLatLng.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
marker.setPosition(markerLatLng);
callback.onPostExecute(marker);
}
}
});
}
private void setMarkerAnimation_(Marker marker, String animationType, PluginAsyncInterface callback) {
Animation animation = null;
try {
animation = Animation.valueOf(animationType.toUpperCase(Locale.US));
} catch (Exception e) {
e.printStackTrace();
}
if (animation == null) {
callback.onPostExecute(marker);
return;
}
switch(animation) {
case DROP:
this.setDropAnimation_(marker, callback);
break;
case BOUNCE:
this.setBounceAnimation_(marker, callback);
break;
default:
break;
}
}
@SuppressWarnings("unused")
private void setAnimation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
String animation = args.getString(2);
final Marker marker = this.getMarker(id);
this.setMarkerAnimation_(marker, animation, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
callbackContext.success();
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
}
/**
* Show the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void showInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.showInfoWindow();
this.sendNoResult(callbackContext);
}
/**
* Set rotation for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setRotation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float rotation = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setRotation", id, rotation, callbackContext);
}
/**
* Set opacity for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setOpacity(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float alpha = (float)args.getDouble(2);
String id = args.getString(1);
this.setFloat("setAlpha", id, alpha, callbackContext);
}
/**
* set position
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
LatLng position = new LatLng(args.getDouble(2), args.getDouble(3));
Marker marker = this.getMarker(id);
marker.setPosition(position);
this.sendNoResult(callbackContext);
}
/**
* Set flat for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setFlat(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
boolean isFlat = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setFlat", id, isFlat, callbackContext);
}
/**
* Set visibility for the object
* @param args
* @param callbackContext
* @throws JSONException
*/
protected void setVisible(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean visible = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setVisible", id, visible, callbackContext);
}
/**
* @param args
* @param callbackContext
* @throws JSONException
*/
protected void setDisableAutoPan(JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean disableAutoPan = args.getBoolean(2);
String id = args.getString(1);
Marker marker = this.getMarker(id);
String propertyId = "marker_property_" + marker.getId();
JSONObject properties = null;
if (this.objects.containsKey(propertyId)) {
properties = (JSONObject)this.objects.get(propertyId);
} else {
properties = new JSONObject();
}
properties.put("disableAutoPan", disableAutoPan);
this.objects.put(propertyId, properties);
this.sendNoResult(callbackContext);
}
/**
* Set title for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setTitle(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String title = args.getString(2);
String id = args.getString(1);
this.setString("setTitle", id, title, callbackContext);
}
/**
* Set the snippet for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setSnippet(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String snippet = args.getString(2);
String id = args.getString(1);
this.setString("setSnippet", id, snippet, callbackContext);
}
/**
* Hide the InfoWindow binded with the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void hideInfoWindow(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
marker.hideInfoWindow();
this.sendNoResult(callbackContext);
}
/**
* Return the position of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void getPosition(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
LatLng position = marker.getPosition();
JSONObject result = new JSONObject();
result.put("lat", position.latitude);
result.put("lng", position.longitude);
callbackContext.success(result);
}
/**
* Return 1 if the InfoWindow of the marker is shown
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void isInfoWindowShown(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Boolean isInfoWndShown = marker.isInfoWindowShown();
callbackContext.success(isInfoWndShown ? 1 : 0);
}
/**
* Remove the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void remove(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
if (marker == null) {
callbackContext.success();
return;
}
marker.remove();
this.objects.remove(id);
String propertyId = "marker_property_" + id;
this.objects.remove(propertyId);
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIconAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setIconAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set anchor for the InfoWindow of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setInfoWindowAnchor(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
float anchorX = (float)args.getDouble(2);
float anchorY = (float)args.getDouble(3);
String id = args.getString(1);
Marker marker = this.getMarker(id);
Bundle imageSize = (Bundle) this.objects.get("imageSize");
if (imageSize != null) {
this._setInfoWindowAnchor(marker, anchorX, anchorY, imageSize.getInt("width"), imageSize.getInt("height"));
}
this.sendNoResult(callbackContext);
}
/**
* Set draggable for the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setDraggable(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
Boolean draggable = args.getBoolean(2);
String id = args.getString(1);
this.setBoolean("setDraggable", id, draggable, callbackContext);
}
/**
* Set icon of the marker
* @param args
* @param callbackContext
* @throws JSONException
*/
@SuppressWarnings("unused")
private void setIcon(final JSONArray args, final CallbackContext callbackContext) throws JSONException {
String id = args.getString(1);
Marker marker = this.getMarker(id);
Object value = args.get(2);
Bundle bundle = null;
if (JSONObject.class.isInstance(value)) {
JSONObject iconProperty = (JSONObject)value;
bundle = PluginUtil.Json2Bundle(iconProperty);
// The `anchor` for icon
if (iconProperty.has("anchor")) {
value = iconProperty.get("anchor");
if (JSONArray.class.isInstance(value)) {
JSONArray points = (JSONArray)value;
double[] anchorPoints = new double[points.length()];
for (int i = 0; i < points.length(); i++) {
anchorPoints[i] = points.getDouble(i);
}
bundle.putDoubleArray("anchor", anchorPoints);
}
}
} else if (JSONArray.class.isInstance(value)) {
float[] hsv = new float[3];
JSONArray arrayRGBA = (JSONArray)value;
Color.RGBToHSV(arrayRGBA.getInt(0), arrayRGBA.getInt(1), arrayRGBA.getInt(2), hsv);
bundle = new Bundle();
bundle.putFloat("iconHue", hsv[0]);
} else if (String.class.isInstance(value)) {
bundle = new Bundle();
bundle.putString("url", (String)value);
}
if (bundle != null) {
this.setIcon_(marker, bundle, new PluginAsyncInterface() {
@Override
public void onPostExecute(Object object) {
PluginMarker.this.sendNoResult(callbackContext);
}
@Override
public void onError(String errorMsg) {
callbackContext.error(errorMsg);
}
});
} else {
this.sendNoResult(callbackContext);
}
}
private void setIcon_(final Marker marker, final Bundle iconProperty, final PluginAsyncInterface callback) {
if (iconProperty.containsKey("iconHue")) {
float hue = iconProperty.getFloat("iconHue");
marker.setIcon(BitmapDescriptorFactory.defaultMarker(hue));
callback.onPostExecute(marker);
return;
}
String iconUrl = iconProperty.getString("url");
if (iconUrl.indexOf(":
iconUrl.startsWith("/") == false &&
iconUrl.startsWith("www/") == false) {
iconUrl = "./" + iconUrl;
}
if (iconUrl.indexOf("./") == 0) {
String currentPage = this.webView.getUrl();
currentPage = currentPage.replaceAll("[^\\/]*$", "");
iconUrl = iconUrl.replace("./", currentPage);
}
if (iconUrl == null) {
callback.onPostExecute(marker);
return;
}
if (iconUrl.indexOf("http") != 0) {
AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
String iconUrl = iconProperty.getString("url");
Bitmap image = null;
if (iconUrl.indexOf("cdvfile:
CordovaResourceApi resourceApi = webView.getResourceApi();
iconUrl = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, iconUrl);
}
if (iconUrl.indexOf("data:image/") == 0 && iconUrl.indexOf(";base64,") > -1) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else if (iconUrl.indexOf("file:
iconUrl.indexOf("file:///android_asset/") == -1) {
iconUrl = iconUrl.replace("file:
File tmp = new File(iconUrl);
if (tmp.exists()) {
image = BitmapFactory.decodeFile(iconUrl);
} else {
if (PluginMarker.this.mapCtrl.isDebug) {
Log.w("GoogleMaps", "icon is not found (" + iconUrl + ")");
}
}
} else {
if (iconUrl.indexOf("file:///android_asset/") == 0) {
iconUrl = iconUrl.replace("file:///android_asset/", "");
}
if (iconUrl.indexOf("./") == 0) {
iconUrl = iconUrl.replace("./", "www/");
}
AssetManager assetManager = PluginMarker.this.cordova.getActivity().getAssets();
InputStream inputStream;
try {
inputStream = assetManager.open(iconUrl);
image = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
callback.onPostExecute(marker);
return null;
}
}
if (image == null) {
callback.onPostExecute(marker);
return null;
}
Boolean isResized = false;
if (iconProperty.containsKey("size") == true) {
Object size = iconProperty.get("size");
if (Bundle.class.isInstance(size)) {
Bundle sizeInfo = (Bundle)size;
int width = sizeInfo.getInt("width", 0);
int height = sizeInfo.getInt("height", 0);
if (width > 0 && height > 0) {
isResized = true;
width = (int)Math.round(width * PluginMarker.this.density);
height = (int)Math.round(height * PluginMarker.this.density);
image = PluginUtil.resizeBitmap(image, width, height);
}
}
}
if (isResized == false) {
image = PluginUtil.scaleBitmapForDevice(image);
}
return image;
}
@Override
protected void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
PluginMarker.this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
callback.onPostExecute(marker);
}
};
task.execute();
return;
}
if (iconUrl.indexOf("http") == 0) {
int width = -1;
int height = -1;
if (iconProperty.containsKey("size") == true) {
Bundle sizeInfo = (Bundle) iconProperty.get("size");
width = sizeInfo.getInt("width", width);
height = sizeInfo.getInt("height", height);
}
AsyncLoadImage task = new AsyncLoadImage(width, height, new AsyncLoadImageInterface() {
@Override
public void onPostExecute(Bitmap image) {
if (image == null) {
callback.onPostExecute(marker);
return;
}
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(image);
marker.setIcon(bitmapDescriptor);
// Save the information for the anchor property
Bundle imageSize = new Bundle();
imageSize.putInt("width", image.getWidth());
imageSize.putInt("height", image.getHeight());
PluginMarker.this.objects.put("imageSize", imageSize);
// The `anchor` of the `icon` property
if (iconProperty.containsKey("anchor") == true) {
double[] anchor = iconProperty.getDoubleArray("anchor");
if (anchor.length == 2) {
_setIconAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
// The `anchor` property for the infoWindow
if (iconProperty.containsKey("infoWindowAnchor") == true) {
double[] anchor = iconProperty.getDoubleArray("infoWindowAnchor");
if (anchor.length == 2) {
_setInfoWindowAnchor(marker, anchor[0], anchor[1], imageSize.getInt("width"), imageSize.getInt("height"));
}
}
image.recycle();
callback.onPostExecute(marker);
}
});
task.execute(iconUrl);
}
}
private void _setIconAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
private void _setInfoWindowAnchor(Marker marker, double anchorX, double anchorY, int imageWidth, int imageHeight) {
// The `anchor` of the `icon` property
anchorX = anchorX * this.density;
anchorY = anchorY * this.density;
marker.setInfoWindowAnchor((float)(anchorX / imageWidth), (float)(anchorY / imageHeight));
}
} |
package edu.umd.cs.findbugs.detect;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Deprecated;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.SignatureParser;
import edu.umd.cs.findbugs.ba.XClass;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.props.AbstractWarningProperty;
import edu.umd.cs.findbugs.props.PriorityAdjustment;
import edu.umd.cs.findbugs.props.WarningPropertySet;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
public class Naming extends PreorderVisitor implements Detector {
public static class NamingProperty extends AbstractWarningProperty {
private NamingProperty(String name, PriorityAdjustment priorityAdjustment) {
super(name, priorityAdjustment);
}
public static final NamingProperty METHOD_IS_CALLED = new NamingProperty("CONFUSING_METHOD_IS_CALLED",
PriorityAdjustment.LOWER_PRIORITY);
public static final NamingProperty METHOD_IS_DEPRECATED = new NamingProperty("CONFUSING_METHOD_IS_DEPRECATED",
PriorityAdjustment.LOWER_PRIORITY);
}
String baseClassName;
boolean classIsPublicOrProtected;
public static @CheckForNull
XMethod definedIn(JavaClass clazz, XMethod m) {
for (Method m2 : clazz.getMethods())
if (m.getName().equals(m2.getName()) && m.getSignature().equals(m2.getSignature()) && m.isStatic() == m2.isStatic())
return XFactory.createXMethod(clazz, m2);
return null;
}
public static boolean confusingMethodNames(XMethod m1, XMethod m2) {
if (m1.isStatic() != m2.isStatic())
return false;
if (m1.getClassName().equals(m2.getClassName()))
return false;
if (m1.getName().equals(m2.getName())) return false;
if (m1.getName().equalsIgnoreCase(m2.getName())
&& removePackageNamesFromSignature(m1.getSignature()).equals(removePackageNamesFromSignature(m2.getSignature())))
return true;
return false;
}
public static boolean confusingMethodNamesWrongPackage(XMethod m1, XMethod m2) {
if (m1.isStatic() != m2.isStatic())
return false;
if (m1.getClassName().equals(m2.getClassName()))
return false;
if (!m1.getName().equals(m2.getName()))
return false;
if (m1.getSignature().equals(m2.getSignature()))
return false;
if (removePackageNamesFromSignature(m1.getSignature()).equals(removePackageNamesFromSignature(m2.getSignature())))
return true;
return false;
}
// map of canonicalName -> trueMethodName
HashMap<String, HashSet<String>> canonicalToTrueMapping = new HashMap<String, HashSet<String>>();
// map of canonicalName -> Set<XMethod>
HashMap<String, HashSet<XMethod>> canonicalToXMethod = new HashMap<String, HashSet<XMethod>>();
HashSet<String> visited = new HashSet<String>();
private BugReporter bugReporter;
public Naming(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
classContext.getJavaClass().accept(this);
}
private boolean checkSuper(XMethod m, HashSet<XMethod> others) {
if (m.isStatic())
return false;
if (m.getName().equals("<init>") || m.getName().equals("<clinit>"))
return false;
for (XMethod m2 : others) {
try {
if ((confusingMethodNames(m, m2) || confusingMethodNamesWrongPackage(m,m2))
&& Repository.instanceOf(m.getClassName(), m2.getClassName())) {
WarningPropertySet<NamingProperty> propertySet = new WarningPropertySet<NamingProperty>();
int priority = HIGH_PRIORITY;
XMethod m3 = null;
try {
JavaClass clazz = Repository.lookupClass(m.getClassName());
if ((m3 = definedIn(clazz, m2)) == null) {
// the method we don't override is also defined in our class
priority = NORMAL_PRIORITY;
}
if (m3 == null)
for (JavaClass s : clazz.getSuperClasses())
if ((m3 = definedIn(s, m)) != null) {
// the method we define is also defined in our superclass
priority = NORMAL_PRIORITY;
break;
}
if (m3 == null)
for (JavaClass i : clazz.getAllInterfaces())
if ((m3 = definedIn(i, m)) != null) {
priority = NORMAL_PRIORITY;
// the method we define is also defined in an interface
break;
}
} catch (ClassNotFoundException e) {
priority++;
AnalysisContext.reportMissingClass(e);
}
XFactory xFactory = AnalysisContext.currentXFactory();
if (m3 == null && AnalysisContext.currentXFactory().isCalled(m))
propertySet.addProperty(NamingProperty.METHOD_IS_CALLED);
else if (m.isDeprecated() || m2.isDeprecated())
propertySet.addProperty(NamingProperty.METHOD_IS_DEPRECATED);
priority = propertySet.computePriority(priority);
if (!m.getName().equals(m2.getName()) && m.getName().equalsIgnoreCase(m2.getName())) {
String pattern = m3 != null ? "NM_VERY_CONFUSING_INTENTIONAL" : "NM_VERY_CONFUSING";
BugInstance bug = new BugInstance(this, pattern, priority).addClass(m.getClassName()).addMethod(m)
.addClass(m2.getClassName()).addMethod(m2);
if (m3 != null)
bug.addMethod(m3);
propertySet.decorateBugInstance(bug);
bugReporter.reportBug(bug);
}
if (!m.getSignature().equals(m2.getSignature())
&& removePackageNamesFromSignature(m.getSignature()).equals(
removePackageNamesFromSignature(m2.getSignature()))) {
String pattern = m3 != null ? "NM_WRONG_PACKAGE_INTENTIONAL" : "NM_WRONG_PACKAGE";
Iterator<String> s = new SignatureParser(m.getSignature()).parameterSignatureIterator();
Iterator<String> s2 = new SignatureParser(m2.getSignature()).parameterSignatureIterator();
while (s.hasNext()) {
String p = s.next();
String p2 = s2.next();
if (!p.equals(p2)) {
BugInstance bug = new BugInstance(this, pattern, priority).addClass(m.getClassName())
.addMethod(m).addClass(m2.getClassName()).addMethod(m2).addFoundAndExpectedType(p, p2);
if (m3 != null)
bug.addMethod(m3);
propertySet.decorateBugInstance(bug);
bugReporter.reportBug(bug);
}
}
}
return true;
}
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
}
return false;
}
private boolean checkNonSuper(XMethod m, HashSet<XMethod> others) {
if (m.isStatic())
return false;
if (m.getName().startsWith("<init>") || m.getName().startsWith("<clinit>"))
return false;
for (XMethod m2 : others) {
if (confusingMethodNames(m, m2)) {
XMethod mm1 = m;
XMethod mm2 = m2;
if (m.compareTo(m2) < 0) {
mm1 = m;
mm2 = m2;
} else {
mm1 = m2;
mm2 = m;
}
bugReporter.reportBug(new BugInstance(this, "NM_CONFUSING", LOW_PRIORITY).addClass(mm1.getClassName()).addMethod(
mm1).addClass(mm2.getClassName()).addMethod(mm2));
return true;
}
}
return false;
}
public void report() {
canonicalNameIterator: for (String allSmall : canonicalToTrueMapping.keySet()) {
HashSet<String> s = canonicalToTrueMapping.get(allSmall);
if (s.size() <= 1)
continue;
HashSet<XMethod> conflictingMethods = canonicalToXMethod.get(allSmall);
for (Iterator<XMethod> j = conflictingMethods.iterator(); j.hasNext();) {
if (checkSuper(j.next(), conflictingMethods))
j.remove();
}
for (XMethod conflictingMethod : conflictingMethods) {
if (checkNonSuper(conflictingMethod, conflictingMethods))
continue canonicalNameIterator;
}
}
}
public String stripPackageName(String className) {
if (className.indexOf('.') >= 0)
return className.substring(className.lastIndexOf('.') + 1);
else if (className.indexOf('/') >= 0)
return className.substring(className.lastIndexOf('/') + 1);
else
return className;
}
public boolean sameSimpleName(String class1, String class2) {
return class1 != null && class2 != null && stripPackageName(class1).equals(stripPackageName(class2));
}
@Override
public void visitJavaClass(JavaClass obj) {
String name = obj.getClassName();
if (!visited.add(name))
return;
String superClassName = obj.getSuperclassName();
if (!name.equals("java.lang.Object")) {
if (sameSimpleName(superClassName, name)) {
bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS", HIGH_PRIORITY).addClass(name)
.addClass(superClassName));
}
for (String interfaceName : obj.getInterfaceNames())
if (sameSimpleName(interfaceName, name)) {
bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_INTERFACE", NORMAL_PRIORITY).addClass(
name).addClass(interfaceName));
}
}
if (obj.isInterface())
return;
if (superClassName.equals("java.lang.Object") && !visited.contains(superClassName)) try {
visitJavaClass(obj.getSuperClass());
} catch (ClassNotFoundException e) {
// ignore it
}
super.visitJavaClass(obj);
}
/**
* Determine whether the class descriptor ultimately inherits from
* java.lang.Exception
* @param d class descriptor we want to check
* @return true iff the descriptor ultimately inherits from Exception
*/
private static boolean mightInheritFromException(ClassDescriptor d) {
while(d != null) {
try {
if("java.lang.Exception".equals(d.getDottedClassName())) {
return true;
}
XClass classNameAndInfo =
Global.getAnalysisCache().
getClassAnalysis(XClass.class, d);
d = classNameAndInfo.getSuperclassDescriptor();
} catch (CheckedAnalysisException e) {
return true; // don't know
}
}
return false;
}
@Override
public void visit(JavaClass obj) {
String name = obj.getClassName();
String[] parts = name.split("[$+.]");
baseClassName = parts[parts.length - 1];
for(String p : obj.getClassName().split("[.]")) if (p.length() == 1) return;
classIsPublicOrProtected = obj.isPublic() || obj.isProtected();
if (Character.isLetter(baseClassName.charAt(0)) && !Character.isUpperCase(baseClassName.charAt(0))
&& baseClassName.indexOf("_") == -1)
bugReporter.reportBug(new BugInstance(this, "NM_CLASS_NAMING_CONVENTION", classIsPublicOrProtected ? NORMAL_PRIORITY
: LOW_PRIORITY).addClass(this));
if (name.endsWith("Exception")) {
// Does it ultimately inherit from Throwable?
if(!mightInheritFromException(DescriptorFactory.createClassDescriptor(obj))) {
// It doens't, so the name is misleading
bugReporter.reportBug(new BugInstance(this, "NM_CLASS_NOT_EXCEPTION", NORMAL_PRIORITY).addClass(this));
}
}
super.visit(obj);
}
@Override
public void visit(Field obj) {
if (getFieldName().length() == 1)
return;
if (!obj.isFinal() && Character.isLetter(getFieldName().charAt(0)) && !Character.isLowerCase(getFieldName().charAt(0))
&& getFieldName().indexOf("_") == -1 && Character.isLetter(getFieldName().charAt(1))
&& Character.isLowerCase(getFieldName().charAt(1))) {
bugReporter.reportBug(new BugInstance(this, "NM_FIELD_NAMING_CONVENTION", classIsPublicOrProtected
&& (obj.isPublic() || obj.isProtected()) ? NORMAL_PRIORITY : LOW_PRIORITY).addClass(this).addVisitedField(
this));
}
}
private final static Pattern sigType = Pattern.compile("L([^;]*/)?([^/]+;)");
private boolean isInnerClass(JavaClass obj) {
for (Field f : obj.getFields())
if (f.getName().startsWith("this$"))
return true;
return false;
}
private boolean markedAsNotUsable(Method obj) {
for (Attribute a : obj.getAttributes())
if (a instanceof Deprecated)
return true;
Code code = obj.getCode();
if (code == null)
return false;
byte[] codeBytes = code.getCode();
if (codeBytes.length > 1 && codeBytes.length < 10) {
int lastOpcode = codeBytes[codeBytes.length - 1] & 0xff;
if (lastOpcode != ATHROW)
return false;
for (int b : codeBytes)
if ((b & 0xff) == RETURN)
return false;
return true;
}
return false;
}
private static @CheckForNull
Method findVoidConstructor(JavaClass clazz) {
for (Method m : clazz.getMethods())
if (m.getName().equals("<init>") && m.getSignature().equals("()V"))
return m;
return null;
}
@Override
public void visit(Method obj) {
String mName = getMethodName();
if (mName.length() == 1)
return;
if (mName.equals("isRequestedSessionIdFromURL") || mName.equals("isRequestedSessionIdFromUrl"))
return;
if (Character.isLetter(mName.charAt(0)) && !Character.isLowerCase(mName.charAt(0)) && Character.isLetter(mName.charAt(1))
&& Character.isLowerCase(mName.charAt(1)) && mName.indexOf("_") == -1)
bugReporter.reportBug(new BugInstance(this, "NM_METHOD_NAMING_CONVENTION", classIsPublicOrProtected
&& (obj.isPublic() || obj.isProtected()) ? NORMAL_PRIORITY : LOW_PRIORITY).addClassAndMethod(this));
String sig = getMethodSig();
if (mName.equals(baseClassName) && sig.equals("()V")) {
Code code = obj.getCode();
Method realVoidConstructor = findVoidConstructor(getThisClass());
if (code != null && !markedAsNotUsable(obj)) {
int priority = NORMAL_PRIORITY;
if (codeDoesSomething(code))
priority
else if (!obj.isPublic() && getThisClass().isPublic())
priority
if (realVoidConstructor == null)
priority++;
bugReporter.reportBug(new BugInstance(this, "NM_METHOD_CONSTRUCTOR_CONFUSION", priority).addClassAndMethod(this)
.lowerPriorityIfDeprecated());
return;
}
}
if (obj.isAbstract())
return;
if (obj.isPrivate())
return;
if (mName.equals("equal") && sig.equals("(Ljava/lang/Object;)Z")) {
bugReporter.reportBug(new BugInstance(this, "NM_BAD_EQUAL", HIGH_PRIORITY).addClassAndMethod(this)
.lowerPriorityIfDeprecated());
return;
}
if (mName.equals("hashcode") && sig.equals("()I")) {
bugReporter.reportBug(new BugInstance(this, "NM_LCASE_HASHCODE", HIGH_PRIORITY).addClassAndMethod(this)
.lowerPriorityIfDeprecated());
return;
}
if (mName.equals("tostring") && sig.equals("()Ljava/lang/String;")) {
bugReporter.reportBug(new BugInstance(this, "NM_LCASE_TOSTRING", HIGH_PRIORITY).addClassAndMethod(this)
.lowerPriorityIfDeprecated());
return;
}
if (obj.isPrivate() || obj.isStatic() || mName.equals("<init>"))
return;
String trueName = mName + sig;
String sig2 = removePackageNamesFromSignature(sig);
String allSmall = mName.toLowerCase() + sig2;
XMethod xm = getXMethod();
{
HashSet<String> s = canonicalToTrueMapping.get(allSmall);
if (s == null) {
s = new HashSet<String>();
canonicalToTrueMapping.put(allSmall, s);
}
s.add(trueName);
}
{
HashSet<XMethod> s = canonicalToXMethod.get(allSmall);
if (s == null) {
s = new HashSet<XMethod>();
canonicalToXMethod.put(allSmall, s);
}
s.add(xm);
}
}
private boolean codeDoesSomething(Code code) {
byte[] codeBytes = code.getCode();
return codeBytes.length > 1;
}
private static String removePackageNamesFromSignature(String sig) {
int end = sig.indexOf(")");
Matcher m = sigType.matcher(sig.substring(0, end));
return m.replaceAll("L$2") + sig.substring(end);
}
} |
/**
* @author Chris Serafin, Peter Maidens, Ken "Mike" Armstrong, Kimberly Kramer
*
* This class abstracts a pantry. It is a controller for the list of ingredients.
* It allows us to keep a list of ingredients and manage this list.
*/
package ca.ualberta.cs.oneclick_cookbook;
import java.util.ArrayList;
// This class abstracts a pantry (or list of ingredients)
// Wraps ArrayList functions
public class Pantry {
private ArrayList<Ingredient> ingredientList = null;
/**
* Constructor
*/
public Pantry() {
ingredientList = new ArrayList<Ingredient>();
}
/**
* Adds the ingredient to the list
* @param Ingredient the ingredient that you want to add
*/
public void addIngredient(Ingredient i) {
ingredientList.add(i);
}
/**
* Removes the ingredient by name
* @param name The name of the ingredient you want to remove. Must be exact
*/
public boolean removeIngredient(String name) {
for (int i=0; i<ingredientList.size(); i++) {
Ingredient ingredient = (Ingredient) ingredientList.get(i);
if (ingredient.getName().equals(name)) {
ingredientList.remove(ingredient);
return true;
}
}
// This happens if name wasn't in the list
return false;
}
/**
* Removes an ingredient based on a passed object
* @param i the ingredient you want to remove
*/
public boolean removeIngredient(Ingredient i) {
return ingredientList.remove(i);
}
/**
* Removes the ingredient at the ith index
* @param i index of the ingredient you want removed
*/
public void removeIngredient(int i) {
ingredientList.remove(i);
}
/**
* Clears the pantry
*/
public void emptyPantry() {
ingredientList.clear();
}
// Returns whether the pantry is empty or not
public boolean isEmpty() {
return ingredientList.isEmpty();
}
// Gets the Ingredient at the specified position
public Ingredient get(int i) {
return ingredientList.get(i);
}
/**
* checks wether an item is in the pantry
* @param name String of the name of the ingredient that you are testing
*/
public boolean isInPantry(String name) {
for (int i=0; i<ingredientList.size(); i++) {
Ingredient ingredient = (Ingredient) ingredientList.get(i);
if (ingredient.getName().equals(name)) {
return true;
}
}
// This happens if name wasn't in the list
return false;
}
/**
* Converst all ingredients to lower case
*/
public void toLower() {
for (int i=0; i<ingredientList.size(); i++) {
ingredientList.get(i).toLower();
}
}
/**
* Returns an ArrayList of the ingredients in the pantry converted to strings
* @return s ArrayList of strings
*/
public ArrayList<String> getStringArrayList() {
ArrayList<String> s = new ArrayList<String>();
for (int i=0; i<ingredientList.size(); i++) {
s.add(ingredientList.get(i).toString());
}
return s;
}
/**
* Converts the pantry to a string
* @return returns converted pantry
*/
public String toString() {
String s = "";
for (int i=0; i<(ingredientList.size() - 1); i++) {
s += ingredientList.get(i).toString() + ", ";
}
s += ingredientList.get(ingredientList.size() - 1).toString();
return s;
}
} |
package com.frostwire.jlibtorrent;
import com.frostwire.jlibtorrent.swig.*;
import com.frostwire.jlibtorrent.swig.torrent_handle.status_flags_t;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* You will usually have to store your torrent handles somewhere, since it's
* the object through which you retrieve information about the torrent and
* aborts the torrent.
* <p/>
* .. warning::
* Any member function that returns a value or fills in a value has to be
* made synchronously. This means it has to wait for the main thread to
* complete the query before it can return. This might potentially be
* expensive if done from within a GUI thread that needs to stay
* responsive. Try to avoid quering for information you don't need, and
* try to do it in as few calls as possible. You can get most of the
* interesting information about a torrent from the
* torrent_handle::status() call.
* <p/>
* The default constructor will initialize the handle to an invalid state.
* Which means you cannot perform any operation on it, unless you first
* assign it a valid handle. If you try to perform any operation on an
* uninitialized handle, it will throw ``invalid_handle``.
* <p/>
* .. warning::
* All operations on a torrent_handle may throw libtorrent_exception
* exception, in case the handle is no longer refering to a torrent.
* There is one exception is_valid() will never throw. Since the torrents
* are processed by a background thread, there is no guarantee that a
* handle will remain valid between two calls.
*
* @author gubatron
* @author aldenml
*/
public final class TorrentHandle {
private static final long REQUEST_STATUS_RESOLUTION_MILLIS = 500;
private final torrent_handle th;
private long lastStatusRequestTime;
private TorrentStatus lastStatus;
public TorrentHandle(torrent_handle th) {
this.th = th;
}
public torrent_handle getSwig() {
return th;
}
/**
* This function starts an asynchronous read operation of the specified
* piece from this torrent. You must have completed the download of the
* specified piece before calling this function.
* <p/>
* When the read operation is completed, it is passed back through an
* alert, read_piece_alert. Since this alert is a reponse to an explicit
* call, it will always be posted, regardless of the alert mask.
* <p/>
* Note that if you read multiple pieces, the read operations are not
* guaranteed to finish in the same order as you initiated them.
*
* @param piece
*/
public void readPiece(int piece) {
th.read_piece(piece);
}
/**
* Returns true if this piece has been completely downloaded, and false
* otherwise.
*
* @param piece
* @return
*/
public boolean havePiece(int piece) {
return th.have_piece(piece);
}
/**
* takes a reference to a vector that will be cleared and filled with one
* entry for each peer connected to this torrent, given the handle is
* valid. If the torrent_handle is invalid, it will return an empty list.
* <p/>
* Each entry in the vector contains
* information about that particular peer. See peer_info.
*
* @return
*/
public List<PeerInfo> getPeerInfo() {
if (!th.is_valid()) {
return Collections.emptyList();
}
peer_info_vector v = new peer_info_vector();
th.get_peer_info(v);
int size = (int) v.size();
List<PeerInfo> l = new ArrayList<PeerInfo>(size);
for (int i = 0; i < size; i++) {
l.add(new PeerInfo(v.get(i)));
}
return l;
}
/**
* Returns a pointer to the torrent_info object associated with this
* torrent. The torrent_info object may be a copy of the internal object.
* If the torrent doesn't have metadata, the pointer will not be
* initialized (i.e. a NULL pointer). The torrent may be in a state
* without metadata only if it was started without a .torrent file, e.g.
* by using the libtorrent extension of just supplying a tracker and
* info-hash.
*
* @return
*/
public TorrentInfo getTorrentInfo() {
torrent_info ti = th.torrent_file();
return ti != null ? new TorrentInfo(th.torrent_file()) : null;
}
/**
* `status()`` will return a structure with information about the status
* of this torrent. If the torrent_handle is invalid, it will throw
* libtorrent_exception exception. See torrent_status. The ``flags``
* argument filters what information is returned in the torrent_status.
* Some information in there is relatively expensive to calculate, and if
* you're not interested in it (and see performance issues), you can
* filter them out.
* <p/>
* By default everything is included. The flags you can use to decide
* what to *include* are defined in the status_flags_t enum.
* <p/>
* It is important not to call this method for each field in the status
* for performance reasons.
*
* @return
*/
public TorrentStatus getStatus(boolean force) {
long now = System.currentTimeMillis();
if (force || (now - lastStatusRequestTime) >= REQUEST_STATUS_RESOLUTION_MILLIS) {
lastStatusRequestTime = now;
lastStatus = new TorrentStatus(th.status());
}
return lastStatus;
}
/**
* `status()`` will return a structure with information about the status
* of this torrent. If the torrent_handle is invalid, it will throw
* libtorrent_exception exception. See torrent_status. The ``flags``
* argument filters what information is returned in the torrent_status.
* Some information in there is relatively expensive to calculate, and if
* you're not interested in it (and see performance issues), you can
* filter them out.
*
* @return
*/
public TorrentStatus getStatus() {
return this.getStatus(false);
}
/**
* returns the info-hash for the torrent.
*
* @return
*/
public Sha1Hash getInfoHash() {
return new Sha1Hash(th.info_hash());
}
/**
* ``pause()`` will disconnect all peers.
* <p/>
* When a torrent is paused, it will however
* remember all share ratios to all peers and remember all potential (not
* connected) peers. Torrents may be paused automatically if there is a
* file error (e.g. disk full) or something similar. See
* file_error_alert.
* <p/>
* To know if a torrent is paused or not, call
* ``torrent_handle::status()`` and inspect ``torrent_status::paused``.
* <p/>
* The ``flags`` argument to pause can be set to
* ``torrent_handle::graceful_pause`` which will delay the disconnect of
* peers that we're still downloading outstanding requests from. The
* torrent will not accept any more requests and will disconnect all idle
* peers. As soon as a peer is done transferring the blocks that were
* requested from it, it is disconnected. This is a graceful shut down of
* the torrent in the sense that no downloaded bytes are wasted.
* <p/>
* torrents that are auto-managed may be automatically resumed again. It
* does not make sense to pause an auto-managed torrent without making it
* not automanaged first.
* <p/>
* The current {@link Session} add torrent implementations add the torrent
* in no-auto-managed mode.
*/
public void pause() {
th.pause();
}
/**
* ``resume()`` will reconnect all peers.
* <p/>
* Torrents that are auto-managed may be automatically resumed again.
*/
public void resume() {
th.resume();
}
/**
* This function returns true if any whole chunk has been downloaded
* since the torrent was first loaded or since the last time the resume
* data was saved. When saving resume data periodically, it makes sense
* to skip any torrent which hasn't downloaded anything since the last
* time.
* <p/>
* .. note::
* A torrent's resume data is considered saved as soon as the alert is
* posted. It is important to make sure this alert is received and
* handled in order for this function to be meaningful.
*
* @return
*/
public boolean needSaveResumeData() {
return th.need_save_resume_data();
}
/**
* changes whether the torrent is auto managed or not. For more info,
* see queuing_.
*
* @param value
*/
public void setAutoManaged(boolean value) {
th.auto_managed(value);
}
/**
* Every torrent that is added is assigned a queue position exactly one
* greater than the greatest queue position of all existing torrents.
* Torrents that are being seeded have -1 as their queue position, since
* they're no longer in line to be downloaded.
* <p/>
* When a torrent is removed or turns into a seed, all torrents with
* greater queue positions have their positions decreased to fill in the
* space in the sequence.
* <p/>
* This function returns the torrent's position in the download
* queue. The torrents with the smallest numbers are the ones that are
* being downloaded. The smaller number, the closer the torrent is to the
* front of the line to be started.
* <p/>
* The queue position is also available in the torrent_status.
*
* @return
*/
public int getQueuePosition() {
return th.queue_position();
}
/**
* The ``queue_position_*()`` functions adjust the torrents position in
* the queue. Up means closer to the front and down means closer to the
* back of the queue. Top and bottom refers to the front and the back of
* the queue respectively.
*/
public void queuePositionUp() {
th.queue_position_up();
}
/**
* The ``queue_position_*()`` functions adjust the torrents position in
* the queue. Up means closer to the front and down means closer to the
* back of the queue. Top and bottom refers to the front and the back of
* the queue respectively.
*/
public void queuePositionDown() {
th.queue_position_down();
}
/**
* The ``queue_position_*()`` functions adjust the torrents position in
* the queue. Up means closer to the front and down means closer to the
* back of the queue. Top and bottom refers to the front and the back of
* the queue respectively.
*/
public void queuePositionTop() {
th.queue_position_top();
}
/**
* The ``queue_position_*()`` functions adjust the torrents position in
* the queue. Up means closer to the front and down means closer to the
* back of the queue. Top and bottom refers to the front and the back of
* the queue respectively.
*/
public void queuePositionBottom() {
th.queue_position_bottom();
}
/**
* ``save_resume_data()`` generates fast-resume data and returns it as an
* entry. This entry is suitable for being bencoded. For more information
* about how fast-resume works, see fast-resume_.
* <p/>
* The ``flags`` argument is a bitmask of flags ORed together. see
* save_resume_flags_t
* <p/>
* This operation is asynchronous, ``save_resume_data`` will return
* immediately. The resume data is delivered when it's done through an
* save_resume_data_alert.
* <p/>
* The fast resume data will be empty in the following cases:
* <p/>
* 1. The torrent handle is invalid.
* 2. The torrent is checking (or is queued for checking) its storage, it
* will obviously not be ready to write resume data.
* 3. The torrent hasn't received valid metadata and was started without
* metadata (see libtorrent's metadata-from-peers_ extension)
* <p/>
* Note that by the time you receive the fast resume data, it may already
* be invalid if the torrent is still downloading! The recommended
* practice is to first pause the session, then generate the fast resume
* data, and then close it down. Make sure to not remove_torrent() before
* you receive the save_resume_data_alert though. There's no need to
* pause when saving intermittent resume data.
* <p/>
* .. warning::
* If you pause every torrent individually instead of pausing the
* session, every torrent will have its paused state saved in the
* resume data!
* <p/>
* .. warning::
* The resume data contains the modification timestamps for all files.
* If one file has been modified when the torrent is added again, the
* will be rechecked. When shutting down, make sure to flush the disk
* cache before saving the resume data. This will make sure that the
* file timestamps are up to date and won't be modified after saving
* the resume data. The recommended way to do this is to pause the
* torrent, which will flush the cache and disconnect all peers.
* <p/>
* .. note::
* It is typically a good idea to save resume data whenever a torrent
* is completed or paused. In those cases you don't need to pause the
* torrent or the session, since the torrent will do no more writing to
* its files. If you save resume data for torrents when they are
* paused, you can accelerate the shutdown process by not saving resume
* data again for paused torrents. Completed torrents should have their
* resume data saved when they complete and on exit, since their
* statistics might be updated.
* <p/>
* In full allocation mode the reume data is never invalidated by
* subsequent writes to the files, since pieces won't move around. This
* means that you don't need to pause before writing resume data in full
* or sparse mode. If you don't, however, any data written to disk after
* you saved resume data and before the session closed is lost.
* <p/>
* It also means that if the resume data is out dated, libtorrent will
* not re-check the files, but assume that it is fairly recent. The
* assumption is that it's better to loose a little bit than to re-check
* the entire file.
* <p/>
* It is still a good idea to save resume data periodically during
* download as well as when closing down.
* <p/>
* Example code to pause and save resume data for all torrents and wait
* for the alerts:
* <p/>
* .. code:: c++
* <p/>
* extern int outstanding_resume_data; // global counter of outstanding resume data
* std::vector<torrent_handle> handles = ses.get_torrents();
* ses.pause();
* for (std::vector<torrent_handle>::iterator i = handles.begin();
* i != handles.end(); ++i)
* {
* torrent_handle& h = *i;
* if (!h.is_valid()) continue;
* torrent_status s = h.status();
* if (!s.has_metadata) continue;
* if (!s.need_save_resume_data()) continue;
* <p/>
* h.save_resume_data();
* ++outstanding_resume_data;
* }
* <p/>
* while (outstanding_resume_data > 0)
* {
* alert const* a = ses.wait_for_alert(seconds(10));
* <p/>
* // if we don't get an alert within 10 seconds, abort
* if (a == 0) break;
* <p/>
* std::auto_ptr<alert> holder = ses.pop_alert();
* <p/>
* if (alert_cast<save_resume_data_failed_alert>(a))
* {
* process_alert(a);
* --outstanding_resume_data;
* continue;
* }
* <p/>
* save_resume_data_alert const* rd = alert_cast<save_resume_data_alert>(a);
* if (rd == 0)
* {
* process_alert(a);
* continue;
* }
* <p/>
* torrent_handle h = rd->handle;
* torrent_status st = h.status(torrent_handle::query_save_path | torrent_handle::query_name);
* std::ofstream out((st.save_path
* + "/" + st.name + ".fastresume").c_str()
* , std::ios_base::binary);
* out.unsetf(std::ios_base::skipws);
* bencode(std::ostream_iterator<char>(out), *rd->resume_data);
* --outstanding_resume_data;
* }
* <p/>
* .. note::
* Note how ``outstanding_resume_data`` is a global counter in this
* example. This is deliberate, otherwise there is a race condition for
* torrents that was just asked to save their resume data, they posted
* the alert, but it has not been received yet. Those torrents would
* report that they don't need to save resume data again, and skipped by
* the initial loop, and thwart the counter otherwise.
*/
public void saveResumeData() {
th.save_resume_data(torrent_handle.save_resume_flags_t.save_info_dict.swigValue());
}
/**
* Returns true if this handle refers to a valid torrent and false if it
* hasn't been initialized or if the torrent it refers to has been
* aborted. Note that a handle may become invalid after it has been added
* to the session. Usually this is because the storage for the torrent is
* somehow invalid or if the filenames are not allowed (and hence cannot
* be opened/created) on your filesystem. If such an error occurs, a
* file_error_alert is generated and all handles that refers to that
* torrent will become invalid.
*
* @return
*/
public boolean isValid() {
return th.is_valid();
}
/**
* Generates a magnet URI from the specified torrent. If the torrent
* handle is invalid, null is returned.
*
* @return
*/
public String makeMagnetUri() {
return th.is_valid() ? libtorrent.make_magnet_uri(th) : null;
}
// ``set_upload_limit`` will limit the upload bandwidth used by this
// particular torrent to the limit you set. It is given as the number of
// bytes per second the torrent is allowed to upload.
// ``set_download_limit`` works the same way but for download bandwidth
// instead of upload bandwidth. Note that setting a higher limit on a
// torrent then the global limit
// (``session_settings::upload_rate_limit``) will not override the global
// rate limit. The torrent can never upload more than the global rate
// limit.
// ``upload_limit`` and ``download_limit`` will return the current limit
// setting, for upload and download, respectively.
public int getUploadLimit() {
return th.upload_limit();
}
// ``set_upload_limit`` will limit the upload bandwidth used by this
// particular torrent to the limit you set. It is given as the number of
// bytes per second the torrent is allowed to upload.
// ``set_download_limit`` works the same way but for download bandwidth
// instead of upload bandwidth. Note that setting a higher limit on a
// torrent then the global limit
// (``session_settings::upload_rate_limit``) will not override the global
// rate limit. The torrent can never upload more than the global rate
// limit.
// ``upload_limit`` and ``download_limit`` will return the current limit
// setting, for upload and download, respectively.
public void setUploadLimit(int limit) {
th.set_upload_limit(limit);
}
// ``set_upload_limit`` will limit the upload bandwidth used by this
// particular torrent to the limit you set. It is given as the number of
// bytes per second the torrent is allowed to upload.
// ``set_download_limit`` works the same way but for download bandwidth
// instead of upload bandwidth. Note that setting a higher limit on a
// torrent then the global limit
// (``session_settings::upload_rate_limit``) will not override the global
// rate limit. The torrent can never upload more than the global rate
// limit.
// ``upload_limit`` and ``download_limit`` will return the current limit
// setting, for upload and download, respectively.
public int getDownloadLimit() {
return th.download_limit();
}
// ``set_upload_limit`` will limit the upload bandwidth used by this
// particular torrent to the limit you set. It is given as the number of
// bytes per second the torrent is allowed to upload.
// ``set_download_limit`` works the same way but for download bandwidth
// instead of upload bandwidth. Note that setting a higher limit on a
// torrent then the global limit
// (``session_settings::upload_rate_limit``) will not override the global
// rate limit. The torrent can never upload more than the global rate
// limit.
// ``upload_limit`` and ``download_limit`` will return the current limit
// setting, for upload and download, respectively.
public void setDownloadLimit(int limit) {
th.set_download_limit(limit);
}
/**
* Enables or disables *sequential download*.
* <p/>
* When enabled, the piece picker will pick pieces in sequence
* instead of rarest first. In this mode, piece priorities are ignored,
* with the exception of priority 7, which are still preferred over the
* sequential piece order.
* <p/>
* Enabling sequential download will affect the piece distribution
* negatively in the swarm. It should be used sparingly.
*
* @param sequential
*/
public void setSequentialDownload(boolean sequential) {
th.set_sequential_download(sequential);
}
// ``force_recheck`` puts the torrent back in a state where it assumes to
// have no resume data. All peers will be disconnected and the torrent
// will stop announcing to the tracker. The torrent will be added to the
// checking queue, and will be checked (all the files will be read and
// compared to the piece hashes). Once the check is complete, the torrent
// will start connecting to peers again, as normal.
public void forceRecheck() {
th.force_recheck();
}
// ``force_reannounce()`` will force this torrent to do another tracker
// request, to receive new peers. The ``seconds`` argument specifies how
// many seconds from now to issue the tracker announces.
// If the tracker's ``min_interval`` has not passed since the last
// announce, the forced announce will be scheduled to happen immediately
// as the ``min_interval`` expires. This is to honor trackers minimum
// re-announce interval settings.
// The ``tracker_index`` argument specifies which tracker to re-announce.
// If set to -1 (which is the default), all trackers are re-announce.
public void forceReannounce(int seconds, int tracker_index) {
th.force_reannounce(seconds, tracker_index);
}
// ``force_reannounce()`` will force this torrent to do another tracker
// request, to receive new peers. The ``seconds`` argument specifies how
// many seconds from now to issue the tracker announces.
// If the tracker's ``min_interval`` has not passed since the last
// announce, the forced announce will be scheduled to happen immediately
// as the ``min_interval`` expires. This is to honor trackers minimum
// re-announce interval settings.
// The ``tracker_index`` argument specifies which tracker to re-announce.
// If set to -1 (which is the default), all trackers are re-announce.
public void forceReannounce(int seconds) {
th.force_reannounce(seconds);
}
/**
* Force this torrent to do another tracker
* request, to receive new peers. The ``seconds`` argument specifies how
* many seconds from now to issue the tracker announces.
* <p/>
* If the tracker's ``min_interval`` has not passed since the last
* announce, the forced announce will be scheduled to happen immediately
* as the ``min_interval`` expires. This is to honor trackers minimum
* re-announce interval settings.
* <p/>
* The ``tracker_index`` argument specifies which tracker to re-announce.
* If set to -1 (which is the default), all trackers are re-announce.
*/
public void forceReannounce() {
th.force_reannounce();
}
/**
* Announce the torrent to the DHT immediately.
*/
public void forceDHTAnnounce() {
th.force_dht_announce();
}
/**
* Will return the list of trackers for this torrent. The
* announce entry contains both a string ``url`` which specify the
* announce url for the tracker as well as an int ``tier``, which is
* specifies the order in which this tracker is tried.
*
* @return
*/
public List<AnnounceEntry> getTrackers() {
announce_entry_vector v = th.trackers();
int size = (int) v.size();
List<AnnounceEntry> list = new ArrayList<AnnounceEntry>(size);
for (int i = 0; i < size; i++) {
list.add(new AnnounceEntry(v.get(i)));
}
return list;
}
/**
* Will send a scrape request to the tracker. A
* scrape request queries the tracker for statistics such as total number
* of incomplete peers, complete peers, number of downloads etc.
* <p/>
* This request will specifically update the ``num_complete`` and
* ``num_incomplete`` fields in the torrent_status struct once it
* completes. When it completes, it will generate a scrape_reply_alert.
* If it fails, it will generate a scrape_failed_alert.
*/
public void scrapeTracker() {
th.scrape_tracker();
}
// If you want
// libtorrent to use another list of trackers for this torrent, you can
// use ``replace_trackers()`` which takes a list of the same form as the
// one returned from ``trackers()`` and will replace it. If you want an
// immediate effect, you have to call force_reannounce(). See
// announce_entry.
// The updated set of trackers will be saved in the resume data, and when
// a torrent is started with resume data, the trackers from the resume
// data will replace the original ones.
public void replaceTrackers(List<AnnounceEntry> trackers) {
announce_entry_vector v = new announce_entry_vector();
for (AnnounceEntry e : trackers) {
v.add(e.getSwig());
}
th.replace_trackers(v);
}
// ``add_tracker()`` will look if the specified tracker is already in the
// set. If it is, it doesn't do anything. If it's not in the current set
// of trackers, it will insert it in the tier specified in the
// announce_entry.
// The updated set of trackers will be saved in the resume data, and when
// a torrent is started with resume data, the trackers from the resume
// data will replace the original ones.
public void addTracker(AnnounceEntry tracker) {
th.add_tracker(tracker.getSwig());
}
// ``add_url_seed()`` adds another url to the torrent's list of url
// seeds. If the given url already exists in that list, the call has no
// effect. The torrent will connect to the server and try to download
// pieces from it, unless it's paused, queued, checking or seeding.
// ``remove_url_seed()`` removes the given url if it exists already.
// ``url_seeds()`` return a set of the url seeds currently in this
// torrent. Note that urls that fails may be removed automatically from
// the list.
// See http-seeding_ for more information.
public void addUrlSeed(String url) {
th.add_url_seed(url);
}
// ``add_url_seed()`` adds another url to the torrent's list of url
// seeds. If the given url already exists in that list, the call has no
// effect. The torrent will connect to the server and try to download
// pieces from it, unless it's paused, queued, checking or seeding.
// ``remove_url_seed()`` removes the given url if it exists already.
// ``url_seeds()`` return a set of the url seeds currently in this
// torrent. Note that urls that fails may be removed automatically from
// the list.
// See http-seeding_ for more information.
public void removeUrlSeed(String url) {
th.remove_url_seed(url);
}
// These functions are identical as the ``*_url_seed()`` variants, but
// they operate on `BEP 17`_ web seeds instead of `BEP 19`_.
// See http-seeding_ for more information.
public void addHttpSeed(String url) {
th.add_url_seed(url);
}
// These functions are identical as the ``*_url_seed()`` variants, but
// they operate on `BEP 17`_ web seeds instead of `BEP 19`_.
// See http-seeding_ for more information.
public void removeHttpSeed(String url) {
th.remove_http_seed(url);
}
/**
* index must be in the range [0, number_of_files).
* <p/>
* The priority values are the same as for piece_priority().
* <p/>
* Whenever a file priority is changed, all other piece priorities are
* reset to match the file priorities. In order to maintain sepcial
* priorities for particular pieces, piece_priority() has to be called
* again for those pieces.
* <p/>
* You cannot set the file priorities on a torrent that does not yet have
* metadata or a torrent that is a seed. ``file_priority(int, int)`` and
* prioritize_files() are both no-ops for such torrents.
*
* @param index
* @param priority
*/
public void setFilePriority(int index, Priority priority) {
th.file_priority(index, priority.getSwig());
}
/**
* index must be in the range [0, number_of_files).
* <p/>
* queries or sets the priority of file index.
*
* @param index
* @return
*/
public Priority getFilePriority(int index) {
return Priority.fromSwig(th.file_priority(index));
}
/**
* Takes a vector that has at as many elements as
* there are files in the torrent. Each entry is the priority of that
* file. The function sets the priorities of all the pieces in the
* torrent based on the vector.
*
* @param priorities
*/
public void prioritizeFiles(Priority[] priorities) {
int[] arr = new int[priorities.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = priorities[i] != Priority.UNKNOWN ? priorities[i].getSwig() : Priority.IGNORE.getSwig();
}
th.prioritize_files(Vectors.ints2int_vector(arr));
}
/**
* Returns a vector with the priorities of all files.
*
* @return
*/
public Priority[] getFilePriorities() {
int_vector v = th.file_priorities();
int size = (int) v.size();
Priority[] arr = new Priority[size];
for (int i = 0; i < size; i++) {
arr[i] = Priority.fromSwig(v.get(i));
}
return arr;
}
/**
* This function sets or resets the deadline associated with a specific
* piece index (``index``). libtorrent will attempt to download this
* entire piece before the deadline expires. This is not necessarily
* possible, but pieces with a more recent deadline will always be
* prioritized over pieces with a deadline further ahead in time. The
* deadline (and flags) of a piece can be changed by calling this
* function again.
* <p/>
* If the piece is already downloaded when this call is made, nothing
* happens, unless the alert_when_available flag is set, in which case it
* will do the same thing as calling read_piece() for ``index``.
*
* @param index
* @param deadline
*/
public void setPieceDeadline(int index, int deadline) {
th.set_piece_deadline(index, deadline);
}
/**
* This function sets or resets the deadline associated with a specific
* piece index (``index``). libtorrent will attempt to download this
* entire piece before the deadline expires. This is not necessarily
* possible, but pieces with a more recent deadline will always be
* prioritized over pieces with a deadline further ahead in time. The
* deadline (and flags) of a piece can be changed by calling this
* function again.
* <p/>
* The ``flags`` parameter can be used to ask libtorrent to send an alert
* once the piece has been downloaded, by passing alert_when_available.
* When set, the read_piece_alert alert will be delivered, with the piece
* data, when it's downloaded.
* <p/>
* If the piece is already downloaded when this call is made, nothing
* happens, unless the alert_when_available flag is set, in which case it
* will do the same thing as calling read_piece() for ``index``.
*
* @param index
* @param deadline
* @param flags
*/
public void setPieceDeadline(int index, int deadline, DeadlineFlags flags) {
th.set_piece_deadline(index, deadline, flags.getSwig());
}
/**
* Removes the deadline from the piece. If it
* hasn't already been downloaded, it will no longer be considered a
* priority.
*
* @param index
*/
public void resetPieceDeadline(int index) {
th.reset_piece_deadline(index);
}
/**
* Removes deadlines on all pieces in the torrent.
* As if {@link #resetPieceDeadline(int)} was called on all pieces.
*/
public void clearPieceDeadlines() {
th.clear_piece_deadlines();
}
/**
* This sets the bandwidth priority of this torrent. The priority of a
* torrent determines how much bandwidth its peers are assigned when
* distributing upload and download rate quotas. A high number gives more
* bandwidth. The priority must be within the range [0, 255].
* <p/>
* The default priority is 0, which is the lowest priority.
* <p/>
* To query the priority of a torrent, use the
* ``torrent_handle::status()`` call.
* <p/>
* Torrents with higher priority will not nececcarily get as much
* bandwidth as they can consume, even if there's is more quota. Other
* peers will still be weighed in when bandwidth is being distributed.
* With other words, bandwidth is not distributed strictly in order of
* priority, but the priority is used as a weight.
* <p/>
* Peers whose Torrent has a higher priority will take precedence when
* distributing unchoke slots. This is a strict prioritization where
* every interested peer on a high priority torrent will be unchoked
* before any other, lower priority, torrents have any peers unchoked.
*
* @param priority
*/
public void setPriority(int priority) {
if (priority < 0 || 255 < priority) {
throw new IllegalArgumentException("The priority must be within the range [0, 255]");
}
th.set_priority(priority);
}
/**
* This function fills in the supplied vector with the number of
* bytes downloaded of each file in this torrent. The progress values are
* ordered the same as the files in the torrent_info. This operation is
* not very cheap. Its complexity is *O(n + mj)*. Where *n* is the number
* of files, *m* is the number of downloading pieces and *j* is the
* number of blocks in a piece.
* <p/>
* The ``flags`` parameter can be used to specify the granularity of the
* file progress. If left at the default value of 0, the progress will be
* as accurate as possible, but also more expensive to calculate. If
* ``torrent_handle::piece_granularity`` is specified, the progress will
* be specified in piece granularity. i.e. only pieces that have been
* fully downloaded and passed the hash check count. When specifying
* piece granularity, the operation is a lot cheaper, since libtorrent
* already keeps track of this internally and no calculation is required.
*
* @param flags
* @return
*/
public long[] getFileProgress(FileProgressFlags flags) {
int64_vector v = new int64_vector();
th.file_progress(v, flags.getSwig());
return Vectors.int64_vector2longs(v);
}
/**
* This function fills in the supplied vector with the number of
* bytes downloaded of each file in this torrent. The progress values are
* ordered the same as the files in the torrent_info. This operation is
* not very cheap. Its complexity is *O(n + mj)*. Where *n* is the number
* of files, *m* is the number of downloading pieces and *j* is the
* number of blocks in a piece.
*
* @return
*/
public long[] getFileProgress() {
int64_vector v = new int64_vector();
th.file_progress(v);
return Vectors.int64_vector2longs(v);
}
/**
* The path to the directory where this torrent's files are stored.
* It's typically the path as was given to async_add_torrent() or
* add_torrent() when this torrent was started.
*
* @return
*/
public String getSavePath() {
torrent_status ts = th.status(status_flags_t.query_save_path.swigValue());
return ts.getSave_path();
}
/**
* The name of the torrent. Typically this is derived from the
* .torrent file. In case the torrent was started without metadata,
* and hasn't completely received it yet, it returns the name given
* to it when added to the session.
*
* @return
*/
public String getName() {
torrent_status ts = th.status(status_flags_t.query_name.swigValue());
return ts.getName();
}
/**
* flags to be passed in {} file_progress().
*/
public enum FileProgressFlags {
DEFAULT(0),
/**
* only calculate file progress at piece granularity. This makes
* the file_progress() call cheaper and also only takes bytes that
* have passed the hash check into account, so progress cannot
* regress in this mode.
*/
PIECE_GRANULARITY(torrent_handle.file_progress_flags_t.piece_granularity.swigValue());
private FileProgressFlags(int swigValue) {
this.swigValue = swigValue;
}
private final int swigValue;
public int getSwig() {
return swigValue;
}
}
/**
* Flags for {@link #setPieceDeadline(int, int, com.frostwire.jlibtorrent.TorrentHandle.DeadlineFlags)}.
*/
public enum DeadlineFlags {
ALERT_WHEN_AVAILABLE(torrent_handle.deadline_flags.alert_when_available.swigValue());
private DeadlineFlags(int swigValue) {
this.swigValue = swigValue;
}
private final int swigValue;
public int getSwig() {
return swigValue;
}
}
} |
package com.orbekk.paxos;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.protobuf.RpcCallback;
import com.orbekk.protobuf.Rpc;
import com.orbekk.same.ConnectionManager;
import com.orbekk.same.RpcFactory;
import com.orbekk.same.Services;
import com.orbekk.same.Services.ClientState;
import com.orbekk.same.Services.PaxosRequest;
import com.orbekk.same.Services.PaxosResponse;
public class MasterProposer extends Thread {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final ClientState client;
private final List<String> paxosLocations;
private final ConnectionManager connections;
private final RpcFactory rpcf;
public MasterProposer(ClientState client, List<String> paxosLocations,
ConnectionManager connections, RpcFactory rpcf) {
this.client = client;
this.paxosLocations = paxosLocations;
this.connections = connections;
this.rpcf = rpcf;
}
private class ResponseHandler implements RpcCallback<PaxosResponse> {
final int proposalNumber;
final int numRequests;
final AtomicInteger bestPromise = new AtomicInteger();
final AtomicInteger numPromises = new AtomicInteger(0);
final AtomicInteger numResponses = new AtomicInteger(0);
final AtomicInteger result = new AtomicInteger();
final CountDownLatch done = new CountDownLatch(1);
public ResponseHandler(int proposalNumber, int numRequests) {
this.proposalNumber = proposalNumber;
this.numRequests = numRequests;
bestPromise.set(-proposalNumber);
}
@Override public void run(PaxosResponse response) {
if (response != null) {
int result = response.getResult();
if (result == proposalNumber) {
numPromises.incrementAndGet();
}
boolean updated = false;
while (!updated) {
int oldVal = bestPromise.get();
int update = Math.min(oldVal, result);
updated = bestPromise.compareAndSet(oldVal, update);
}
}
numResponses.incrementAndGet();
checkDone();
}
private void checkDone() {
if (numPromises.get() > numRequests / 2) {
result.set(proposalNumber);
done.countDown();
} else if (numResponses.get() >= numRequests) {
result.set(bestPromise.get());
done.countDown();
}
}
public int getResult() throws InterruptedException {
done.await();
logger.info("ResponseHandler: {} / {} successes.",
numPromises.get(), numRequests);
return result.get();
}
}
private int internalPropose(int proposalNumber)
throws InterruptedException {
ResponseHandler handler = new ResponseHandler(proposalNumber,
paxosLocations.size());
for (String location : paxosLocations) {
Rpc rpc = rpcf.create();
Services.Paxos paxos = connections.getPaxos0(location);
if (paxos == null) {
handler.run(null);
continue;
}
PaxosRequest request = PaxosRequest.newBuilder()
.setClient(client)
.setProposalNumber(proposalNumber)
.build();
paxos.propose(rpc, request, handler);
}
return handler.getResult();
}
private int internalAcceptRequest(int proposalNumber)
throws InterruptedException {
ResponseHandler handler = new ResponseHandler(proposalNumber,
paxosLocations.size());
for (String location : paxosLocations) {
Rpc rpc = rpcf.create();
Services.Paxos paxos = connections.getPaxos0(location);
PaxosRequest request = PaxosRequest.newBuilder()
.setClient(client)
.setProposalNumber(proposalNumber)
.build();
paxos.acceptRequest(rpc, request, handler);
rpc.await();
logger.info("Rpc result from paxos.acceptRequest: " + rpc.errorText());
}
return handler.getResult();
}
boolean propose(int proposalNumber) throws InterruptedException {
int result = internalPropose(proposalNumber);
if (result == proposalNumber) {
result = internalAcceptRequest(proposalNumber);
}
if (result == proposalNumber) {
return true;
} else {
return false;
}
}
boolean proposeRetry(int proposalNumber) throws InterruptedException {
return proposeRetry(proposalNumber, null) != null;
}
Integer proposeRetry(int proposalNumber, Runnable retryAction)
throws InterruptedException {
logger.info("Paxos services: {}.", paxosLocations);
assert proposalNumber > 0;
int nextProposal = proposalNumber;
int result = nextProposal - 1;
while (!Thread.currentThread().isInterrupted() && result != nextProposal) {
result = internalPropose(nextProposal);
if (result == nextProposal) {
result = internalAcceptRequest(nextProposal);
}
logger.info("Proposed value {}, result {}.",
nextProposal, result);
if (result < 0) {
nextProposal = -result + 1;
if (retryAction != null) {
retryAction.run();
}
}
}
if (Thread.interrupted()) {
throw new InterruptedException();
}
return result;
}
public Future<Integer> startProposalTask(final int proposalNumber,
final Runnable retryAction) {
Callable<Integer> proposalCallable = new Callable<Integer>() {
@Override public Integer call() throws Exception {
return proposeRetry(proposalNumber, retryAction);
}
};
FutureTask<Integer> task = new FutureTask<Integer>(proposalCallable);
new Thread(task).start();
return task;
}
} |
package cz.hobrasoft.pdfmu.sign;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.CrlClient;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.OcspClient;
import com.itextpdf.text.pdf.security.PrivateKeySignature;
import com.itextpdf.text.pdf.security.TSAClient;
import cz.hobrasoft.pdfmu.Operation;
import cz.hobrasoft.pdfmu.OperationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Collection;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* Adds a digital signature to a PDF document
*
* @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a>
*/
public class OperationSign implements Operation {
// digitalsignatures20130304.pdf : Code sample 1.6
// Initialize the security provider
private static final BouncyCastleProvider provider = new BouncyCastleProvider();
static {
// We need to register the provider because it needs to be accessible by its name globally.
// {@link com.itextpdf.text.pdf.security.PrivateKeySignature#PrivateKeySignature(PrivateKey pk, String hashAlgorithm, String provider)}
// uses the provider name.
Security.addProvider(provider);
}
// Initialize the digest algorithm
private static final ExternalDigest externalDigest = new BouncyCastleDigest();
// `signatureParameters` is a member variable
// so that we can add the arguments to the parser in `addParser`.
// We need an instance of {@link SignatureParameters} in `addParser`
// because the interface `ArgsConfiguration` does not allow static methods.
private final SignatureParameters signatureParameters = new SignatureParameters();
private static void sign(PdfSignatureAppearance sap,
ExternalDigest externalDigest,
ExternalSignature externalSignature,
Certificate[] chain,
MakeSignature.CryptoStandard sigtype) throws OperationException {
// TODO?: Set some of the following parameters more sensibly
// Certificate Revocation List
// digitalsignatures20130304.pdf : Section 3.2
Collection<CrlClient> crlList = null;
// Online Certificate Status Protocol
// digitalsignatures20130304.pdf : Section 3.2.4
OcspClient ocspClient = null;
// Time Stamp Authority
// digitalsignatures20130304.pdf : Section 3.3
TSAClient tsaClient = null;
// digitalsignatures20130304.pdf : Section 3.5
// The value of 0 means "try a generous educated guess".
// We need not change this unless we want to optimize the resulting PDF document size.
int estimatedSize = 0;
System.err.println(String.format("Cryptographic standard (signature format): %s", sigtype));
try {
MakeSignature.signDetached(sap, externalDigest, externalSignature, chain, crlList, ocspClient, tsaClient, estimatedSize, sigtype);
} catch (IOException | DocumentException | GeneralSecurityException ex) {
throw new OperationException("Could not sign the document.", ex);
} catch (NullPointerException ex) {
throw new OperationException("Could not sign the document. Invalid digest algorithm?", ex);
}
System.err.println("Document successfully signed.");
}
private static void sign(PdfSignatureAppearance sap,
ExternalSignature externalSignature,
Certificate[] chain,
MakeSignature.CryptoStandard sigtype) throws OperationException {
// Use the static BouncyCastleDigest instance
sign(sap, OperationSign.externalDigest, externalSignature, chain, sigtype);
}
private void sign(PdfSignatureAppearance sap,
PrivateKey pk,
String digestAlgorithm,
Certificate[] chain,
MakeSignature.CryptoStandard sigtype) throws OperationException {
assert digestAlgorithm != null;
// Initialize the signature algorithm
System.err.println(String.format("Digest algorithm: %s", digestAlgorithm));
if (DigestAlgorithms.getAllowedDigests(digestAlgorithm) == null) {
throw new OperationException(String.format("The digest algorithm %s is not supported.", digestAlgorithm));
}
System.err.println(String.format("Signature security provider: %s", provider.getName()));
ExternalSignature externalSignature = new PrivateKeySignature(pk, digestAlgorithm, provider.getName());
sign(sap, externalSignature, chain, sigtype);
}
private void sign(PdfSignatureAppearance sap,
KeyStore ks,
KeyParameters keyParameters,
String digestAlgorithm,
MakeSignature.CryptoStandard sigtype) throws OperationException {
assert keyParameters != null;
// Fix the values, especially if they were not set at all
keyParameters.fix(ks);
PrivateKey pk = keyParameters.getPrivateKey(ks);
Certificate[] chain = keyParameters.getCertificateChain(ks);
sign(sap, pk, digestAlgorithm, chain, sigtype);
}
private void sign(PdfSignatureAppearance sap,
KeystoreParameters keystoreParameters,
KeyParameters keyParameters,
String digestAlgorithm,
MakeSignature.CryptoStandard sigtype) throws OperationException {
assert keystoreParameters != null;
// Initialize and load keystore
KeyStore ks = keystoreParameters.loadKeystore();
sign(sap, ks, keyParameters, digestAlgorithm, sigtype);
}
private void sign(PdfStamper stp,
SignatureParameters signatureParameters) throws OperationException {
assert signatureParameters != null;
// Unwrap the signature parameters
SignatureAppearanceParameters signatureAppearanceParameters = signatureParameters.appearance;
KeystoreParameters keystoreParameters = signatureParameters.keystore;
KeyParameters keyParameters = signatureParameters.key;
String digestAlgorithm = signatureParameters.digestAlgorithm;
MakeSignature.CryptoStandard sigtype = signatureParameters.sigtype;
// Initialize the signature appearance
PdfSignatureAppearance sap = signatureAppearanceParameters.getSignatureAppearance(stp);
sign(sap, keystoreParameters, keyParameters, digestAlgorithm, sigtype);
}
private void sign(PdfReader pdfReader,
File outFile,
boolean append,
SignatureParameters signatureParameters) throws OperationException {
assert outFile != null;
System.err.println(String.format("Output PDF document: %s", outFile));
// Open the output stream
FileOutputStream os;
try {
os = new FileOutputStream(outFile);
} catch (FileNotFoundException ex) {
throw new OperationException("Could not open the output file.", ex);
}
if (append) {
System.err.println("Appending signature.");
} else {
System.err.println("Replacing signature.");
}
PdfStamper stp;
try {
// digitalsignatures20130304.pdf : Code sample 2.17
// TODO?: Make sure version is high enough
stp = PdfStamper.createSignature(pdfReader, os, '\0', null, append);
} catch (DocumentException | IOException ex) {
throw new OperationException("Could not open the PDF stamper.", ex);
}
sign(stp, signatureParameters);
// Close the PDF stamper
try {
stp.close();
} catch (DocumentException | IOException ex) {
throw new OperationException("Could not close PDF stamper.", ex);
}
// Close the output stream
try {
os.close();
} catch (IOException ex) {
throw new OperationException("Could not close the output file.", ex);
}
}
private void sign(File inFile,
File outFile,
boolean append,
SignatureParameters signatureParameters) throws OperationException {
assert inFile != null;
System.err.println(String.format("Input PDF document: %s", inFile));
// Open the input stream
FileInputStream inStream;
try {
inStream = new FileInputStream(inFile);
} catch (FileNotFoundException ex) {
throw new OperationException("Input file not found.", ex);
}
// Open the PDF reader
// PdfReader parses a PDF document.
PdfReader pdfReader;
try {
pdfReader = new PdfReader(inStream);
} catch (IOException ex) {
throw new OperationException("Could not open the input PDF document.", ex);
}
if (outFile == null) {
System.err.println("Output file not set. Commencing in-place operation.");
outFile = inFile;
}
sign(pdfReader, outFile, append, signatureParameters);
// Close the PDF reader
pdfReader.close();
// Close the input stream
try {
inStream.close();
} catch (IOException ex) {
throw new OperationException("Could not close the input file.", ex);
}
}
@Override
public void execute(Namespace namespace) throws OperationException {
// Input file
File inFile = namespace.get("in");
assert inFile != null; // Required argument
System.err.println(String.format("Input PDF document: %s", inFile));
// Output file
File outFile = namespace.get("out");
if (outFile == null) {
System.err.println("--out option not specified; assuming in-place version change");
outFile = inFile;
}
System.err.println(String.format("Output PDF document: %s", outFile));
if (outFile.exists()) {
System.err.println("Output file already exists.");
if (!namespace.getBoolean("force")) {
throw new OperationException("Set --force flag to overwrite.");
}
}
boolean append = true; // TODO?: Expose
// Initialize signature parameters
signatureParameters.setFromNamespace(namespace);
sign(inFile, outFile, append, signatureParameters);
}
@Override
public Subparser addParser(Subparsers subparsers) {
String help = "Digitally sign a PDF document";
String metavarIn = "IN.pdf";
String metavarOut = "OUT.pdf";
// Add the subparser
Subparser subparser = subparsers.addParser("sign")
.help(help)
.description(help)
.defaultHelp(true)
.setDefault("command", OperationSign.class);
// Add arguments to the subparser
// Positional arguments are required by default
subparser.addArgument("in")
.help("input PDF document")
.metavar(metavarIn)
.type(Arguments.fileType().acceptSystemIn().verifyCanRead())
.required(true);
subparser.addArgument("-o", "--out")
.help(String.format("output PDF document (default: <%s>)", metavarIn))
.metavar(metavarOut)
.type(Arguments.fileType().verifyCanCreate())
.nargs("?");
subparser.addArgument("-f", "--force")
.help(String.format("overwrite %s if it exists", metavarOut))
.type(boolean.class)
.action(Arguments.storeTrue());
signatureParameters.addArguments(subparser);
return subparser;
}
} |
package org.smoothbuild.db.object.obj.expr;
import static com.google.common.truth.Truth.assertThat;
import static org.smoothbuild.testing.common.AssertCall.assertCall;
import static org.smoothbuild.util.collect.Lists.list;
import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.smoothbuild.db.object.obj.ObjBTestCase;
import org.smoothbuild.db.object.obj.val.ArrayB;
import org.smoothbuild.db.object.type.expr.IfCB;
import org.smoothbuild.testing.TestingContext;
public class IfBTest extends TestingContext {
@Nested
class _infer_type_of_if {
@Test
public void with_both_clauses_having_same_type() {
assertThat(ifB(boolB(true), intB(1), intB(2)).cat())
.isEqualTo(ifCB(intTB()));
}
@Test
public void with_then_clauses_being_subtype_of_else_clause() {
assertThat(ifB(boolB(true), arrayB(nothingTB()), arrayB(stringTB())).cat())
.isEqualTo(ifCB(arrayTB(stringTB())));
}
@Test
public void with_else_clauses_being_subtype_of_then_clause() {
assertThat(ifB(boolB(true), arrayB(stringTB()), arrayB(nothingTB())).cat())
.isEqualTo(ifCB(arrayTB(stringTB())));
}
}
@Test
public void then_clauses_can_be_subtype_of_else_clause() {
var ifCB = ifCB(arrayTB(stringTB()));
var then = arrayB(stringTB());
var else_ = arrayB(nothingTB());
test_clauses(ifCB, then, else_);
}
@Test
public void else_clauses_can_be_subtype_of_then_clause() {
var then = arrayB(stringTB());
var else_ = arrayB(nothingTB());
var ifCB = ifCB(arrayTB(stringTB()));
test_clauses(ifCB, then, else_);
}
private void test_clauses(IfCB ifCB, ArrayB then, ArrayB else_) {
var ifB = ifB(boolB(true), then, else_);
assertThat(ifB.cat())
.isEqualTo(ifCB);
assertThat(ifB.data().then())
.isEqualTo(then);
assertThat(ifB.data().else_())
.isEqualTo(else_);
}
@Test
public void creating_if_with_condition_not_being_bool_causes_exception() {
assertCall(() -> ifB(blobB(0), intB(1), intB(2)))
.throwsException(new IllegalArgumentException(
"`condition` component must evaluate to BoolH but is `Blob`."));
}
@Test
public void condition_getter() {
var ifB = ifB(boolB(true), intB(1), intB(2));
assertThat(ifB.data().condition())
.isEqualTo(boolB(true));
}
@Test
public void then_getter() {
var ifB = ifB(boolB(true), intB(1), intB(2));
assertThat(ifB.data().then())
.isEqualTo(intB(1));
}
@Test
public void else_getter() {
var ifB = ifB(boolB(true), intB(1), intB(2));
assertThat(ifB.data().else_())
.isEqualTo(intB(2));
}
@Nested
class _equals_hash_hashcode extends ObjBTestCase<IfB> {
@Override
protected List<IfB> equalValues() {
return list(
ifB(boolB(true), intB(1), intB(2)),
ifB(boolB(true), intB(1), intB(2))
);
}
@Override
protected List<IfB> nonEqualValues() {
return list(
ifB(boolB(true), intB(1), intB(2)),
ifB(boolB(true), intB(1), intB(9)),
ifB(boolB(true), intB(9), intB(2)),
ifB(boolB(false), intB(1), intB(2))
);
}
}
@Test
public void if_can_be_read_back_by_hash() {
var condition = boolB(true);
var then = intB(1);
var else_ = intB(2);
var ifB = ifB(condition, then, else_);
assertThat(byteDbOther().get(ifB.hash()))
.isEqualTo(ifB);
}
@Test
public void map_read_back_by_hash_has_same_data() {
var condition = boolB(true);
var then = intB(1);
var else_ = intB(2);
var ifB = ifB(condition, then, else_);
var readIf = (IfB) byteDbOther().get(ifB.hash());
var readIfData = readIf.data();
var ifData = ifB.data();
assertThat(readIfData.condition())
.isEqualTo(ifData.condition());
assertThat(readIfData.then())
.isEqualTo(ifData.then());
assertThat(readIfData.else_())
.isEqualTo(ifData.else_());
}
@Test
public void to_string() {
var condition = boolB(true);
var then = intB(1);
var else_ = intB(2);
var ifB = ifB(condition, then, else_);
assertThat(ifB.toString())
.isEqualTo("If:Int(???)@" + ifB.hash());
}
} |
package com.imu.coursenet.dao.impl;
import java.util.ArrayList;
import java.util.List;
import com.imu.coursenet.dao.AdminDao;
import com.imu.coursenet.domain.Admin;
import com.imu.coursenet.support.YeekuHibernateDaoSupport;
public class AdminDaoImpl
extends YeekuHibernateDaoSupport
implements AdminDao
{
@Override
public Admin get(Integer userId) {
return getHibernateTemplate()
.get(Admin.class , userId);
}
@Override
public Integer save(Admin admin) {
return (Integer)getHibernateTemplate()
.save(admin);
}
@Override
public void update(Admin admin) {
getHibernateTemplate()
.update(admin);
}
@Override
public void delete(Admin admin) {
getHibernateTemplate()
.delete(admin);
}
@Override
public void delete(Integer userId) {
getHibernateTemplate()
.delete(get(userId));
}
@Override
public List<Admin> findAll() {
return (List<Admin>)getHibernateTemplate()
.find("from Admin");
}
@Override
public List<Admin> findByAccountAndPass(String userAccount,String userPass)
{
return (List<Admin>)getHibernateTemplate()
.find("from Admin a where a.userAccount = ? and a.userPass=?"
,userAccount , userPass);
/*
List admin=new ArrayList();
Admin ad=new Admin();
admin.add(ad);
return admin;
*/
}
} |
package com.intuit.quickfoods;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
public class QuickFoodsService extends Service{
public NsdHelper mNsdHelper;
public QuickFoodsConnection mConnection;
public Handler mUpdateHandler;
public static final String TAG = "SocketConnection";
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mUpdateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG,msg.getData().getString("msg"));
// todo when you a message
}
};
mConnection = new QuickFoodsConnection(mUpdateHandler);
mNsdHelper = new NsdHelper(getApplicationContext());
mNsdHelper.initializeNsd();
advertise();
discover();
connect();
send();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void advertise() {
// Register service
if(mConnection.getLocalPort() > -1) {
mNsdHelper.registerService(mConnection.getLocalPort());
} else {
Log.d(TAG, "ServerSocket isn't bound.");
}
}
public void discover() {
mNsdHelper.discoverServices();
}
public void connect() {
NsdServiceInfo service = mNsdHelper.getChosenServiceInfo();
if (service != null) {
Log.d(TAG, "Connecting.");
mConnection.connectToServer(service.getHost(),
service.getPort());
} else {
Log.d(TAG, "No service to connect to!");
}
}
public void send() {
//EditText messageView = (EditText) this.findViewById(R.id.chatInput);
//if (messageView != null) {
//String messageString = messageView.getText().toString();
// TODO
String messageString = "DUMMY";
if (!messageString.isEmpty()) {
mConnection.sendMessage(messageString);
}
//messageView.setText("");
}
public void addChatLine(String line) {
//mStatusView.append("\n" + line);
}
@Override
public void onDestroy() {
mNsdHelper.tearDown();
mConnection.tearDown();
super.onDestroy();
}
} |
package com.karateca.ddescriber.model;
import com.intellij.find.FindResult;
import com.intellij.openapi.editor.Document;
import java.util.ArrayList;
import java.util.List;
/**
* @author Andres Dominguez.
*/
class Hierarchy {
private final Document document;
private final TestFindResult closest;
private final List<TestFindResult> testFindResults;
public Hierarchy(Document document, List<FindResult> findResults, int caretOffset) {
this.document = document;
testFindResults = new ArrayList<TestFindResult>();
for (FindResult findResult : findResults) {
TestFindResult result = new TestFindResult(document, findResult);
testFindResults.add(result);
}
// TODO: no longer necessary
this.closest = getClosestTestFromCaret(caretOffset);
}
public Hierarchy(Document document, List<FindResult> findResults) {
this(document, findResults, 0);
}
/**
* Get the closest unit test or suite from the current caret position.
*
* @param caretOffset The current caret position in the editor.
* @return The closest test or suite.
*/
public TestFindResult getClosestTestFromCaret(int caretOffset) {
int lineNumber = document.getLineNumber(caretOffset) + 1;
TestFindResult closest = null;
int minDistance = Integer.MAX_VALUE;
// Get the closest unit test or suite from the current caret.
for (TestFindResult testFindResult : testFindResults) {
int distance = Math.abs(lineNumber - testFindResult.getLineNumber());
if (distance < minDistance) {
closest = testFindResult;
minDistance = distance;
} else {
return closest;
}
}
return closest;
}
public TestFindResult getClosest() {
return closest;
}
public List<TestFindResult> getMarkedElements() {
List<TestFindResult> results = new ArrayList<TestFindResult>();
for (TestFindResult element : testFindResults) {
if (element.getTestState() != TestState.NotModified) {
results.add(element);
}
}
return results;
}
public List<TestFindResult> getAllUnitTests() {
return testFindResults;
}
} |
// Kyle Russell
// AUT University 2016
// Highly Secured Systems A2
package com.kyleruss.hssa2.commons;
public class RequestPaths
{
private RequestPaths() {}
public static final String USER_PUBLIC_GET_REQ = "/key/user/public/fetch";
public static final String SERV_CONNECT_REQ = "/user/connect";
public static final String SERV_DISCON_REQ = "/user/disconnect";
public static final String PASS_REQ = "/user/password/send";
public static final String USER_PUBLIC_SEND_REQ = "/key/user/add";
public static final String USER_SETTINGS_SAVE = "/user/settings/save";
public static final String USER_LIST_REQ = "/user/online/list";
public static final String SERV_PUBLIC_GET_REQ = "/key/server/public/get";
public static final String PROFILE_UP_REQ = "/user/profile/upload";
} |
package net.coobird.paint.filter;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
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;
/**
* <p>
* The {@code ImageFilterThreadingWrapper} class is a wrapper class to
* </p>
* <p>
* Note: An image with at least one dimension under 100 pixels will cause the
* {@code ImageFilterThreadingWrapper} to bypass the multithreaded rendering
* operation and@handoff the processing to the wrapped {@link ImageFilter}.
* </p>
* <p>
* At small sizes, the expected time savings from using multithreaded rendering
* is negative, as the overhead for creating threads is larger than the benefit
* of using multiple threads to render the image.
* </p>
* @author coobird
*
*/
public class ImageFilterThreadingWrapper extends ImageFilter
{
/**
* Number of pixels to overlap between the rendered quadrants.
*/
private static final int OVERLAP = 5;
private static ExecutorService es = Executors.newCachedThreadPool();
/**
* The wrapped {@code ImageFilter}.
*/
private ImageFilter filter;
/**
* Indicates whether or not multi-threaded rendering should be bypassed.
*/
private boolean bypass = false;
/**
* Cannot instantiate an {@code ThreadedWrapperFilter} without any
* arguments.
*/
private ImageFilterThreadingWrapper() {}
/**
* Instantiates a {@code ThreadedWrapperFilter} object with the specified
* {@link ImageFilter}.
* @param filter The {@code ImageFilter} to wrap.
*/
public ImageFilterThreadingWrapper(ImageFilter filter)
{
this.filter = filter;
/*
* If only one processor is available, multi-threaded processing will
* be bypassed.
*/
if (Runtime.getRuntime().availableProcessors() == 1)
{
bypass = true;
}
}
@Override
public BufferedImage processImage(BufferedImage img)
{
int width = img.getWidth();
int height = img.getHeight();
/*
* If the input size is less than 100 in any dimension, or if the
* bypass flag is set, multi-threaded rendering will be bypassed, and
* processing will be performed by the wrapped
*/
if (width < 100 || height < 100 || bypass)
{
return filter.processImage(img);
}
final int halfWidth = img.getWidth() / 2;
final int halfHeight = img.getHeight() / 2;
/*
* Prepare the source images to perform the filtering on.
* Each image has an overhang to prevent a "bordering" effect when
* stitching the images back together at the end.
*/
final BufferedImage i1 = img.getSubimage(
0,
0,
halfWidth + OVERLAP,
halfHeight + OVERLAP
);
final BufferedImage i2 = img.getSubimage(
halfWidth - OVERLAP,
0,
halfWidth + OVERLAP,
halfHeight + OVERLAP
);
final BufferedImage i3 = img.getSubimage(
0,
halfHeight - OVERLAP,
halfWidth + OVERLAP,
halfHeight + OVERLAP
);
final BufferedImage i4 = img.getSubimage(
halfWidth - OVERLAP,
halfHeight - OVERLAP,
halfWidth + OVERLAP,
halfHeight + OVERLAP
);
BufferedImage result = new BufferedImage(
img.getWidth(),
img.getHeight(),
img.getType()
);
/*
* Send off a Callable to four threads.
* Each thread will call the filter.processImage, then take a subimage
* and return that as the result.
* The subimage@is shifted to remove the overlap to eliminate the
* "bordering" effect (which occurs at the edges of an image when a
* filter is applied) which makes the resulting stitched up image to
* have borders down the horizontal and vertical center of the image.
*/
Future<BufferedImage> f1 = es.submit(new Callable<BufferedImage>() {
public BufferedImage call()
{
return filter.processImage(i1).getSubimage(
0,
0,
halfWidth,
halfHeight
);
}
});
Future<BufferedImage> f2 = es.submit(new Callable<BufferedImage>() {
public BufferedImage call()
{
return filter.processImage(i2).getSubimage(
OVERLAP,
0,
halfWidth,
halfHeight
);
}
});
Future<BufferedImage> f3 = es.submit(new Callable<BufferedImage>() {
public BufferedImage call()
{
return filter.processImage(i3).getSubimage(
0,
OVERLAP,
halfWidth,
halfHeight
);
}
});
Future<BufferedImage> f4 = es.submit(new Callable<BufferedImage>() {
public BufferedImage call()
{
return filter.processImage(i4).getSubimage(
OVERLAP,
OVERLAP,
halfWidth,
halfHeight
);
}
});
/*
* Stitch up the results from each of the four threads to make the
* resulting image.
*/
Graphics2D g = result.createGraphics();
try
{
g.drawImage(f1.get(), 0, 0, null);
g.drawImage(f2.get(), halfWidth, 0, null);
g.drawImage(f3.get(), 0, halfHeight, null);
g.drawImage(f4.get(), halfWidth, halfHeight, null);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
finally
{
g.dispose();
}
return result;
}
} |
package com.patr.radix.ui.unlock;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.xutils.common.util.LogUtil;
import com.patr.radix.LockValidateActivity;
import com.patr.radix.App;
import com.patr.radix.R;
import com.patr.radix.adapter.CommunityListAdapter;
import com.patr.radix.bean.GetCommunityListResult;
import com.patr.radix.bean.GetLockListResult;
import com.patr.radix.bean.GetWeatherResult;
import com.patr.radix.bean.MDevice;
import com.patr.radix.bean.RadixLock;
import com.patr.radix.ble.BluetoothLeService;
import com.patr.radix.bll.CacheManager;
import com.patr.radix.bll.GetCommunityListParser;
import com.patr.radix.bll.GetLockListParser;
import com.patr.radix.bll.ServiceManager;
import com.patr.radix.network.RequestListener;
import com.patr.radix.ui.WeatherActivity;
import com.patr.radix.ui.view.ListSelectDialog;
import com.patr.radix.ui.view.LoadingDialog;
import com.patr.radix.ui.view.TitleBarView;
import com.patr.radix.utils.Constants;
import com.patr.radix.utils.GattAttributes;
import com.patr.radix.utils.NetUtils;
import com.patr.radix.utils.PrefUtil;
import com.patr.radix.utils.ToastUtil;
import com.patr.radix.utils.Utils;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.utils.FileAccessor;
import com.yuntongxun.ecdemo.core.ClientUser;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecsdk.ECInitParams.LoginAuthType;
import com.yuntongxun.ecsdk.ECInitParams.LoginMode;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources.NotFoundException;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class UnlockFragment extends Fragment implements OnClickListener,
OnItemClickListener, SensorEventListener {
private Context context;
private TextView areaTv;
private ImageView weatherIv;
private TextView weatherTv;
private TextView tempTv;
private ImageButton detailBtn;
private ImageButton shakeBtn;
private TextView keyTv;
private Button sendKeyBtn;
private LinearLayout keysLl;
private CommunityListAdapter adapter;
private LoadingDialog loadingDialog;
SensorManager sensorManager = null;
Vibrator vibrator = null;
private Handler handler;
private static BluetoothAdapter mBluetoothAdapter;
private final List<MDevice> list = new ArrayList<MDevice>();
private BluetoothLeScanner bleScanner;
private boolean mScanning = false;
private BluetoothGattCharacteristic notifyCharacteristic;
private BluetoothGattCharacteristic writeCharacteristic;
private boolean notifyEnable = false;
private boolean handShake = false;
private String currentDevAddress;
private String currentDevName;
private boolean isUnlocking = false;
private boolean isDisconnectForUnlock = false;
private boolean foundDevice = false;
private int retryCount = 0;
private static final int REQUEST_FINE_LOCATION = 0;
private boolean bleReseting = false;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_unlock, container, false);
areaTv = (TextView) view.findViewById(R.id.area_tv);
weatherIv = (ImageView) view.findViewById(R.id.weather_iv);
weatherTv = (TextView) view.findViewById(R.id.weather_tv);
tempTv = (TextView) view.findViewById(R.id.temp_tv);
detailBtn = (ImageButton) view.findViewById(R.id.weather_detail_btn);
shakeBtn = (ImageButton) view.findViewById(R.id.shake_btn);
keyTv = (TextView) view.findViewById(R.id.key_tv);
sendKeyBtn = (Button) view.findViewById(R.id.send_key_btn);
keysLl = (LinearLayout) view.findViewById(R.id.key_ll);
detailBtn.setOnClickListener(this);
shakeBtn.setOnClickListener(this);
sendKeyBtn.setOnClickListener(this);
loadingDialog = new LoadingDialog(context);
init();
loadData();
return view;
}
private void init() {
sensorManager = (SensorManager) context
.getSystemService(Context.SENSOR_SERVICE);
vibrator = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
adapter = new CommunityListAdapter(context,
App.instance.getCommunities());
checkBleSupportAndInitialize();
handler = new Handler(context.getMainLooper());
context.registerReceiver(mGattUpdateReceiver,
Utils.makeGattUpdateIntentFilter());
Intent gattServiceIntent = new Intent(context.getApplicationContext(),
BluetoothLeService.class);
context.startService(gattServiceIntent);
}
/**
* BroadcastReceiver for receiving the GATT communication status
*/
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
// Status received when connected to GATT Server
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
System.out.println("
// statusTv.setText("");
LogUtil.d("");
handler.postDelayed(new Runnable() {
@Override
public void run() {
BluetoothLeService.discoverServices();
}
}, 50);
}
// Services Discovered from GATT Server
else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
.equals(action)) {
System.out.println("
// statusTv.setText();
LogUtil.d("…");
prepareGattServices(BluetoothLeService
.getSupportedGattServices());
handler.postDelayed(new Runnable() {
@Override
public void run() {
doUnlock();
}
}, 50);
} else if (action
.equals(BluetoothLeService.ACTION_GATT_DISCONNECTED)) {
System.out.println("
// connect break ()
// statusTv.setText("");
LogUtil.d("");
if (!isDisconnectForUnlock) {
handler.post(new Runnable() {
@Override
public void run() {
BluetoothLeService.close();
}
});
isUnlocking = false;
} else {
isDisconnectForUnlock = false;
}
}
// There are four basic operations for moving data in BLE: read,
// write, notify,
// and indicate. The BLE protocol specification requires that the
// maximum data
// payload size for these operations is 20 bytes, or in the case of
// read operations,
// 22 bytes. BLE is built for low power consumption, for infrequent
// short-burst data transmissions.
// Sending lots of data is possible, but usually ends up being less
// efficient than classic Bluetooth
// when trying to achieve maximum throughput.
// googleandroidnotify
Bundle extras = intent.getExtras();
if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
// Data Received
if (extras.containsKey(Constants.EXTRA_BYTE_VALUE)) {
final byte[] array = intent
.getByteArrayExtra(Constants.EXTRA_BYTE_VALUE);
LogUtil.d("" + Utils.ByteArraytoHex(array));
handle(array);
}
if (extras.containsKey(Constants.EXTRA_DESCRIPTOR_BYTE_VALUE)) {
if (extras
.containsKey(Constants.EXTRA_DESCRIPTOR_BYTE_VALUE_CHARACTERISTIC_UUID)) {
byte[] array = intent
.getByteArrayExtra(Constants.EXTRA_DESCRIPTOR_BYTE_VALUE);
// updateButtonStatus(array);
}
}
}
if (action
.equals(BluetoothLeService.ACTION_GATT_DESCRIPTORWRITE_RESULT)) {
if (extras.containsKey(Constants.EXTRA_DESCRIPTOR_WRITE_RESULT)) {
int status = extras
.getInt(Constants.EXTRA_DESCRIPTOR_WRITE_RESULT);
if (status != BluetoothGatt.GATT_SUCCESS) {
Toast.makeText(context, R.string.option_fail,
Toast.LENGTH_LONG).show();
}
}
}
if (action
.equals(BluetoothLeService.ACTION_GATT_CHARACTERISTIC_ERROR)) {
if (extras
.containsKey(Constants.EXTRA_CHARACTERISTIC_ERROR_MESSAGE)) {
String errorMessage = extras
.getString(Constants.EXTRA_CHARACTERISTIC_ERROR_MESSAGE);
System.out
.println("GattDetailActivity
+ errorMessage);
Toast.makeText(context, errorMessage, Toast.LENGTH_LONG)
.show();
}
}
// write characteristics succcess
if (action
.equals(BluetoothLeService.ACTION_GATT_CHARACTERISTIC_WRITE_SUCCESS)) {
LogUtil.d("");
}
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
// final int state =
// intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
// BluetoothDevice.ERROR);
// if (state == BluetoothDevice.BOND_BONDING) {}
// else if (state == BluetoothDevice.BOND_BONDED) {}
// else if (state == BluetoothDevice.BOND_NONE) {}
}
}
};
/**
* Getting the GATT Services
*
* @param gattServices
*/
private void prepareGattServices(List<BluetoothGattService> gattServices) {
prepareData(gattServices);
}
/**
* Prepare GATTServices data.
*
* @param gattServices
*/
private void prepareData(List<BluetoothGattService> gattServices) {
if (gattServices == null)
return;
for (BluetoothGattService gattService : gattServices) {
String uuid = gattService.getUuid().toString();
if (uuid.equals(GattAttributes.GENERIC_ACCESS_SERVICE)
|| uuid.equals(GattAttributes.GENERIC_ATTRIBUTE_SERVICE))
continue;
if (uuid.equals(GattAttributes.USR_SERVICE)) {
initCharacteristics(gattService.getCharacteristics());
notifyOption(true);
break;
}
}
}
private void handle(byte[] array) {
int size = array.length;
if (size < 6 || array[0] != (byte) 0xAA) {
// invalid msg
// if (isUnlocking) {
// retryCount++;
// if (retryCount <= 3) {
// doUnlock();
// } else {
// ToastUtil.showShort(context, "");
// disconnectDevice();
return;
}
byte cmd = array[2];
int len;
switch (cmd) {
case Constants.UNLOCK:
len = array[3];
if (size < 6 + len || array[len + 5] != (byte) 0xDD) {
// invalid msg
if (isUnlocking) {
LogUtil.d("");
ToastUtil.showShort(context, "");
disconnectDevice();
loadingDialog.dismiss();
}
} else {
byte check = array[1];
check = (byte) (check ^ cmd ^ array[3]);
for (int i = 0; i < len; i++) {
check ^= array[i + 4];
}
if (check == array[len + 4]) {
// check pass
if (array[4] == 0x00) {
ToastUtil.showShort(context, "");
disconnectDevice();
loadingDialog.dismiss();
} else {
if (isUnlocking) {
LogUtil.d("");
ToastUtil.showShort(context, "");
disconnectDevice();
loadingDialog.dismiss();
}
}
} else {
// check fail
if (isUnlocking) {
LogUtil.d("");
ToastUtil.showShort(context, "");
disconnectDevice();
loadingDialog.dismiss();
}
}
}
break;
default:
// INVALID REQUEST/RESPONSE.
break;
// case Constants.HAND_SHAKE:
// if (size < 5 || array[4] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// if ((cmd ^ array[2]) == array[3]) {
// if (array[2] == (byte) 0x00) {
// handShake = true;
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// } else {
// // checkFailed();
// break;
// case Constants.READ_CARD:
// if (size < 12 || array[11] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// for (int i = 2; i < 10; i++) {
// if (array[i] != (byte) 0x00) {
// // checkFailed();
// writeOption("90 ", "FF 00 00 00 00 00 00 00 00 ");
// return;
// byte check = cmd;
// for (int i = 2; i < 10; i++) {
// check ^= array[i];
// if (check == array[10]) {
// if (handShake) {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("90 ", "00 00 00 00 00 " +
// MyApplication.instance.getCardNum());
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("90 ", "FF 00 00 00 00 00 00 00 00 ");
// } else {
// // checkFailed();
// writeOption("90 ", "FF 00 00 00 00 00 00 00 00 ");
// break;
// case Constants.WRITE_CARD:
// if (size < 12 || array[11] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// for (int i = 2; i < 6; i++) {
// if (array[i] != (byte) 0x00) {
// // checkFailed();
// writeOption("91 ", "FF 00 00 00 00 00 00 00 00 ");
// return;
// byte check = cmd;
// for (int i = 2; i < 10; i++) {
// check ^= array[i];
// if (check == array[10]) {
// if (handShake) {
// byte[] cn = new byte[4];
// for (int i = 0; i < 4; i++) {
// cn[i] = array[i + 6];
// MyApplication.instance.setCardNum(Utils.ByteArraytoHex(cn));
// MyApplication.instance.setCsn(MyApplication.instance.getCardNum());
// // messageEt.append("" + cardNum + "\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("91 ", "00 ");
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("91 ", "FF ");
// } else {
// // checkFailed();
// writeOption("91 ", "FF ");
// break;
// case Constants.DISCONNECT:
// if (size < 12 || array[11] != (byte) 0xDD) {
// // invalidMsg();
// } else {
// for (int i = 2; i < 10; i++) {
// if (array[i] != (byte) 0x00) {
// // checkFailed();
// writeOption("A0 ", "FF ");
// return;
// byte check = cmd;
// for (int i = 2; i < 10; i++) {
// check ^= array[i];
// if (check == array[10]) {
// if (handShake) {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("A0 ", "00 ");
// handShake = false;
// } else {
// // messageEt.append("\n");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// writeOption("A0 ", "FF ");
// } else {
// // checkFailed();
// writeOption("A0 ", "FF ");
// break;
// default:
// // messageEt.append("INVALID REQUEST/RESPONSE.");
// // messageEt.setSelection(messageEt.getText().length(),
// // messageEt.getText().length());
// break;
}
}
private void doUnlock() {
writeOption("30 ", "06 00 00 " + App.instance.getUserInfo().getCardNo());
}
private void writeOption(String cmd, String data) {
writeOption(Utils.getCmdData("00 ", cmd, data));
}
private void writeOption(String hexStr) {
writeCharacteristic(writeCharacteristic,
Utils.getCmdDataByteArray(hexStr));
}
private void writeCharacteristic(
BluetoothGattCharacteristic characteristic, byte[] bytes) {
// Writing the hexValue to the characteristics
try {
LogUtil.d("write bytes: " + Utils.ByteArraytoHex(bytes));
BluetoothLeService.writeCharacteristicGattDb(characteristic, bytes);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void initCharacteristics(
List<BluetoothGattCharacteristic> characteristics) {
for (BluetoothGattCharacteristic c : characteristics) {
if (Utils.getPorperties(context, c).equals("Notify")) {
notifyCharacteristic = c;
continue;
}
if (Utils.getPorperties(context, c).equals("Write")) {
writeCharacteristic = c;
continue;
}
}
}
private void notifyOption(boolean enabled) {
if (notifyEnable && !enabled) {
notifyEnable = false;
stopBroadcastDataNotify(notifyCharacteristic);
} else if (!notifyEnable && enabled) {
notifyEnable = true;
prepareBroadcastDataNotify(notifyCharacteristic);
}
}
/**
* Preparing Broadcast receiver to broadcast notify characteristics
*
* @param characteristic
*/
void prepareBroadcastDataNotify(BluetoothGattCharacteristic characteristic) {
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
BluetoothLeService.setCharacteristicNotification(characteristic,
true);
}
}
/**
* Stopping Broadcast receiver to broadcast notify characteristics
*
* @param characteristic
*/
void stopBroadcastDataNotify(BluetoothGattCharacteristic characteristic) {
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
BluetoothLeService.setCharacteristicNotification(characteristic,
false);
}
}
private void connectDevice(BluetoothDevice device) {
currentDevAddress = device.getAddress();
currentDevName = device.getName();
LogUtil.d("connectDevice: DevName = " + currentDevName
+ "; DevAddress = " + currentDevAddress);
if (BluetoothLeService.getConnectionState() != BluetoothLeService.STATE_DISCONNECTED) {
isDisconnectForUnlock = true;
BluetoothLeService.disconnect();
handler.postDelayed(new Runnable() {
@Override
public void run() {
BluetoothLeService.connect(currentDevAddress,
currentDevName, context);
}
}, 300);
} else {
BluetoothLeService.connect(currentDevAddress, currentDevName,
context);
}
}
private void disconnectDevice() {
notifyOption(false);
isDisconnectForUnlock = false;
handler.postDelayed(new Runnable() {
@Override
public void run() {
BluetoothLeService.disconnect();
}
}, 50);
}
private void loadData() {
if (App.instance.getSelectedCommunity() == null) {
getCommunityList();
return;
}
if (!TextUtils.isEmpty(App.instance.getMyMobile())) {
String appKey = FileAccessor.getAppKey();
String token = FileAccessor.getAppToken();
String myMobile = App.instance.getMyMobile();
String pass = "";
ClientUser clientUser = new ClientUser(myMobile);
clientUser.setAppKey(appKey);
clientUser.setAppToken(token);
clientUser.setLoginAuthType(LoginAuthType.NORMAL_AUTH);
clientUser.setPassword(pass);
CCPAppManager.setClientUser(clientUser);
SDKCoreHelper.init(App.instance, LoginMode.FORCE_LOGIN);
}
}
private void getWeather() {
ServiceManager.getWeather(new RequestListener<GetWeatherResult>() {
@Override
public void onStart() {
}
@Override
public void onSuccess(int stateCode, GetWeatherResult result) {
if (result.getErrorCode().equals("0")) {
refreshWeather(result);
} else {
// ToastUtil.showShort(context, result.getReason());
}
}
@Override
public void onFailure(Exception error, String content) {
ToastUtil.showShort(context, "");
}
});
}
private void refreshWeather(GetWeatherResult result) {
Field f;
try {
f = (Field) R.drawable.class.getDeclaredField("ww"
+ result.getImg());
int id = f.getInt(R.drawable.class);
weatherIv.setImageResource(id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
weatherTv.setText(result.getWeather());
tempTv.setText(result.getTemp() + "℃");
areaTv.setText(result.getCity());
}
private void getCommunityList() {
switch (NetUtils.getConnectedType(context)) {
case NONE:
getCommunityListFromCache();
break;
case WIFI:
case OTHER:
getCommunityListFromServer();
break;
default:
break;
}
}
private void getCommunityListFromCache() {
CacheManager.getCacheContent(context,
CacheManager.getCommunityListUrl(),
new RequestListener<GetCommunityListResult>() {
@Override
public void onSuccess(int stateCode,
GetCommunityListResult result) {
if (result != null) {
App.instance.setCommunities(result.getCommunities());
adapter.notifyDataSetChanged();
ListSelectDialog.show(context, "", adapter,
UnlockFragment.this);
}
}
}, new GetCommunityListParser());
}
private void getCommunityListFromServer() {
ServiceManager
.getCommunityList(new RequestListener<GetCommunityListResult>() {
@Override
public void onSuccess(int stateCode,
GetCommunityListResult result) {
if (result != null) {
if (result.isSuccesses()) {
App.instance.setCommunities(result
.getCommunities());
saveCommunityListToDb(result.getResponse());
adapter.notifyDataSetChanged();
ListSelectDialog.show(context, "",
adapter, UnlockFragment.this);
} else {
// ToastUtil.showShort(context,
// result.getRetinfo());
getCommunityListFromCache();
}
} else {
getCommunityListFromCache();
}
}
@Override
public void onFailure(Exception error, String content) {
getCommunityListFromCache();
}
});
}
/**
*
*
* @param content
*/
protected void saveCommunityListToDb(String content) {
CacheManager.saveCacheContent(context,
CacheManager.getCommunityListUrl(), content,
new RequestListener<Boolean>() {
@Override
public void onSuccess(Boolean result) {
LogUtil.i("save " + CacheManager.getCommunityListUrl()
+ "=" + result);
}
});
}
private void getLockList() {
if (!TextUtils.isEmpty(App.instance.getUserInfo().getToken())) {
switch (NetUtils.getConnectedType(context)) {
case NONE:
getLockListFromCache();
break;
case WIFI:
case OTHER:
getLockListFromServer();
break;
default:
break;
}
} else if (App.firstRequest) {
ToastUtil.showShort(context, "");
App.firstRequest = false;
}
}
private void getLockListFromCache() {
if (App.instance.getSelectedCommunity() != null) {
CacheManager.getCacheContent(context,
CacheManager.getLockListUrl(),
new RequestListener<GetLockListResult>() {
@Override
public void onSuccess(int stateCode,
GetLockListResult result) {
if (result != null) {
App.instance.setLocks(result.getLocks());
setSelectedKey();
refreshKey();
}
}
}, new GetLockListParser());
}
}
private void getLockListFromServer() {
if (App.instance.getSelectedCommunity() != null) {
ServiceManager
.getLockList(new RequestListener<GetLockListResult>() {
@Override
public void onSuccess(int stateCode,
GetLockListResult result) {
if (result != null) {
if (result.isSuccesses()) {
App.instance.setLocks(result.getLocks());
saveLockListToDb(result.getResponse());
setSelectedKey();
refreshKey();
} else {
// ToastUtil.showShort(context,
// result.getRetinfo());
getLockListFromCache();
}
} else {
getLockListFromCache();
}
}
@Override
public void onFailure(Exception error, String content) {
getLockListFromCache();
}
});
}
}
/**
*
*
* @param content
*/
protected void saveLockListToDb(String content) {
CacheManager.saveCacheContent(context, CacheManager.getLockListUrl(),
content, new RequestListener<Boolean>() {
@Override
public void onSuccess(Boolean result) {
LogUtil.i("save " + CacheManager.getLockListUrl() + "="
+ result);
}
});
}
private void refreshKey() {
RadixLock selectedKey = App.instance.getSelectedLock();
if (selectedKey != null) {
keyTv.setText(selectedKey.getName());
}
keysLl.removeAllViews();
final List<RadixLock> keys = App.instance.getLocks();
int size = keys.size();
for (int i = 0; i < size; i++) {
KeyView keyView;
if (keys.get(i).equals(selectedKey)) {
keyView = new KeyView(context, keys.get(i), i, true);
} else {
keyView = new KeyView(context, keys.get(i), i, false);
}
keyView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int idx = (int) v.getTag();
if (!keys.get(idx).equals(App.instance.getSelectedLock())) {
App.instance.setSelectedLock(keys.get(idx));
refreshKey();
}
}
});
keysLl.addView(keyView);
}
}
private void setSelectedKey() {
String selectedKey = PrefUtil.getString(context,
Constants.PREF_SELECTED_KEY);
for (RadixLock lock : App.instance.getLocks()) {
if (selectedKey.equals(lock.getId())) {
App.instance.setSelectedLock(lock);
return;
}
}
if (App.instance.getLocks().size() > 0) {
App.instance.setSelectedLock(App.instance.getLocks().get(0));
}
}
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
}
@Override
public void onResume() {
super.onResume();
if (PrefUtil.getBoolean(context, Constants.PREF_SHAKE_SWITCH, true)) {
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
getWeather();
getLockList();
}
@Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onDestroy() {
super.onDestroy();
context.unregisterReceiver(mGattUpdateReceiver);
if (loadingDialog.isShowing()) {
loadingDialog.dismiss();
}
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.weather_detail_btn:
case R.id.weather_rl:
context.startActivity(new Intent(context, WeatherActivity.class));
break;
case R.id.send_key_btn:
context.startActivity(new Intent(context, MyKeysActivity.class));
break;
case R.id.shake_btn:
preUnlock();
break;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
App.instance.setSelectedCommunity(adapter.getItem(position));
if (!adapter.isSelect(position)) {
App.instance.setSelectedLock(null);
getLockList();
}
adapter.select(position);
}
@Override
public void onSensorChanged(SensorEvent event) {
int sensorType = event.sensor.getType();
// values[0]:Xvalues[1]Yvalues[2]Z
float[] values = event.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER) {
if ((Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || Math
.abs(values[2]) > 17)) {
LogUtil.d("============ values[0] = " + values[0]);
LogUtil.d("============ values[1] = " + values[1]);
LogUtil.d("============ values[2] = " + values[2]);
vibrator.vibrate(500);
preUnlock();
}
}
}
private void preUnlock() {
RadixLock lock = App.instance.getSelectedLock();
LogUtil.d("preUnlock: lock = " + lock.getBleName1());
if (lock != null) {
String lockPaternStr = PrefUtil.getString(context,
Constants.PREF_LOCK_KEY, null);
if (!TextUtils.isEmpty(lockPaternStr)) {
LockValidateActivity.startForResult(this, Constants.LOCK_CHECK);
} else {
unlock();
}
} else {
ToastUtil.showShort(context, "");
}
}
private void unlock() {
if (mBluetoothAdapter == null) {
getBluetoothAdapter();
}
if (!mBluetoothAdapter.isEnabled()) {
if (bleReseting) {
ToastUtil.showLong(context, "");
} else {
ToastUtil.showLong(context, "");
}
return;
}
if (!isUnlocking) {
isUnlocking = true;
retryCount = 0;
RadixLock lock = App.instance.getSelectedLock();
LogUtil.d("unlock: inBleName = " + lock.getBleName1()
+ ", outBleName = " + lock.getBleName2());
loadingDialog.show("…");
startScan();
}
}
private void checkBleSupportAndInitialize() {
// Use this check to determine whether BLE is supported on the device.
if (!context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show();
return;
}
// Initializes a Blue tooth adapter.
getBluetoothAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Blue tooth
Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
}
private void bleReset() {
// Initializes a Blue tooth adapter.
getBluetoothAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Blue tooth
Toast.makeText(context, "BLE", Toast.LENGTH_SHORT).show();
return;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
bleReseting = true;
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
bleReseting = false;
}
}
}, 8000);
}
private void getBluetoothAdapter() {
final BluetoothManager bluetoothManager = (BluetoothManager) context
.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
/**
* Call back for BLE Scan This call back is called when a BLE device is
* found near by.
*/
private LeScanCallback mLeScanCallback = new LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
byte[] scanRecord) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
MDevice mDev = new MDevice(device, rssi);
if (list.contains(mDev)) {
return;
}
list.add(mDev);
String name = mDev.getDevice().getName();
LogUtil.d("" + name);
if (name == null) {
return;
}
RadixLock lock = App.instance.getSelectedLock();
if (name.equals(lock.getBleName1())
|| name.equals(lock.getBleName2())) {
if (!foundDevice) {
foundDevice = true;
isUnlocking = true;
LogUtil.d("……");
new Thread() {
int time = 0;
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
loadingDialog.show("…");
}
});
while (isUnlocking) {
try {
sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time += 50;
if (time >= 8000) {
break;
}
}
if (isUnlocking) {
isUnlocking = false;
bleReset();
}
handler.post(new Runnable() {
@Override
public void run() {
loadingDialog.dismiss();
}
});
}
}.start();
handler.postDelayed(new Runnable() {
@Override
public void run() {
connectDevice(device);
}
}, 50);
}
}
}
});
}
};
@SuppressLint("NewApi")
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
final MDevice mDev = new MDevice(result.getDevice(),
result.getRssi());
if (list.contains(mDev)) {
return;
}
list.add(mDev);
String name = mDev.getDevice().getName();
LogUtil.d("" + name);
if (name == null) {
return;
}
RadixLock lock = App.instance.getSelectedLock();
if (name.equals(lock.getBleName1())
|| name.equals(lock.getBleName2())) {
if (!foundDevice) {
foundDevice = true;
isUnlocking = true;
LogUtil.d("……");
loadingDialog.show("…");
handler.postDelayed(new Runnable() {
@Override
public void run() {
connectDevice(mDev.getDevice());
}
}, 50);
new Thread() {
int time = 0;
@Override
public void run() {
while (isUnlocking) {
try {
sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
time += 50;
if (time >= 8000) {
break;
}
}
if (isUnlocking) {
handler.post(new Runnable() {
@Override
public void run() {
BluetoothLeService.close();
isUnlocking = false;
bleReset();
}
});
}
handler.post(new Runnable() {
@Override
public void run() {
loadingDialog.dismiss();
}
});
}
}.start();
}
}
}
};
private void startScan() {
list.clear();
foundDevice = false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
scanPrevious21Version();
} else {
scanAfter21Version();
}
}
private void scanPrevious21Version() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mBluetoothAdapter != null) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
if (!foundDevice) {
ToastUtil.showShort(context, "");
loadingDialog.dismiss();
isUnlocking = false;
}
mScanning = false;
}
}, 3000);
if (mBluetoothAdapter == null) {
getBluetoothAdapter();
}
if (mBluetoothAdapter != null) {
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void scanAfter21Version() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (bleScanner != null) {
bleScanner.stopScan(mScanCallback);
}
if (!foundDevice) {
// ToastUtil.showShort(context, "");
loadingDialog.dismiss();
isUnlocking = false;
}
mScanning = false;
}
}, 3000);
if (bleScanner == null) {
if (mBluetoothAdapter == null) {
getBluetoothAdapter();
}
bleScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
if (bleScanner != null) {
mScanning = true;
bleScanner.startScan(mScanCallback);
}
}
// @TargetApi(Build.VERSION_CODES.M)
// private void mayRequestLocation() {
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// ToastUtil.showLong(context, "Android 6.0");
// REQUEST_FINE_LOCATION);
// return;
// } else {
// } else {
// @Override
// switch (requestCode) {
// case REQUEST_FINE_LOCATION:
// // If request is cancelled, the result arrays are empty.
// if (grantResults.length > 0
// if (mScanning == false) {
// startScan();
// } else {
// break;
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constants.LOCK_CHECK) {
if (resultCode == Constants.LOCK_CHECK_OK) {
unlock();
} else {
ToastUtil.showShort(context, "");
}
}
}
} |
package net.sf.jaer.eventprocessing.filter;
import java.util.SplittableRandom;
import com.google.common.collect.EvictingQueue;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.jogamp.opengl.util.gl2.GLUT;
import java.awt.Color;
import java.awt.Font;
import java.beans.PropertyChangeEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.RemoteControlCommand;
import net.sf.jaer.util.RemoteControlled;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.eventio.AEFileInputStream;
import net.sf.jaer.graphics.ChipDataFilePreview;
import net.sf.jaer.graphics.DavisRenderer;
import net.sf.jaer.util.DATFileFilter;
import net.sf.jaer.util.DrawGL;
import org.apache.commons.lang3.ArrayUtils;
/**
* Filter for testing noise filters
*
* @author Tobi Delbruck, Shasha Guo, Oct-Jan 2020
*/
@Description("Tests background BA denoising filters by injecting known noise and measuring how much signal and noise is filtered")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class NoiseTesterFilter extends AbstractNoiseFilter implements FrameAnnotater, RemoteControlled {
public static final int MAX_NUM_RECORDED_EVENTS = 10_0000_0000;
public static final float MAX_TOTAL_NOISE_RATE_HZ = 50e6f;
public static final float RATE_LIMIT_HZ = 25; //per pixel, separately for leak and shot rates
private FilterChain chain;
private float shotNoiseRateHz = getFloat("shotNoiseRateHz", .1f);
private float leakNoiseRateHz = getFloat("leakNoiseRateHz", .1f);
private float poissonDtUs = 1;
private float shotOffThresholdProb; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
private float shotOnThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
private float leakOnThresholdProb; // bounds for samppling Poisson noise
private PrerecordedNoise prerecordedNoise = null;
private ROCHistory rocHistory = new ROCHistory();
private static String DEFAULT_CSV_FILENAME_BASE = "NoiseTesterFilter";
private String csvFileName = getString("csvFileName", DEFAULT_CSV_FILENAME_BASE);
private File csvFile = null;
private BufferedWriter csvWriter = null;
// chip size values, set in initFilter()
private int sx = 0;
private int sy = 0;
private Integer lastTimestampPreviousPacket = null, firstSignalTimestmap = null; // use Integer Object so it can be null to signify no value yet
private float TPR = 0;
private float TPO = 0;
private float TNR = 0;
private float accuracy = 0;
private float BR = 0;
float inSignalRateHz = 0, inNoiseRateHz = 0, outSignalRateHz = 0, outNoiseRateHz = 0;
// private EventPacket<ApsDvsEvent> signalAndNoisePacket = null;
private final SplittableRandom random = new SplittableRandom();
private EventPacket<BasicEvent> signalAndNoisePacket = null;
// private EventList<BasicEvent> noiseList = new EventList();
private AbstractNoiseFilter[] noiseFilters = null;
private AbstractNoiseFilter selectedFilter = null;
protected boolean resetCalled = true; // flag to reset on next event
// private float annotateAlpha = getFloat("annotateAlpha", 0.5f);
private DavisRenderer renderer = null;
private boolean overlayPositives = getBoolean("overlayPositives", false);
private boolean overlayNegatives = getBoolean("overlayNegatives", false);
private int rocHistoryLength = getInt("rocHistoryLength", 1);
private final int LIST_LENGTH = 10000;
private ArrayList<FilteredEventWithNNb> tpList = new ArrayList(LIST_LENGTH),
fnList = new ArrayList(LIST_LENGTH),
fpList = new ArrayList(LIST_LENGTH),
tnList = new ArrayList(LIST_LENGTH); // output of classification
private ArrayList<BasicEvent> noiseList = new ArrayList<BasicEvent>(LIST_LENGTH); // TODO make it lazy, when filter is enabled
private NNbHistograms nnbHistograms = new NNbHistograms(); // tracks stats of neighbors to events when they are filtered in or out
public enum NoiseFilterEnum {
BackgroundActivityFilter, SpatioTemporalCorrelationFilter, DoubleWindowFilter, OrderNBackgroundActivityFilter, MedianDtFilter
}
private NoiseFilterEnum selectedNoiseFilterEnum = NoiseFilterEnum.valueOf(getString("selectedNoiseFilter", NoiseFilterEnum.BackgroundActivityFilter.toString())); //default is BAF
private float correlationTimeS = getFloat("correlationTimeS", 20e-3f);
private volatile boolean stopMe = false; // to interrupt if filterPacket takes too long
private final long MAX_FILTER_PROCESSING_TIME_MS = 5000; // times out to avoid using up all heap
private TextRenderer textRenderer = null;
public NoiseTesterFilter(AEChip chip) {
super(chip);
String out = "5. Output";
String noise = "4. Noise";
setPropertyTooltip(noise, "shotNoiseRateHz", "rate per pixel of shot noise events");
setPropertyTooltip(noise, "leakNoiseRateHz", "rate per pixel of leak noise events");
setPropertyTooltip(noise, "openNoiseSourceRecording", "Open a pre-recorded AEDAT file as noise source.");
setPropertyTooltip(noise, "closeNoiseSourceRecording", "Closes the pre-recorded noise input.");
setPropertyTooltip(out, "closeCsvFile", "Closes the output spreadsheet data file.");
setPropertyTooltip(out, "csvFileName", "Enter a filename base here to open CSV output file (appending to it if it already exists)");
setPropertyTooltip(TT_FILT_CONTROL, "selectedNoiseFilterEnum", "Choose a noise filter to test");
// setPropertyTooltip(ann, "annotateAlpha", "Sets the transparency for the annotated pixels. Only works for Davis renderer.");
setPropertyTooltip(TT_DISP, "overlayPositives", "<html><p>Overlay positives (passed input events)<p>FPs (red) are noise in output.<p>TPs (green) are signal in output.");
setPropertyTooltip(TT_DISP, "overlayNegatives", "<html><p>Overlay negatives (rejected input events)<p>TNs (green) are noise filtered out.<p>FNs (red) are signal filtered out.");
setPropertyTooltip(TT_DISP, "rocHistoryLength", "Number of samples of ROC point to show.");
setPropertyTooltip(TT_DISP, "clearROCHistory", "Clears samples from display.");
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
boolean wasEnabled = this.filterEnabled;
this.filterEnabled = yes;
if (yes) {
resetFilter();
for (EventFilter2D f : chain) {
if (selectedFilter != null && selectedFilter == f) {
f.setFilterEnabled(yes);
}
}
} else {
for (EventFilter2D f : chain) {
f.setFilterEnabled(false);
}
if (renderer != null) {
renderer.clearAnnotationMap();
}
}
if (!isEnclosed()) {
String key = prefsEnabledKey();
getPrefs().putBoolean(key, this.filterEnabled);
}
support.firePropertyChange("filterEnabled", wasEnabled, this.filterEnabled);
}
private int rocSampleCounter = 0;
private final int ROC_LABEL_TAU_INTERVAL = 30;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
String s = null;
float x, y;
if (!showFilteringStatistics) {
return;
}
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 10));
}
final GLUT glut = new GLUT();
GL2 gl = drawable.getGL().getGL2();
rocHistory.draw(gl);
gl.glPushMatrix();
gl.glColor3f(.2f, .2f, .8f); // must set color before raster position (raster position is like glVertex)
gl.glRasterPos3f(0, sy * .9f, 0);
String overlayString = "Overlay ";
if (overlayNegatives) {
overlayString += "negatives: FN (green), TN (red)";
}
if (overlayPositives) {
overlayString += "positives: TP (green), FP (red)";
}
if ((!overlayPositives) && (!overlayNegatives)) {
overlayString += "None";
}
if (prerecordedNoise != null) {
s = String.format("NTF: Precorded noise from %s. %s", prerecordedNoise.file.getName(),
overlayString);
} else {
s = String.format("NTF: Synthetic noise: Leak %sHz, Shot %sHz. %s", eng.format(leakNoiseRateHz), eng.format(shotNoiseRateHz),
overlayString);
}
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, getAnnotationRasterYPosition("NTF"), 0);
s = String.format("TPR=%6.1f%% TNR=%6.1f%% TPO=%6.1f%%, dT=%.2fus", 100 * TPR, 100 * TNR, 100 * TPO, poissonDtUs);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, getAnnotationRasterYPosition("NTF") + 10, 0);
s = String.format("In sigRate=%s noiseRate=%s, Out sigRate=%s noiseRate=%s Hz", eng.format(inSignalRateHz), eng.format(inNoiseRateHz), eng.format(outSignalRateHz), eng.format(outNoiseRateHz));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glPopMatrix();
// nnbHistograms.draw(gl); shows neighbor distributions, not informative
}
private void annotateNoiseFilteringEvents(ArrayList<FilteredEventWithNNb> outSig, ArrayList<FilteredEventWithNNb> outNoise) {
if (renderer == null) {
return;
}
renderer.clearAnnotationMap();
final int offset = 1;
// final float a = getAnnotateAlpha();
final float[] noiseColor = {1f, 0, 0, 1}, sigColor = {0, 1f, 0, 1};
for (FilteredEventWithNNb e : outSig) {
renderer.setAnnotateColorRGBA(e.e.x + 2 >= sx ? e.e.x : e.e.x + offset, e.e.y - 2 < 0 ? e.e.y : e.e.y - offset, sigColor);
}
for (FilteredEventWithNNb e : outNoise) {
renderer.setAnnotateColorRGBA(e.e.x + 2 >= sx ? e.e.x : e.e.x + offset, e.e.y - 2 < 0 ? e.e.y : e.e.y - offset, noiseColor);
// renderer.setAnnotateColorRGBA(e.x+2, e.y-2, noiseColor);
}
}
private class BackwardsTimestampException extends Exception {
public BackwardsTimestampException(String string) {
super(string);
}
}
private ArrayList<BasicEvent> createEventList(EventPacket<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.getSize());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
private ArrayList<BasicEvent> createEventList(List<BasicEvent> p) throws BackwardsTimestampException {
ArrayList<BasicEvent> l = new ArrayList(p.size());
BasicEvent pe = null;
for (BasicEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
l.add(e);
pe = e;
}
return l;
}
private final boolean checkStopMe(String where) {
if (stopMe) {
log.severe(where + "\n: Processing took longer than " + MAX_FILTER_PROCESSING_TIME_MS + "ms, disabling filter");
setFilterEnabled(false);
return true;
}
return false;
}
/**
* Finds the intersection of events in a that are in b. Assumes packets are
* non-monotonic in timestamp ordering. Handles duplicates. Each duplicate
* is matched once. The matching is by event .equals() method.
*
* @param a ArrayList<BasicEvent> of a
* @param b likewise, but is list of events with NNb bits in byte
* @param intersect the target list to fill with intersections, include NNb
* bits
* @return count of intersections
*/
private int countIntersect(ArrayList<BasicEvent> a, ArrayList<FilteredEventWithNNb> b, ArrayList<FilteredEventWithNNb> intersect) {
intersect.clear();
if (a.isEmpty() || b.isEmpty()) {
return 0;
}
int count = 0;
// TODO test case
// a = new ArrayList();
// b = new ArrayList();
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 0, (short) 0));
// a.add(new BasicEvent(4, (short) 1, (short) 0));
// a.add(new BasicEvent(4, (short) 2, (short) 0));
//// a.add(new BasicEvent(2, (short) 0, (short) 0));
//// a.add(new BasicEvent(10, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(2, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 0, (short) 0));
// b.add(new BasicEvent(4, (short) 1, (short) 0));
// b.add(new BasicEvent(10, (short) 0, (short) 0));
int i = 0, j = 0;
final int na = a.size(), nb = b.size();
while (i < na && j < nb) {
if (a.get(i).timestamp < b.get(j).e.timestamp) {
i++;
} else if (b.get(j).e.timestamp < a.get(i).timestamp) {
j++;
} else {
// If timestamps equal, it mmight be identical events or maybe not
// and there might be several events with identical timestamps.
// We MUST match all a with all b.
// We don't want to increment both pointers or we can miss matches.
// We do an inner double loop for exhaustive matching as long as the timestamps
// are identical.
int i1 = i, j1 = j;
while (i1 < na && j1 < nb && a.get(i1).timestamp == b.get(j1).e.timestamp) {
boolean match = false;
while (j1 < nb && i1 < na && a.get(i1).timestamp == b.get(j1).e.timestamp) {
if (a.get(i1).equals(b.get(j1).e)) {
count++;
intersect.add(b.get(j1)); // TODO debug
// we have a match, so use up the a element
i1++;
match = true;
}
j1++;
}
if (!match) {
i1++;
}
j1 = j; // reset j to start of matching ts region
}
i = i1; // when done, timestamps are different or we reached end of either or both arrays
j = j1;
}
}
// System.out.println("%%%%%%%%%%%%%%");
// printarr(a, "a");
// printarr(b, "b");
// printarr(intersect, "intsct");
return count;
}
// TODO test case
private void printarr(ArrayList<BasicEvent> a, String n) {
final int MAX = 30;
if (a.size() > MAX) {
System.out.printf("
return;
}
System.out.printf("%s[%d]
for (int i = 0; i < a.size(); i++) {
BasicEvent e = a.get(i);
System.out.printf("%s[%d]=[%d %d %d %d]\n", n, i, e.timestamp, e.x, e.y, (e instanceof PolarityEvent) ? ((PolarityEvent) e).getPolaritySignum() : 0);
}
}
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
totalEventCount = 0; // from super, to measure filtering
filteredOutEventCount = 0;
int TP = 0; // filter take real events as real events. the number of events
int TN = 0; // filter take noise events as noise events
int FP = 0; // filter take noise events as real events
int FN = 0; // filter take real events as noise events
if (in == null || in.isEmpty()) {
// log.warning("empty packet, cannot inject noise");
return in;
}
stopMe = false;
Timer stopper = new Timer("NoiseTesterFilter.Stopper", true);
stopper.schedule(new TimerTask() {
@Override
public void run() {
stopMe = true;
}
}, MAX_FILTER_PROCESSING_TIME_MS);
BasicEvent firstE = in.getFirstEvent();
if (firstSignalTimestmap == null) {
firstSignalTimestmap = firstE.timestamp;
}
if (resetCalled) {
resetCalled = false;
int ts = in.getLastTimestamp(); // we use getLastTimestamp because getFirstTimestamp contains event from BEFORE the rewind :-(
// initialize filters with lastTimesMap to Poisson waiting times
log.info("initializing timestamp maps with Poisson process waiting times");
for (AbstractNoiseFilter f : noiseFilters) {
int[][] map = f.getLastTimesMap();
if (map != null) {
initializeLastTimesMapForNoiseRate(map, shotNoiseRateHz + leakNoiseRateHz, ts); // TODO move to filter so that each filter can initialize its own map
}
}
}
// copy input events to inList
ArrayList<BasicEvent> signalList;
try {
signalList = createEventList((EventPacket<BasicEvent>) in);
} catch (BackwardsTimestampException ex) {
log.warning(String.format("%s: skipping nonmonotonic packet [%s]", ex, in));
return in;
}
assert signalList.size() == in.getSizeNotFilteredOut() : String.format("signalList size (%d) != in.getSizeNotFilteredOut() (%d)", signalList.size(), in.getSizeNotFilteredOut());
// add noise into signalList to get the outputPacketWithNoiseAdded, track noise in noiseList
noiseList.clear();
addNoise(in, signalAndNoisePacket, noiseList, shotNoiseRateHz, leakNoiseRateHz);
// we need to copy the augmented event packet to a HashSet for use with Collections
ArrayList<BasicEvent> signalAndNoiseList;
try {
signalAndNoiseList = createEventList((EventPacket<BasicEvent>) signalAndNoisePacket);
// filter the augmented packet
// make sure to record events, turned off by default for normal use
for (EventFilter2D f : getEnclosedFilterChain()) {
((AbstractNoiseFilter) f).setRecordFilteredOutEvents(true);
}
EventPacket<BasicEvent> passedSignalAndNoisePacket = (EventPacket<BasicEvent>) getEnclosedFilterChain().filterPacket(signalAndNoisePacket);
ArrayList<FilteredEventWithNNb> negativeList = selectedFilter.getNegativeEvents();
ArrayList<FilteredEventWithNNb> positiveList = selectedFilter.getPositiveEvents();
// make a list of the output packet, which has noise filtered out by selected filter
ArrayList<BasicEvent> passedSignalAndNoiseList = createEventList(passedSignalAndNoisePacket);
assert (signalList.size() + noiseList.size() == signalAndNoiseList.size());
// now we sort out the mess
TP = countIntersect(signalList, positiveList, tpList); // True positives: Signal that was correctly retained by filtering
updateNnbHistograms(Classification.TP, tpList);
if (checkStopMe("after TP")) {
return in;
}
FN = countIntersect(signalList, negativeList, fnList); // False negatives: Signal that was incorrectly removed by filter.
updateNnbHistograms(Classification.FN, fnList);
if (checkStopMe("after FN")) {
return in;
}
FP = countIntersect(noiseList, positiveList, fpList); // False positives: Noise that is incorrectly passed by filter
updateNnbHistograms(Classification.FP, fpList);
if (checkStopMe("after FP")) {
return in;
}
TN = countIntersect(noiseList, negativeList, tnList); // True negatives: Noise that was correctly removed by filter
updateNnbHistograms(Classification.TN, tnList);
if (checkStopMe("after TN")) {
return in;
}
stopper.cancel();
// if (TN + FP != noiseList.size()) {
// System.err.println(String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size()));
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert (TN + FP == noiseList.size()) : String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size());
totalEventCount = signalAndNoiseList.size();
int outputEventCount = passedSignalAndNoiseList.size();
filteredOutEventCount = totalEventCount - outputEventCount;
// if (TP + FP != outputEventCount) {
// System.err.printf("@@@@@@@@@ TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
assert TP + FP == outputEventCount : String.format("TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// if (TP + TN + FP + FN != totalEventCount) {
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
assert TP + TN + FP + FN == totalEventCount : String.format("TP (%d) + TN (%d) + FP (%d) + FN (%d) = %d != totalEventCount (%d)", TP, TN, FP, FN, TP + TN + FP + FN, totalEventCount);
assert TN + FN == filteredOutEventCount : String.format("TN (%d) + FN (%d) = %d != filteredOutEventCount (%d)", TN, FN, TN + FN, filteredOutEventCount);
// System.out.printf("every packet is: %d %d %d %d %d, %d %d %d: %d %d %d %d\n", inList.size(), newInList.size(), outList.size(), outRealList.size(), outNoiseList.size(), outInitList.size(), outInitRealList.size(), outInitNoiseList.size(), TP, TN, FP, FN);
TPR = TP + FN == 0 ? 0f : (float) (TP * 1.0 / (TP + FN)); // percentage of true positive events. that's output real events out of all real events
TPO = TP + FP == 0 ? 0f : (float) (TP * 1.0 / (TP + FP)); // percentage of real events in the filter's output
TNR = TN + FP == 0 ? 0f : (float) (TN * 1.0 / (TN + FP));
accuracy = (float) ((TP + TN) * 1.0 / (TP + TN + FP + FN));
BR = TPR + TPO == 0 ? 0f : (float) (2 * TPR * TPO / (TPR + TPO)); // wish to norm to 1. if both TPR and TPO is 1. the value is 1
// System.out.printf("shotNoiseRateHz and leakNoiseRateHz is %.2f and %.2f\n", shotNoiseRateHz, leakNoiseRateHz);
if (lastTimestampPreviousPacket != null) {
int deltaTime = in.getLastTimestamp() - lastTimestampPreviousPacket;
inSignalRateHz = (1e6f * in.getSize()) / deltaTime;
inNoiseRateHz = (1e6f * noiseList.size()) / deltaTime;
outSignalRateHz = (1e6f * TP) / deltaTime;
outNoiseRateHz = (1e6f * FP) / deltaTime;
}
if (csvWriter != null) {
try {
csvWriter.write(String.format("%d,%d,%d,%d,%f,%f,%f,%d,%f,%f,%f,%f\n",
TP, TN, FP, FN, TPR, TNR, BR, firstE.timestamp,
inSignalRateHz, inNoiseRateHz, outSignalRateHz, outNoiseRateHz));
} catch (IOException e) {
doCloseCsvFile();
}
}
if (overlayPositives) {
annotateNoiseFilteringEvents(tpList, fpList);
}
if (overlayNegatives) {
annotateNoiseFilteringEvents(fnList, tnList);
}
rocHistory.addSample(1 - TNR, TPR, getCorrelationTimeS());
lastTimestampPreviousPacket = in.getLastTimestamp();
return passedSignalAndNoisePacket;
} catch (BackwardsTimestampException ex) {
Logger.getLogger(NoiseTesterFilter.class.getName()).log(Level.SEVERE, null, ex);
return in;
}
}
private void addNoise(EventPacket<? extends BasicEvent> in, EventPacket<? extends BasicEvent> augmentedPacket, List<BasicEvent> generatedNoise, float shotNoiseRateHz, float leakNoiseRateHz) {
// we need at least 1 event to be able to inject noise before it
if ((in.isEmpty())) {
log.warning("no input events in this packet, cannot inject noise because there is no end event");
return;
}
// save input packet
augmentedPacket.clear();
generatedNoise.clear();
// make the itertor to save events with added noise events
OutputEventIterator<ApsDvsEvent> outItr = (OutputEventIterator<ApsDvsEvent>) augmentedPacket.outputIterator();
if (prerecordedNoise == null && leakNoiseRateHz == 0 && shotNoiseRateHz == 0) {
for (BasicEvent ie : in) {
outItr.nextOutput().copyFrom(ie);
}
return; // no noise, just return which returns the copy from filterPacket
}
int firstTsThisPacket = in.getFirstTimestamp();
// insert noise between last event of last packet and first event of current packet
// but only if there waa a previous packet and we are monotonic
if (lastTimestampPreviousPacket != null) {
if (firstTsThisPacket < lastTimestampPreviousPacket) {
log.warning(String.format("non-monotonic timestamp: Resetting filter. (first event %d is smaller than previous event %d by %d)",
firstTsThisPacket, lastTimestampPreviousPacket, firstTsThisPacket - lastTimestampPreviousPacket));
resetFilter();
return;
}
// we had some previous event
int lastPacketTs = lastTimestampPreviousPacket + 1; // 1us more than timestamp of the last event in the last packet
insertNoiseEvents(lastPacketTs, firstTsThisPacket, outItr, generatedNoise);
checkStopMe(String.format("after insertNoiseEvents at start of packet over interval of %ss",
eng.format(1e-6f * (lastPacketTs - firstTsThisPacket))));
}
// insert noise between events of this packet after the first event, record their timestamp
int preEts = 0;
int lastEventTs = in.getFirstTimestamp();
for (BasicEvent ie : in) {
// if it is the first event or any with first event timestamp then just copy them
if (ie.timestamp == firstTsThisPacket) {
outItr.nextOutput().copyFrom(ie);
continue;
}
// save the previous timestamp and get the next one, and then inject noise between them
preEts = lastEventTs;
lastEventTs = ie.timestamp;
insertNoiseEvents(preEts, lastEventTs, outItr, generatedNoise);
outItr.nextOutput().copyFrom(ie);
}
}
private void insertNoiseEvents(int lastPacketTs, int firstTsThisPacket, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> generatedNoise) {
// check that we don't have too many events, packet will get too large
int tstepUs = (firstTsThisPacket - lastPacketTs);
if (tstepUs > 100_0000) {
stopMe = true;
checkStopMe("timestep longer than 100ms for inserting noise events, disabling filter");
return;
}
final int checkStopInterval = 100000;
int checks = 0;
for (double ts = lastPacketTs; ts < firstTsThisPacket; ts += poissonDtUs) {
// note that poissonDtUs is float but we truncate the actual timestamp to int us value here.
// It's OK if there are events with duplicate timestamps (there are plenty in input already).
sampleNoiseEvent((int) ts, outItr, generatedNoise, shotOffThresholdProb, shotOnThresholdProb, leakOnThresholdProb); // note noise injection updates ts to make sure monotonic
if (checks++ > checkStopInterval) {
if (checkStopMe("sampling noise events")) {
break;
}
}
}
}
private int sampleNoiseEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList, float shotOffThresholdProb, float shotOnThresholdProb, float leakOnThresholdProb) {
if (prerecordedNoise == null) {
final double randomnum = random.nextDouble();
if (randomnum < shotOffThresholdProb) {
injectOffEvent(ts, outItr, noiseList);
} else if (randomnum > shotOnThresholdProb) {
injectOnEvent(ts, outItr, noiseList);
}
if (random.nextDouble() < leakOnThresholdProb) {
injectOnEvent(ts, outItr, noiseList);
}
return ts;
} else {
ArrayList<BasicEvent> noiseEvents = prerecordedNoise.nextEvents(ts); // these have timestamps of the prerecorded noise
for (BasicEvent e : noiseEvents) {
PolarityEvent pe = (PolarityEvent) e;
BasicEvent ecopy = outItr.nextOutput(); // get the next event from output packet
ecopy.copyFrom(e); // copy its fields from the noise event
ecopy.timestamp = ts; // update the timestamp to the current timestamp
noiseList.add(ecopy); // add it to the list of noise events we keep for analysis
}
return ts;
}
}
private void injectOnEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
final int x = (short) random.nextInt(sx);
final int y = (short) random.nextInt(sy);
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
e.polarity = PolarityEvent.Polarity.On;
noiseList.add(e);
}
private void injectOffEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<BasicEvent> noiseList) {
final int x = (short) random.nextInt(sx);
final int y = (short) random.nextInt(sy);
ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput();
e.setSpecial(false);
e.x = (short) (x);
e.y = (short) (y);
e.timestamp = ts;
e.polarity = PolarityEvent.Polarity.Off;
noiseList.add(e);
}
@Override
synchronized public void resetFilter() {
lastTimestampPreviousPacket = null;
firstSignalTimestmap = null;
resetCalled = true;
getEnclosedFilterChain().reset();
if (prerecordedNoise != null) {
prerecordedNoise.rewind();
}
nnbHistograms.reset();
}
private void computeProbs() {
// the rate per pixel results in overall noise rate for entire sensor that is product of pixel rate and number of pixels.
// we compute this overall noise rate to determine the Poisson sample interval that is much smaller than this to enable simple Poisson noise sampling.
// Compute time step that is 10X less than the overall mean interval for noise
// dt is the time interval such that if we sample a random value 0-1 every dt us, the the overall noise rate will be correct.
int npix = (chip.getSizeX() * chip.getSizeY());
float tmp = (float) (1.0 / ((leakNoiseRateHz + shotNoiseRateHz) * npix)); // this value is very small
poissonDtUs = ((tmp / 10) * 1000000); // 1s = 1000000 us // TODO document why 10 here. It is to ensure that prob(>1 event per sample is low)
final float minPoissonDtUs = 1f / (1e-6f * MAX_TOTAL_NOISE_RATE_HZ);
if (prerecordedNoise != null) {
log.info("Prerecoded noise input: clipping max noise rate to MAX_TOTAL_NOISE_RATE_HZ=" + eng.format(MAX_TOTAL_NOISE_RATE_HZ) + "Hz");
poissonDtUs = minPoissonDtUs;
} else if (poissonDtUs < minPoissonDtUs) {
log.info("clipping max noise rate to MAX_TOTAL_NOISE_RATE_HZ=" + eng.format(MAX_TOTAL_NOISE_RATE_HZ) + "Hz");
poissonDtUs = minPoissonDtUs;
} else // if (poissonDtUs < 1) {
// log.warning(String.format("Poisson sampling rate is less than 1us which is timestep resolution, could be slow"));
{
shotOffThresholdProb = 0.5f * (poissonDtUs * 1e-6f * npix) * shotNoiseRateHz; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
}
shotOnThresholdProb = 1 - shotOffThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
leakOnThresholdProb = (poissonDtUs * 1e-6f * npix) * leakNoiseRateHz; // bounds for samppling Poisson noise
}
@Override
public void initFilter() {
if (chain == null) {
chain = new FilterChain(chip);
// for(NoiseFilterEnum en:NoiseFilterEnum.values()){
// Class cl=Class.forName(en.va);
noiseFilters = new AbstractNoiseFilter[]{new BackgroundActivityFilter(chip), new SpatioTemporalCorrelationFilter(chip), new DoubleWindowFilter(chip), new OrderNBackgroundActivityFilter((chip)), new MedianDtFilter(chip)};
for (AbstractNoiseFilter n : noiseFilters) {
n.initFilter();
chain.add(n);
getSupport().addPropertyChangeListener(n);
n.getSupport().addPropertyChangeListener(this); // make sure we are synchronized both ways for all filter parameters
}
setEnclosedFilterChain(chain);
if (getChip().getAeViewer() != null) {
getChip().getAeViewer().getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this);
getChip().getAeViewer().getSupport().addPropertyChangeListener(AEViewer.EVENT_CHIP, this);
getChip().getAeViewer().getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this);
}
if (chip.getRemoteControl() != null) {
log.info("adding RemoteControlCommand listener to AEChip\n");
chip.getRemoteControl().addCommandListener(this, "setNoiseFilterParameters", "set correlation time or distance.");
}
if (chip.getRenderer() instanceof DavisRenderer) {
renderer = (DavisRenderer) chip.getRenderer();
}
}
sx = chip.getSizeX() - 1;
sy = chip.getSizeY() - 1;
signalAndNoisePacket = new EventPacket<>(ApsDvsEvent.class);
setSelectedNoiseFilterEnum(selectedNoiseFilterEnum);
computeProbs();
// setAnnotateAlpha(annotateAlpha);
fixRendererAnnotationLayerShowing(); // make sure renderer is properly set up.
}
/**
* @return the shotNoiseRateHz
*/
public float getShotNoiseRateHz() {
return shotNoiseRateHz;
}
@Override
public int[][] getLastTimesMap() {
return null;
}
/**
* @param shotNoiseRateHz the shotNoiseRateHz to set
*/
synchronized public void setShotNoiseRateHz(float shotNoiseRateHz) {
if (shotNoiseRateHz < 0) {
shotNoiseRateHz = 0;
}
if (shotNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
shotNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("shotNoiseRateHz", shotNoiseRateHz);
getSupport().firePropertyChange("shotNoiseRateHz", this.shotNoiseRateHz, shotNoiseRateHz);
this.shotNoiseRateHz = shotNoiseRateHz;
computeProbs();
}
/**
* @return the leakNoiseRateHz
*/
public float getLeakNoiseRateHz() {
return leakNoiseRateHz;
}
/**
* @param leakNoiseRateHz the leakNoiseRateHz to set
*/
synchronized public void setLeakNoiseRateHz(float leakNoiseRateHz) {
if (leakNoiseRateHz < 0) {
leakNoiseRateHz = 0;
}
if (leakNoiseRateHz > RATE_LIMIT_HZ) {
log.warning("high leak rates will hang the filter and consume all memory");
leakNoiseRateHz = RATE_LIMIT_HZ;
}
putFloat("leakNoiseRateHz", leakNoiseRateHz);
getSupport().firePropertyChange("leakNoiseRateHz", this.leakNoiseRateHz, leakNoiseRateHz);
this.leakNoiseRateHz = leakNoiseRateHz;
computeProbs();
}
/**
* @return the csvFileName
*/
public String getCsvFilename() {
return csvFileName;
}
/**
* @param csvFileName the csvFileName to set
*/
public void setCsvFilename(String csvFileName) {
if (csvFileName.toLowerCase().endsWith(".csv")) {
csvFileName = csvFileName.substring(0, csvFileName.length() - 4);
}
putString("csvFileName", csvFileName);
getSupport().firePropertyChange("csvFileName", this.csvFileName, csvFileName);
this.csvFileName = csvFileName;
openCvsFiile();
}
public void doCloseCsvFile() {
if (csvFile != null) {
try {
log.info("closing statistics output file" + csvFile);
csvWriter.close();
} catch (IOException e) {
log.warning("could not close " + csvFile + ": caught " + e.toString());
} finally {
csvFile = null;
csvWriter = null;
}
}
}
private void openCvsFiile() {
String fn = csvFileName + ".csv";
csvFile = new File(fn);
log.info(String.format("opening %s for output", fn));
try {
csvWriter = new BufferedWriter(new FileWriter(csvFile, true));
if (!csvFile.exists()) { // write header
log.info("file did not exist, so writing header");
csvWriter.write(String.format("TP,TN,FP,FN,TPR,TNR,BR,firstE.timestamp,"
+ "inSignalRateHz,inNoiseRateHz,outSignalRateHz,outNoiseRateHz\n"));
}
} catch (IOException ex) {
log.warning(String.format("could not open %s for output; caught %s", fn, ex.toString()));
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt); //To change body of generated methods, choose Tools | Templates.
if (evt.getPropertyName() == AEInputStream.EVENT_REWOUND) {
// log.info(String.format("got rewound event %s, setting reset on next packet", evt));
resetCalled = true;
} else if (evt.getPropertyName() == AEViewer.EVENT_FILEOPEN) {
if (prerecordedNoise != null) {
prerecordedNoise.rewind();
}
}
}
/**
* @return the selectedNoiseFilter
*/
public NoiseFilterEnum getSelectedNoiseFilterEnum() {
return selectedNoiseFilterEnum;
}
/**
* @param selectedNoiseFilter the selectedNoiseFilter to set
*/
synchronized public void setSelectedNoiseFilterEnum(NoiseFilterEnum selectedNoiseFilter) {
this.selectedNoiseFilterEnum = selectedNoiseFilter;
putString("selectedNoiseFilter", selectedNoiseFilter.toString());
for (AbstractNoiseFilter n : noiseFilters) {
if (n.getClass().getSimpleName().equals(selectedNoiseFilter.toString())) {
n.initFilter();
n.setFilterEnabled(true);
log.info("setting " + n.getClass().getSimpleName() + " enabled");
selectedFilter = n;
} else {
n.setFilterEnabled(false);
}
}
resetCalled = true; // make sure we iniitialize the timestamp maps on next packet for new filter
rocHistory.reset();
}
private String USAGE = "Need at least 2 arguments: noisefilter <command> <args>\nCommands are: setNoiseFilterParameters <csvFilename> xx <shotNoiseRateHz> xx <leakNoiseRateHz> xx and specific to the filter\n";
@Override
public String processRemoteControlCommand(RemoteControlCommand command, String input) {
// parse command and set parameters of NoiseTesterFilter, and pass command to specific filter for further processing
// setNoiseFilterParameters csvFilename 10msBAFdot_500m_0m_300num0 shotNoiseRateHz 0.5 leakNoiseRateHz 0 dt 300 num 0
String[] tok = input.split("\\s");
if (tok.length < 2) {
return USAGE;
} else {
for (int i = 1; i < tok.length; i++) {
if (tok[i].equals("csvFileName")) {
setCsvFilename(tok[i + 1]);
} else if (tok[i].equals("shotNoiseRateHz")) {
setShotNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setShotNoiseRateHz %f", shotNoiseRateHz));
} else if (tok[i].equals("leakNoiseRateHz")) {
setLeakNoiseRateHz(Float.parseFloat(tok[i + 1]));
log.info(String.format("setLeakNoiseRateHz %f", leakNoiseRateHz));
} else if (tok[i].equals("closeFile")) {
doCloseCsvFile();
log.info(String.format("closeFile %s", csvFileName));
}
}
log.info("Received Command:" + input);
String out = selectedFilter.setParameters(command, input);
log.info("Execute Command:" + input);
return out;
}
}
/**
* Fills lastTimesMap with waiting times drawn from Poisson process with
* rate noiseRateHz
*
* @param lastTimesMap map
* @param noiseRateHz rate in Hz
* @param lastTimestampUs the last timestamp; waiting times are created
* before this time
*/
protected void initializeLastTimesMapForNoiseRate(int[][] lastTimesMap, float noiseRateHz, int lastTimestampUs) {
for (final int[] arrayRow : lastTimesMap) {
for (int i = 0; i < arrayRow.length; i++) {
final double p = random.nextDouble();
final double t = -noiseRateHz * Math.log(1 - p);
final int tUs = (int) (1000000 * t);
arrayRow[i] = lastTimestampUs - tUs;
}
}
}
@Override
public void setCorrelationTimeS(float dtS) {
super.setCorrelationTimeS(dtS);
for (AbstractNoiseFilter f : noiseFilters) {
f.setCorrelationTimeS(dtS);
}
}
@Override
public void setAdaptiveFilteringEnabled(boolean adaptiveFilteringEnabled) {
super.setAdaptiveFilteringEnabled(adaptiveFilteringEnabled);
for (AbstractNoiseFilter f : noiseFilters) {
f.setAdaptiveFilteringEnabled(adaptiveFilteringEnabled);
}
}
@Override
public synchronized void setSubsampleBy(int subsampleBy) {
super.setSubsampleBy(subsampleBy);
for (AbstractNoiseFilter f : noiseFilters) {
f.setSubsampleBy(subsampleBy);
}
}
@Override
public void setFilterHotPixels(boolean filterHotPixels) {
super.setFilterHotPixels(filterHotPixels); //To change body of generated methods, choose Tools | Templates.
for (AbstractNoiseFilter f : noiseFilters) {
f.setFilterHotPixels(filterHotPixels);
}
}
@Override
public void setLetFirstEventThrough(boolean letFirstEventThrough) {
super.setLetFirstEventThrough(letFirstEventThrough); //To change body of generated methods, choose Tools | Templates.
for (AbstractNoiseFilter f : noiseFilters) {
f.setLetFirstEventThrough(letFirstEventThrough);
}
}
@Override
public synchronized void setSigmaDistPixels(int sigmaDistPixels) {
super.setSigmaDistPixels(sigmaDistPixels); //To change body of generated methods, choose Tools | Templates.
for (AbstractNoiseFilter f : noiseFilters) {
f.setSigmaDistPixels(sigmaDistPixels);
}
}
// /**
// * @return the annotateAlpha
// */
// public float getAnnotateAlpha() {
// return annotateAlpha;
// /**
// * @param annotateAlpha the annotateAlpha to set
// */
// public void setAnnotateAlpha(float annotateAlpha) {
// if (annotateAlpha > 1.0) {
// annotateAlpha = 1.0f;
// if (annotateAlpha < 0.0) {
// annotateAlpha = 0.0f;
// this.annotateAlpha = annotateAlpha;
// if (renderer != null) {
// renderer.setAnnotateAlpha(annotateAlpha);
/**
* Sets renderer to show annotation layer
*/
private void fixRendererAnnotationLayerShowing() {
if (renderer != null) {
renderer.setDisplayAnnotation(this.overlayNegatives || this.overlayPositives);
}
}
/**
* @return the overlayPositives
*/
public boolean isOverlayPositives() {
return overlayPositives;
}
/**
* @return the overlayNegatives
*/
public boolean isOverlayNegatives() {
return overlayNegatives;
}
/**
* @param overlayNegatives the overlayNegatives to set
*/
public void setOverlayNegatives(boolean overlayNegatives) {
boolean oldOverlayNegatives = this.overlayNegatives;
this.overlayNegatives = overlayNegatives;
putBoolean("overlayNegatives", overlayNegatives);
getSupport().firePropertyChange("overlayNegatives", oldOverlayNegatives, overlayNegatives);
fixRendererAnnotationLayerShowing();
}
/**
* @param overlayPositives the overlayPositives to set
*/
public void setOverlayPositives(boolean overlayPositives) {
boolean oldOverlayPositives = this.overlayPositives;
this.overlayPositives = overlayPositives;
putBoolean("overlayPositives", overlayPositives);
getSupport().firePropertyChange("overlayPositives", oldOverlayPositives, overlayPositives);
fixRendererAnnotationLayerShowing();
}
/**
* @return the rocHistory
*/
public int getRocHistoryLength() {
return rocHistoryLength;
}
/**
* @param rocHistory the rocHistory to set
*/
synchronized public void setRocHistoryLength(int rocHistoryLength) {
if (rocHistoryLength > 10000) {
rocHistoryLength = 10000;
}
this.rocHistoryLength = rocHistoryLength;
putInt("rocHistoryLength", rocHistoryLength);
rocHistory.reset();
}
synchronized public void doClearROCHistory() {
rocHistory.reset();
}
synchronized public void doPrintNnbInfo() {
System.out.print(nnbHistograms.toString());
}
synchronized public void doCloseNoiseSourceRecording() {
if (prerecordedNoise != null) {
log.info("clearing recoerded noise input data");
prerecordedNoise = null;
}
}
synchronized public void doOpenNoiseSourceRecording() {
JFileChooser fileChooser = new JFileChooser();
ChipDataFilePreview preview = new ChipDataFilePreview(fileChooser, getChip());
// from book swing hacks
fileChooser.addPropertyChangeListener(preview);
fileChooser.setAccessory(preview);
String chosenPrerecordedNoiseFilePath = getString("chosenPrerecordedNoiseFilePath", "");
// get the last folder
DATFileFilter datFileFilter = new DATFileFilter();
fileChooser.addChoosableFileFilter(datFileFilter);
File sf = new File(chosenPrerecordedNoiseFilePath);
fileChooser.setCurrentDirectory(sf);
fileChooser.setSelectedFile(sf);
try {
int retValue = fileChooser.showOpenDialog(getChip().getAeViewer().getFilterFrame());
if (retValue == JFileChooser.APPROVE_OPTION) {
chosenPrerecordedNoiseFilePath = fileChooser.getSelectedFile().toString();
putString("chosenPrerecordedNoiseFilePath", chosenPrerecordedNoiseFilePath);
try {
prerecordedNoise = new PrerecordedNoise(fileChooser.getSelectedFile());
computeProbs(); // set poissonDtUs after we construct prerecordedNoise so it is set properly
} catch (IOException ex) {
log.warning(String.format("Exception trying to open data file: " + ex));
}
} else {
preview.showFile(null);
}
} catch (GLException e) {
log.warning(e.toString());
preview.showFile(null);
}
}
private enum Classification {
None, TP, FP, TN, FN
}
private void updateNnbHistograms(Classification classification, ArrayList<FilteredEventWithNNb> filteredInNnb) {
for (FilteredEventWithNNb e : filteredInNnb) {
nnbHistograms.addEvent(classification, e.nnb);
}
}
/**
* Tracks statistics of neighbors for false and true positives and negatives
*/
private class NNbHistograms {
NnbHistogram tpHist, fpHist, tnHist, fnHist;
NnbHistogram[] histograms;
private class NnbHistogram {
Classification classification = Classification.None;
final int[] nnbcounts = new int[8]; // bit frequencies around us, 8 neighbors
final int[] byteHist = new int[256]; // array of frequency of patterns versus the pattern index
int count; // total # events
final float[] prob = new float[256];
public NnbHistogram(Classification classification) {
this.classification = classification;
}
void reset() {
Arrays.fill(nnbcounts, 0);
Arrays.fill(byteHist, 0);
count = 0;
}
void addEvent(byte nnb) {
count++;
byteHist[0xff & nnb]++; // make sure we get unsigned byte
if (nnb == 0) {
return;
}
for (int i = 0; i < 8; i++) {
if ((((nnb & 0xff) >> i) & 1) != 0) {
nnbcounts[i]++;
}
}
}
String computeProbabilities() {
for (int i = 0; i < 256; i++) {
prob[i] = (float) byteHist[i] / count;
}
final Integer[] ids = new Integer[256];
for (int i = 0; i < ids.length; i++) {
ids[i] = i;
}
Arrays.sort(ids, new Comparator<Integer>() {
@Override
public int compare(final Integer o1, final Integer o2) {
return -Float.compare(prob[o1], prob[o2]);
}
});
StringBuilder sb = new StringBuilder(classification + " probabilities (count=" + count + ")");
final int perline = 4;
if (count > 0) {
for (int i = 0; i < ids.length; i++) {
if (prob[ids[i]] < 0.005f) {
break;
}
if (i % perline == 0) {
sb.append(String.format("\n%3d-%3d: ", i, i + perline - 1));
}
String binstring = String.format("%8s", Integer.toBinaryString(ids[i] & 0xFF)).replace(' ', '0');
sb.append(String.format("%4.1f%%:%s, ", 100 * prob[ids[i]], binstring));
}
}
sb.append("\n");
// log.info(sb.toString());
// float[] sortedProb = Arrays.copyOf(prob, 0);
// Arrays.sort(sortedProb);
// ArrayUtils.reverse(prob);
return sb.toString();
}
public String toString() {
return computeProbabilities();
// StringBuilder sb = new StringBuilder(classification.toString() + " neighbors: [");
// for (int i : nnbcounts) {
// sb.append(i + " ");
// sb.append("]\n");
// sb.append("counts: ");
// final int perline = 32;
// for (int i = 0; i < byteHist.length; i++) {
// if (i % perline == 0) {
// sb.append("\n");
// sb.append(byteHist[i] + " ");
// sb.append("\n");
// return sb.toString();
}
void draw(GL2 gl) {
int sum = 0;
for (int i = 0; i < nnbcounts.length; i++) {
sum += nnbcounts[i];
}
if (sum == 0) {
sum = 1;
}
gl.glPushMatrix();
for (int i = 0; i < nnbcounts.length; i++) {
if (nnbcounts[i] == 0) {
continue;
}
int ind = i < 4 ? i : i + 1;
int y = ind % 3, x = ind / 3;
float b = (float) nnbcounts[i] / sum;
gl.glColor3f(b, b, b);
gl.glRectf(x, y, x + 1, y + 1);
}
gl.glPopMatrix();
}
}
public NNbHistograms() {
tpHist = new NnbHistogram(Classification.TP);
fpHist = new NnbHistogram(Classification.FP);
tnHist = new NnbHistogram(Classification.TN);
fnHist = new NnbHistogram(Classification.FN);
histograms = new NnbHistogram[]{tpHist, fpHist, tnHist, fnHist};
}
void reset() {
tpHist.reset();
fpHist.reset();
tnHist.reset();
fnHist.reset();
}
void addEvent(Classification classification, byte nnb) {
switch (classification) {
case TP:
tpHist.addEvent(nnb);
break;
case FP:
fpHist.addEvent(nnb);
break;
case TN:
tnHist.addEvent(nnb);
break;
case FN:
fnHist.addEvent(nnb);
break;
}
}
void draw(GL2 gl) {
int sc = 5;
int x = -20;
int y = 0;
gl.glPushMatrix();
gl.glTranslatef(-sc * 6, 0, 0);
gl.glScalef(sc, sc, 1);
for (int i = 0; i < histograms.length; i++) {
histograms[i].draw(gl);
gl.glTranslatef(0, 4, 0);
}
gl.glPopMatrix();
}
@Override
public String toString() {
return "NNbHistograms{\n" + "tpHist=" + tpHist + "\n fpHist=" + fpHist + "\n tnHist=" + tnHist + "\n fnHist=" + fnHist + "}\n";
}
}
private class ROCHistory {
private EvictingQueue<ROCSample> rocHistoryList = EvictingQueue.create(rocHistoryLength);
private Float lastTau = null;
private final double LOG10_CHANGE_TO_ADD_LABEL = .2;
GLUT glut = new GLUT();
private int counter = 0;
private final int SAMPLE_INTERVAL_NO_CHANGE = 30;
private int legendDisplayListId = 0;
private ROCSample[] legendROCs = null;
ROCSample createAbsolutePosition(float x, float y, float tau, boolean labeled) {
return new ROCSample(x, y, tau, labeled);
}
ROCSample createTprFpr(float tpr, float fpr, float tau, boolean labeled) {
return new ROCSample(fpr * sx, tpr * sy, tau, labeled);
}
class ROCSample {
float x, y, tau;
boolean labeled = false;
final int SIZE = 2; // chip pixels
private ROCSample(float x, float y, float tau, boolean labeled) {
this.x = x;
this.y = y;
this.tau = tau;
this.labeled = labeled;
}
private void draw(GL2 gl) {
float hue = (float) (Math.log10(tau) / 2 + 1.5); //. hue is 1 for tau=0.1s and is 0 for tau = 1ms
Color c = Color.getHSBColor(hue, 1f, hue);
float[] rgb = c.getRGBComponents(null);
gl.glColor3fv(rgb, 0);
gl.glLineWidth(1);
gl.glPushMatrix();
DrawGL.drawBox(gl, x, y, SIZE, SIZE, 0);
gl.glPopMatrix();
if (labeled) {
// gl.glTranslatef(5 * L, - 3 * L, 0);
gl.glRasterPos3f(x + SIZE, y, 0);
// gl.glRotatef(-45, 0, 0, 1); // can't rotate bitmaps, must use stroke and glScalef
String s = String.format("%ss", eng.format(tau));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
// glut.glutStrokeString(GLUT.STROKE_ROMAN, s);
}
}
}
private void reset() {
rocHistoryList = EvictingQueue.create(rocHistoryLength);
lastTau = null;
}
void addSample(float fpr, float tpr, float tau) {
boolean labelIt = lastTau == null
|| Math.abs(Math.log10(tau / lastTau)) > .1
|| ++counter >= SAMPLE_INTERVAL_NO_CHANGE;
rocHistoryList.add(rocHistory.createTprFpr(tpr, fpr, tau, labelIt));
if (labelIt) {
lastTau = tau;
}
if (counter > SAMPLE_INTERVAL_NO_CHANGE) {
counter = 0;
}
}
private void drawLegend(GL2 gl) {
if (legendDisplayListId == 0) {
int NLEG = 8;
legendROCs = new ROCSample[NLEG];
for (int i = 0; i < NLEG; i++) {
ROCSample r = createAbsolutePosition(sx + 5, i * 12 + 20, (float) Math.pow(10, -3 + 2f * i / (NLEG - 1)), true);
legendROCs[i] = r;
}
legendDisplayListId = gl.glGenLists(1);
gl.glNewList(legendDisplayListId, GL2.GL_COMPILE);
{ // TODO make a real list
}
gl.glEndList();
}
gl.glPushMatrix();
// gl.glCallList(legendDisplayListId);
for (ROCSample r : legendROCs) {
r.draw(gl);
}
gl.glPopMatrix();
}
void draw(GL2 gl) {
// draw axes
gl.glPushMatrix();
gl.glColor4f(.8f, .8f, .2f, .5f); // must set color before raster position (raster position is like glVertex)
gl.glLineWidth(2);
gl.glBegin(GL.GL_LINE_STRIP);
gl.glVertex2f(0, sy);
gl.glVertex2f(0, 0);
gl.glVertex2f(sx, 0);
gl.glEnd();
gl.glRasterPos3f(sx / 2 - 30, -10, 0);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, "FPR");
// gl.glPushMatrix();
// gl.glTranslatef(sx / 2, -10, 0);
// gl.glScalef(.1f, .1f, 1);
// glut.glutStrokeString(GLUT.STROKE_ROMAN, "FPR");
// gl.glPopMatrix();
gl.glRasterPos3f(-30, sy / 2, 0);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, "TPR");
gl.glPopMatrix();
for (ROCSample rocSample : rocHistoryList) {
rocSample.draw((gl));
}
// draw X at TPR / TNR point
int L = 12;
gl.glColor4f(.8f, .8f, .2f, .5f); // must set color before raster position (raster position is like glVertex)
gl.glLineWidth(6);
float x = (1 - TNR) * sx;
float y = TPR * sy;
gl.glPushMatrix();
DrawGL.drawCross(gl, x, y, L, 0);
gl.glPopMatrix();
if (rocHistoryLength > 1) {
drawLegend(gl);
}
}
}
// recorded noise to be used as input
private class PrerecordedNoise {
EventPacket<BasicEvent> recordedNoiseFileNoisePacket = null;
Iterator<BasicEvent> itr = null;
BasicEvent noiseFirstEvent, noiseNextEvent;
int noiseFirstTs;
Integer signalMostRecentTs;
private ArrayList<BasicEvent> returnedEvents = new ArrayList();
int noiseEventCounter = 0;
File file;
private PrerecordedNoise(File chosenPrerecordedNoiseFilePath) throws IOException {
file = chosenPrerecordedNoiseFilePath;
AEFileInputStream recordedNoiseAeFileInputStream = new AEFileInputStream(file, getChip());
AEPacketRaw rawPacket = recordedNoiseAeFileInputStream.readPacketByNumber(MAX_NUM_RECORDED_EVENTS);
recordedNoiseAeFileInputStream.close();
EventPacket<BasicEvent> inpack = getChip().getEventExtractor().extractPacket(rawPacket);
EventPacket<BasicEvent> recordedNoiseFileNoisePacket = new EventPacket(PolarityEvent.class);
OutputEventIterator outItr = recordedNoiseFileNoisePacket.outputIterator();
for (BasicEvent p : inpack) {
outItr.nextOutput().copyFrom(p);
}
this.recordedNoiseFileNoisePacket = recordedNoiseFileNoisePacket;
itr = recordedNoiseFileNoisePacket.inputIterator();
noiseFirstEvent = recordedNoiseFileNoisePacket.getFirstEvent();
noiseFirstTs = recordedNoiseFileNoisePacket.getFirstTimestamp();
this.noiseNextEvent = this.noiseFirstEvent;
computeProbs(); // set noise sample rate via poissonDtUs
log.info(String.format("Loaded %s pre-recorded events with duration %ss from %s", eng.format(recordedNoiseFileNoisePacket.getSize()), eng.format(1e-6f * recordedNoiseAeFileInputStream.getDurationUs()), chosenPrerecordedNoiseFilePath));
}
ArrayList<BasicEvent> nextEvents(int ts) {
returnedEvents.clear();
if (signalMostRecentTs == null) {
signalMostRecentTs = ts;
return returnedEvents; // no events at first, just get the timestamap
}
if (ts < signalMostRecentTs) { // time went backwards, rewind noise events
rewind();
return nextEvents(ts);
}
while (noiseNextEvent.timestamp - noiseFirstTs < ts - signalMostRecentTs) {
returnedEvents.add(noiseNextEvent);
noiseEventCounter++;
if (itr.hasNext()) {
noiseNextEvent = itr.next();
} else {
rewind();
return returnedEvents;
}
}
return returnedEvents;
}
private void rewind() {
log.info(String.format("rewinding noise events after %d events", noiseEventCounter));
this.itr = recordedNoiseFileNoisePacket.inputIterator();
noiseNextEvent = noiseFirstEvent;
signalMostRecentTs = null;
noiseEventCounter = 0;
}
}
} |
package com.pixel.nfcsettings;
import java.io.IOException;
import java.nio.charset.Charset;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class WriteMailActivity extends Activity {
private NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
private String urlAddress="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.writemail);
final EditText addressEditText = (EditText)this.findViewById(R.id.emailaddresseditText1);
final EditText subjectEditText = (EditText)this.findViewById(R.id.subjecteditText2);
final EditText mailBodyEditText = (EditText)this.findViewById(R.id.body);
Button writeMailButton = (Button)this.findViewById(R.id.writeemailbutton1);
writeMailButton.setOnClickListener(new android.view.View.OnClickListener()
{
public void onClick(View view) {
String mailAddress = addressEditText.getText().toString();
String mailSubject = subjectEditText.getText().toString();
String mailBody = mailBodyEditText.getText().toString();
urlAddress = mailAddress+"?subject=" +mailSubject+"&body="+mailBody;
TextView messageText = (TextView)findViewById(R.id.textView1);
messageText.setText("Touch NFC Tag to share e-mail\n"+
"Mail addres: "+mailAddress+"\nSubject: "+mailSubject+"\nBody: "+mailBody);
}
});
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
mFilters = new IntentFilter[] {
ndef,
};
mTechLists = new String[][] { new String[] { Ndef.class.getName() },
new String[] { NdefFormatable.class.getName() }};
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
mTechLists);
}
@Override
public void onNewIntent(Intent intent) {
Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] uriField = urlAddress.getBytes(Charset.forName("US-ASCII"));
byte[] payload = new byte[uriField.length + 1]; //add 1 for the URI Prefix
payload[0] = 0x06;
System.arraycopy(uriField, 0, payload, 1, uriField.length); //appends URI to payload
NdefRecord URIRecord = new NdefRecord(
NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);
NdefMessage newMessage= new NdefMessage(new NdefRecord[] { URIRecord });
writeNdefMessageToTag(newMessage, tag);
}
@Override
public void onPause() {
super.onPause();
mNfcAdapter.disableForegroundDispatch(this);
}
boolean writeNdefMessageToTag(NdefMessage message, Tag detectedTag) {
int size = message.toByteArray().length;
try {
Ndef ndef = Ndef.get(detectedTag);
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) {
Toast.makeText(this, "Tag is read-only.", Toast.LENGTH_SHORT).show();
return false;
}
if (ndef.getMaxSize() < size) {
Toast.makeText(this, "The data cannot written to tag, Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.", Toast.LENGTH_SHORT).show();
return false;
}
ndef.writeNdefMessage(message);
ndef.close();
Toast.makeText(this, "Message is written tag.", Toast.LENGTH_SHORT).show();
return true;
} else {
NdefFormatable ndefFormat = NdefFormatable.get(detectedTag);
if (ndefFormat != null) {
try {
ndefFormat.connect();
ndefFormat.format(message);
ndefFormat.close();
Toast.makeText(this, "The data is written to the tag ", Toast.LENGTH_SHORT).show();
return true;
} catch (IOException e) {
Toast.makeText(this, "Failed to format tag", Toast.LENGTH_SHORT).show();
return false;
}
} else {
Toast.makeText(this, "NDEF is not supported", Toast.LENGTH_SHORT).show();
return false;
}
}
} catch (Exception e) {
Toast.makeText(this, "Write opreation has failed", Toast.LENGTH_SHORT).show();
}
return false;
}
} |
package net.sf.jsqlparser.statement.create.table;
import java.util.List;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.StatementVisitor;
import net.sf.jsqlparser.statement.select.PlainSelect;
/**
* A "CREATE TABLE" statement
*/
public class CreateTable implements Statement {
private Table table;
private boolean tableIfNotExists = false;
private boolean orReplaceTable = false;
private List<String> tableOptionsStrings;
private List<ColumnDefinition> columnDefinitions;
private List<Index> indexes;
public void accept(StatementVisitor statementVisitor) {
statementVisitor.visit(this);
}
/**
* The name of the table to be created
*
* @return The {@link Table} identifier for the table being created.
*/
public Table getTable() {
return table;
}
public void setTable(Table table) {
this.table = table;
}
/**
* Table if not exists
*
* @return The table if not exists
*/
public boolean getTableIfNotExists() {
return tableIfNotExists;
}
public void setTableIfNotExists(boolean tableIfNotExists) {
this.tableIfNotExists = tableIfNotExists;
}
/**
* Replace Table if exists
*
* @return The or replace table
*/
public boolean getOrReplaceTable() {
return orReplaceTable;
}
public void setOrReplaceTable(boolean orReplaceTable) {
this.orReplaceTable = orReplaceTable;
}
/**
* A list of {@link ColumnDefinition}s of this table.
*
* @return The column definitions.
*/
public List<ColumnDefinition> getColumnDefinitions() {
return columnDefinitions;
}
public void setColumnDefinitions(List<ColumnDefinition> list) {
columnDefinitions = list;
}
/**
* A list of options (as simple strings) of this table definition, as ("TYPE", "=", "MYISAM")
*
* @return The table options as simple strings
*/
public List<String> getTableOptionsStrings() {
return tableOptionsStrings;
}
public void setTableOptionsStrings(List<String> list) {
tableOptionsStrings = list;
}
/**
* A list of {@link Index}es (for example "PRIMARY KEY") of this table.<br>
* Indexes created with column definitions (as in mycol INT PRIMARY KEY) are not inserted into this list.
*
* @return A list of indexes
*/
public List<Index> getIndexes() {
return indexes;
}
public void setIndexes(List<Index> list) {
indexes = list;
}
public String toString() {
String sql = "";
String ifNotExistsStr = this.tableIfNotExists ? "IF NOT EXISTS " : "";
String orReplaceStr = this.orReplaceTable ? "DROP TABLE " + table + ";\n" : "";
sql += orReplaceStr;
sql += "CREATE TABLE " + ifNotExistsStr + table + " (";
sql += PlainSelect.getStringList(columnDefinitions, true, false);
if (indexes != null && indexes.size() != 0) {
sql += ", ";
sql += PlainSelect.getStringList(indexes);
}
sql += ") ";
sql += PlainSelect.getStringList(tableOptionsStrings, false, false);
return sql;
}
} |
package com.valkryst.VTerminal.component;
import com.valkryst.VTerminal.Tile;
import com.valkryst.VTerminal.Screen;
import com.valkryst.VTerminal.TileGrid;
import com.valkryst.VTerminal.builder.ButtonBuilder;
import com.valkryst.VTerminal.palette.ColorPalette;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import javax.swing.event.MouseInputListener;
import java.awt.Color;
import java.awt.event.MouseEvent;
@ToString
public class Button extends Component {
/** Whether or not the button is in the normal state. */
private boolean isInNormalState = true;
/** whether or not the button is in the hovered state. */
private boolean isInHoveredState = false;
/** Whether or not the button is in the pressed state. */
private boolean isInPressedState = false;
/** The background color for when the button is in the normal state. */
protected Color backgroundColor_normal;
/** The foreground color for when the button is in the normal state. */
protected Color foregroundColor_normal;
/** The background color for when the button is in the hover state. */
protected Color backgroundColor_hover;
/** The foreground color for when the button is in the hover state. */
protected Color foregroundColor_hover;
/** The background color for when the button is in the pressed state. */
protected Color backgroundColor_pressed;
/** The foreground color for when the button is in the pressed state. */
protected Color foregroundColor_pressed;
/** The color palette. */
@Getter @Setter @NonNull private ColorPalette colorPalette;
/** The function to run when the button is clicked. */
@Getter @Setter @NonNull private Runnable onClickFunction;
/**
* Constructs a new AsciiButton.
*
* @param builder
* The builder to use.
*
* @throws NullPointerException
* If the builder is null.
*/
public Button(final @NonNull ButtonBuilder builder) {
super(builder.getDimensions(), builder.getPosition());
colorPalette = builder.getColorPalette();
backgroundColor_normal = colorPalette.getButton_defaultBackground();
foregroundColor_normal = colorPalette.getButton_defaultForeground();
backgroundColor_hover = colorPalette.getButton_hoverBackground();
foregroundColor_hover = colorPalette.getButton_hoverForeground();
backgroundColor_pressed = colorPalette.getButton_pressedBackground();
foregroundColor_pressed = colorPalette.getButton_pressedForeground();
this.onClickFunction = builder.getOnClickFunction();
// Set the button's text:
final char[] text = builder.getText().toCharArray();
final Tile[] tiles = super.tiles.getRow(0);
for (int x = 0; x < tiles.length; x++) {
tiles[x].setCharacter(text[x]);
tiles[x].setBackgroundColor(backgroundColor_normal);
tiles[x].setForegroundColor(foregroundColor_normal);
}
}
@Override
public void createEventListeners(final @NonNull Screen parentScreen) {
if (super.eventListeners.size() > 0) {
return;
}
final MouseInputListener mouseListener = new MouseInputListener() {
@Override
public void mouseDragged(final MouseEvent e) {}
@Override
public void mouseMoved(final MouseEvent e) {
if (intersects(parentScreen.getMousePosition())) {
setStateHovered();
} else {
setStateNormal();
}
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (intersects(parentScreen.getMousePosition())) {
setStatePressed();
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (isInPressedState) {
onClickFunction.run();
}
if (intersects(parentScreen.getMousePosition())) {
setStateHovered();
} else {
setStateNormal();
}
}
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
};
super.eventListeners.add(mouseListener);
}
/**
* Sets the button state to normal if the current state allows for the normal
* state to be set.
*/
protected void setStateNormal() {
boolean canSetState = isInNormalState == false;
canSetState &= isInHoveredState || isInPressedState;
if (canSetState) {
isInNormalState = true;
isInHoveredState = false;
isInPressedState = false;
setColors(backgroundColor_normal, foregroundColor_normal);
redrawFunction.run();
}
}
/**
* Sets the button state to hovered if the current state allows for the normal
* state to be set.
*/
protected void setStateHovered() {
boolean canSetState = isInNormalState || isInPressedState;
canSetState &= isInHoveredState == false;
if (canSetState) {
isInNormalState = false;
isInHoveredState = true;
isInPressedState = false;
setColors(backgroundColor_hover, foregroundColor_hover);
redrawFunction.run();
}
}
/**
* Sets the button state to pressed if the current state allows for the normal
* state to be set.
*/
protected void setStatePressed() {
boolean canSetState = isInNormalState || isInHoveredState;
canSetState &= isInPressedState == false;
if (canSetState) {
isInNormalState = false;
isInHoveredState = false;
isInPressedState = true;
setColors(backgroundColor_pressed, foregroundColor_pressed);
redrawFunction.run();
}
}
/**
* Sets the back/foreground colors of all characters to the specified colors.
*
* @param backgroundColor
* The new background color.
*
* @param foregroundColor
* The new foreground color.
*
* @throws NullPointerException
* If the background or foreground color is null.
*/
private void setColors(final @NonNull Color backgroundColor, final @NonNull Color foregroundColor) {
for (final Tile tile : super.tiles.getRow(0)) {
tile.setBackgroundColor(backgroundColor);
tile.setForegroundColor(foregroundColor);
}
}
/**
* Sets the text displayed on the button.
*
* @param text
* The new text.
*/
public void setText(String text) {
if (text == null) {
text = "";
}
for (int x = 0 ; x < tiles.getWidth() ; x++) {
if (x == 0 || x == 1) {
continue;
}
if (x <= text.length()) {
// Because we skip the first two tiles (checkbox & space after it), we have to use -2 to
// compensate.
tiles.getTileAt(x, 0).setCharacter(text.charAt(x - 2));
} else {
tiles.getTileAt(x, 0).setCharacter(' ');
}
}
}
} |
package org.apache.xerces.validators.schema;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.framework.XMLContentSpecNode;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.framework.XMLValidator;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.utils.ChunkyCharArray;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.utils.ImplementationMessages;
import org.xml.sax.Locator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import java.util.StringTokenizer;
import java.util.Stack;
// for schema
import org.apache.xerces.validators.dtd.XMLContentModel;
import org.apache.xerces.validators.dtd.SimpleContentModel;
import org.apache.xerces.validators.dtd.MixedContentModel;
import org.apache.xerces.validators.dtd.DFAContentModel;
import org.apache.xerces.validators.dtd.CMException;
import org.apache.xerces.validators.dtd.CMNode;
import org.apache.xerces.validators.dtd.CMLeaf;
import org.apache.xerces.validators.dtd.CMUniOp;
import org.apache.xerces.validators.dtd.CMBinOp;
import org.apache.xerces.validators.dtd.InsertableElementsInfo;
import org.apache.xerces.validators.dtd.EntityPool;
import org.apache.xerces.validators.dtd.ElementDeclPool;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.dom.DocumentTypeImpl;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector; // REVISIT remove
import org.apache.xerces.validators.datatype.DatatypeValidator;
import org.apache.xerces.validators.datatype.InvalidDatatypeValueException;
import org.apache.xerces.validators.datatype.IllegalFacetException;
import org.apache.xerces.validators.datatype.IllegalFacetValueException;
import org.apache.xerces.validators.datatype.UnknownFacetException;
import org.apache.xerces.validators.datatype.BooleanValidator;
import org.apache.xerces.validators.datatype.IntegerValidator;
import org.apache.xerces.validators.datatype.StringValidator;
import org.apache.xerces.validators.datatype.FloatValidator;
import org.apache.xerces.validators.datatype.DoubleValidator;
import org.apache.xerces.validators.datatype.DecimalValidator;
import org.apache.xerces.msg.SchemaMessages;
/**
* XSchemaValidator is an <font color="red"><b>experimental</b></font> implementation
* of a validator for the W3C Schema Language. All of its implementation is subject
* to change.
*/
public class XSchemaValidator implements XMLValidator {
// Debugging options
private static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
private static final boolean DEBUG_PRINT_ATTRIBUTES = false;
private static final boolean DEBUG_PRINT_CONTENT = false;
private static final boolean DEBUG_PAREN_DEPTH = false;
private static final boolean DEBUG_MARKUP_DEPTH = false;
private boolean fValidationEnabled = false;
private boolean fDynamicValidation = false;
private boolean fValidationEnabledByDynamic = false;
private boolean fDynamicDisabledByValidation = false;
private boolean fValidating = false;
private boolean fWarningOnDuplicateAttDef = false;
private boolean fWarningOnUndeclaredElements = false;
private EntityPool fEntityPool = null;
private ElementDeclPool fElementDeclPool = null;
private int fStandaloneReader = -1;
private int[] fElementTypeStack = new int[8];
private int[] fContentSpecTypeStack = new int[8];
private int[] fElementChildCount = new int[8];
private int[][] fElementChildren = new int[8][];
private int fElementDepth = -1;
private NamespacesScope fNamespacesScope = null;
private boolean fNamespacesEnabled = false;
private int fRootElementType = -1;
private int fAttrIndex = -1;
private XMLErrorReporter fErrorReporter = null;
private XMLEntityHandler fEntityHandler = null;
private StringPool fStringPool = null;
private boolean fBufferDatatype = false;
private StringBuffer fDatatypeBuffer = new StringBuffer();
private DatatypeValidatorRegistry fDatatypeRegistry = new DatatypeValidatorRegistry();
private int fTypeCount = 0;
private int fGroupCount = 0;
private int fModelGroupCount = 0;
private int fAttributeGroupCount = 0;
private Hashtable fForwardRefs = new Hashtable(); // REVISIT w/ more efficient structure later
private Hashtable fAttrGroupUses = new Hashtable();
// constants
private static final String ELT_COMMENT = "comment";
private static final String ELT_DATATYPEDECL = "datatype";
private static final String ELT_ARCHETYPEDECL = "archetype";
private static final String ELT_ELEMENTDECL = "element";
private static final String ELT_GROUP = "group";
private static final String ELT_ATTRGROUPDECL = "attrGroup";
private static final String ELT_ATTRGROUPREF = "attrGroupRef";
private static final String ELT_MODELGROUPDECL = "modelGroup";
private static final String ELT_MODELGROUPREF = "modelGroupRef";
private static final String ELT_TEXTENTITYDECL = "textEntity";
private static final String ELT_EXTERNALENTITYDECL = "externalEntity";
private static final String ELT_UNPARSEDENTITYDECL = "unparsedEntity";
private static final String ELT_NOTATIONDECL = "notation";
private static final String ELT_REFINES = "refines";
private static final String ELT_ATTRIBUTEDECL = "attribute";
private static final String ATT_NAME = "name";
private static final String ATT_CONTENT = "content";
private static final String ATT_MODEL = "model";
private static final String ATT_ORDER = "order";
private static final String ATT_TYPE = "type";
private static final String ATT_DEFAULT = "default";
private static final String ATT_FIXED = "fixed";
private static final String ATT_COLLECTION = "collection";
private static final String ATT_REF = "ref";
private static final String ATT_ARCHREF = "archRef";
private static final String ATT_SCHEMAABBREV = "schemaAbbrev";
private static final String ATT_SCHEMANAME = "schemaName";
private static final String ATT_MINOCCURS = "minOccurs";
private static final String ATT_MAXOCCURS = "maxOccurs";
private static final String ATT_EXPORT = "export";
private static final String ATTVAL_ANY = "any";
private static final String ATTVAL_MIXED = "mixed";
private static final String ATTVAL_EMPTY = "empty";
private static final String ATTVAL_CHOICE = "choice";
private static final String ATTVAL_SEQ = "seq";
private static final String ATTVAL_ALL = "all";
private static final String ATTVAL_ELEMONLY = "elemOnly";
private static final String ATTVAL_TEXTONLY = "textOnly";
private Document fSchemaDocument;
public XSchemaValidator(StringPool stringPool, XMLErrorReporter errorReporter, XMLEntityHandler entityHandler) {
fEntityPool = new EntityPool(stringPool, errorReporter, true);
fElementDeclPool = new ElementDeclPool(stringPool, errorReporter);
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fStringPool = stringPool;
fDatatypeRegistry.initializeRegistry();
}
public void reset(StringPool stringPool, XMLErrorReporter errorReporter, XMLEntityHandler entityHandler) throws Exception {
fEntityPool.reset(stringPool);
fValidating = fValidationEnabled;
fElementDeclPool.reset(stringPool);
fRootElementType = -1;
fAttrIndex = -1;
fStandaloneReader = -1;
fElementDepth = -1;
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fStringPool = stringPool;
fSchemaDocument = null;
}
/** @deprecated */
public Document getSchemaDocument() {
return fSchemaDocument;
}
// Turning on validation/dynamic turns on validation if it is off, and this
// is remembered. Turning off validation DISABLES validation/dynamic if it
// is on. Turning off validation/dynamic DOES NOT turn off validation if it
// was explicitly turned on, only if it was turned on BECAUSE OF the call to
// turn validation/dynamic on. Turning on validation will REENABLE and turn
// validation/dynamic back on if it was disabled by a call that turned off
// validation while validation/dynamic was enabled.
public void setValidationEnabled(boolean flag) {
fValidationEnabled = flag;
fValidationEnabledByDynamic = false;
if (fValidationEnabled) {
if (fDynamicDisabledByValidation) {
fDynamicValidation = true;
fDynamicDisabledByValidation = false;
}
} else if (fDynamicValidation) {
fDynamicValidation = false;
fDynamicDisabledByValidation = true;
}
fValidating = fValidationEnabled;
}
public boolean getValidationEnabled() {
return fValidationEnabled;
}
public void setDynamicValidationEnabled(boolean flag) {
fDynamicValidation = flag;
fDynamicDisabledByValidation = false;
if (fDynamicValidation) {
if (!fValidationEnabled) {
fValidationEnabledByDynamic = true;
fValidationEnabled = true;
}
} else if (fValidationEnabledByDynamic) {
fValidationEnabled = false;
fValidationEnabledByDynamic = false;
}
}
public boolean getDynamicValidationEnabled() {
return fDynamicValidation;
}
public void setNamespacesEnabled(boolean flag) {
fNamespacesEnabled = flag;
}
public boolean getNamespacesEnabled() {
return fNamespacesEnabled;
}
public void setWarningOnDuplicateAttDef(boolean flag) {
fWarningOnDuplicateAttDef = flag;
}
public boolean getWarningOnDuplicateAttDef() {
return fWarningOnDuplicateAttDef;
}
public void setWarningOnUndeclaredElements(boolean flag) {
fWarningOnUndeclaredElements = flag;
}
public boolean getWarningOnUndeclaredElements() {
return fWarningOnUndeclaredElements;
}
private boolean usingStandaloneReader() {
return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader;
}
private boolean invalidStandaloneAttDef(int elementTypeIndex, int attrNameIndex) {
if (fStandaloneReader == -1)
return false;
if (elementTypeIndex == -1) // we are normalizing a default att value... this ok?
return false;
int attDefIndex = fElementDeclPool.getAttDef(elementTypeIndex, attrNameIndex);
return fElementDeclPool.getAttDefIsExternal(attDefIndex);
}
// Validator interface
public boolean notationDeclared(int notationNameIndex) {
return fEntityPool.lookupNotation(notationNameIndex) != -1;
}
protected void addRequiredNotation(int notationName, Locator locator, int majorCode, int minorCode, Object[] args) throws Exception {
fEntityPool.addRequiredNotation(notationName, locator, majorCode, minorCode, args);
}
public void characters(char[] chars, int offset, int length) throws Exception {
if (fValidating) {
charDataInContent();
if (fBufferDatatype)
fDatatypeBuffer.append(chars, offset, length);
}
}
public void characters(int stringIndex) throws Exception {
if (fValidating) {
charDataInContent();
if (fBufferDatatype)
fDatatypeBuffer.append(fStringPool.toString(stringIndex));
}
}
public void ignorableWhitespace(char[] chars, int offset, int length) throws Exception {
if (fStandaloneReader != -1 && fValidating) {
int elementIndex = getElement(peekElementType());
if (fElementDeclPool.getElementDeclIsExternal(elementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
}
}
public void ignorableWhitespace(int stringIndex) throws Exception {
if (fStandaloneReader != -1 && fValidating) {
int elementIndex = getElement(peekElementType());
if (fElementDeclPool.getElementDeclIsExternal(elementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
}
}
public int getElement(int elementTypeIndex) {
int elementIndex = fElementDeclPool.getElement(elementTypeIndex);
return elementIndex;
}
public int getElementType(int elementIndex) throws Exception {
int name = fElementDeclPool.getElementType(elementIndex);
return name;
}
public int getContentSpecType(int elementIndex) {
int contentspecType = fElementDeclPool.getContentSpecType(elementIndex);
return contentspecType;
}
public int getContentSpec(int elementIndex) {
int contentspec = fElementDeclPool.getContentSpec(elementIndex);
return contentspec;
}
public String getContentSpecAsString(int elementIndex) {
String contentspec = fElementDeclPool.getContentSpecAsString(elementIndex);
return contentspec;
}
public void getContentSpecNode(int contentSpecIndex, XMLContentSpecNode csn) {
fElementDeclPool.getContentSpecNode(contentSpecIndex, csn);
}
public int getAttName(int attDefIndex) {
int attName = fElementDeclPool.getAttName(attDefIndex);
return attName;
}
public int getAttValue(int attDefIndex) {
int attValue = fElementDeclPool.getAttValue(attDefIndex);
return attValue;
}
public int lookupEntity(int entityNameIndex) {
int entityIndex = fEntityPool.lookupEntity(entityNameIndex);
return entityIndex;
}
public boolean externalReferenceInContent(int entityIndex) throws Exception {
boolean external = fEntityPool.isExternalEntity(entityIndex);
if (fStandaloneReader != -1 && fValidating) {
if (external) {
reportRecoverableXMLError(XMLMessages.MSG_EXTERNAL_ENTITY_NOT_PERMITTED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fEntityPool.getEntityName(entityIndex));
} else if (fEntityPool.getEntityDeclIsExternal(entityIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_REFERENCE_TO_EXTERNALLY_DECLARED_ENTITY_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fEntityPool.getEntityName(entityIndex));
}
}
return external;
}
public int valueOfReferenceInAttValue(int entityIndex) throws Exception {
if (fStandaloneReader != -1 && fValidating && fEntityPool.getEntityDeclIsExternal(entityIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_REFERENCE_TO_EXTERNALLY_DECLARED_ENTITY_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fEntityPool.getEntityName(entityIndex));
}
int entityValue = fEntityPool.getEntityValue(entityIndex);
return entityValue;
}
public boolean isExternalEntity(int entityIndex) {
boolean external = fEntityPool.isExternalEntity(entityIndex);
return external;
}
public boolean isUnparsedEntity(int entityIndex) {
boolean external = fEntityPool.isUnparsedEntity(entityIndex);
return external;
}
public int getEntityName(int entityIndex) {
int name = fEntityPool.getEntityName(entityIndex);
return name;
}
public int getEntityValue(int entityIndex) {
int value = fEntityPool.getEntityValue(entityIndex);
return value;
}
public String getPublicIdOfEntity(int entityIndex) {
int publicId = fEntityPool.getPublicId(entityIndex);
return fStringPool.toString(publicId);
}
public int getPublicIdIndexOfEntity(int entityIndex) {
int publicId = fEntityPool.getPublicId(entityIndex);
return publicId;
}
public String getSystemIdOfEntity(int entityIndex) {
int systemId = fEntityPool.getSystemId(entityIndex);
return fStringPool.toString(systemId);
}
public int getSystemIdIndexOfEntity(int entityIndex) {
int systemId = fEntityPool.getSystemId(entityIndex);
return systemId;
}
public int getNotationName(int entityIndex) {
int name = fEntityPool.getNotationName(entityIndex);
return name;
}
public int lookupParameterEntity(int peNameIndex) throws Exception {
throw new RuntimeException("cannot happen 26"); // not called
}
public boolean isExternalParameterEntity(int peIndex) {
throw new RuntimeException("cannot happen 27"); // not called
}
public int getParameterEntityValue(int peIndex) {
throw new RuntimeException("cannot happen 28"); // not called
}
public String getPublicIdOfParameterEntity(int peIndex) {
throw new RuntimeException("cannot happen 29"); // not called
}
public String getSystemIdOfParameterEntity(int peIndex) {
throw new RuntimeException("cannot happen 30"); // not called
}
public void rootElementSpecified(int rootElementType) throws Exception {
if (fValidating) {
fRootElementType = rootElementType; // REVISIT - how does schema do this?
if (fRootElementType != -1 && rootElementType != fRootElementType) {
reportRecoverableXMLError(XMLMessages.MSG_ROOT_ELEMENT_TYPE,
XMLMessages.VC_ROOT_ELEMENT_TYPE,
fRootElementType, rootElementType);
}
}
}
public boolean attributeSpecified(int elementTypeIndex, XMLAttrList attrList, int attrNameIndex, Locator attrNameLocator, int attValueIndex) throws Exception {
int attDefIndex = fElementDeclPool.getAttDef(elementTypeIndex, attrNameIndex);
if (attDefIndex == -1) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(elementTypeIndex),
fStringPool.toString(attrNameIndex) };
fErrorReporter.reportError(attrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
int attType = fStringPool.addSymbol("CDATA");
if (fAttrIndex == -1)
fAttrIndex = attrList.startAttrList();
return attrList.addAttr(attrNameIndex, attValueIndex, attType, true, true) != -1;
}
int attType = fElementDeclPool.getAttType(attDefIndex);
if (attType != fStringPool.addSymbol("CDATA")) {
int enumIndex = fElementDeclPool.getEnumeration(attDefIndex);
attValueIndex = normalizeAttributeValue(elementTypeIndex, attrNameIndex, attValueIndex, attType, enumIndex);
}
if (fAttrIndex == -1)
fAttrIndex = attrList.startAttrList();
return attrList.addAttr(attrNameIndex, attValueIndex, attType, true, true) != -1;
}
public boolean startElement(int elementTypeIndex, XMLAttrList attrList) throws Exception {
int attrIndex = fAttrIndex;
fAttrIndex = -1;
int elementIndex = fElementDeclPool.getElement(elementTypeIndex);
int contentSpecType = (elementIndex == -1) ? -1 : fElementDeclPool.getContentSpecType(elementIndex);
if (contentSpecType == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementTypeIndex);
}
if (elementIndex != -1) {
attrIndex = fElementDeclPool.addDefaultAttributes(elementIndex, attrList, attrIndex, fValidating, fStandaloneReader != -1);
}
checkAttributes(elementIndex, attrList, attrIndex);
if (fValidating && contentSpecType == fStringPool.addSymbol("DATATYPE")) {
fBufferDatatype = true;
fDatatypeBuffer.setLength(0);
}
pushElement(elementTypeIndex, contentSpecType);
return contentSpecType == fStringPool.addSymbol("CHILDREN");
}
public boolean endElement(int elementTypeIndex) throws Exception {
if (fValidating) {
int elementIndex = fElementDeclPool.getElement(elementTypeIndex);
if (elementIndex != -1 && fElementDeclPool.getContentSpecType(elementIndex) != -1) {
int childCount = peekChildCount();
int result = checkContent(elementIndex, childCount, peekChildren());
if (result != -1) {
int majorCode = result != childCount ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE;
reportRecoverableXMLError(majorCode,
0,
fStringPool.toString(elementTypeIndex),
fElementDeclPool.getContentSpecAsString(elementIndex));
}
}
fBufferDatatype = false;
}
popElement();
return peekContentSpecType() == fStringPool.addSymbol("CHILDREN");
}
private int normalizeAttributeValue(int elementTypeIndex, int attrNameIndex, int attValueIndex, int attType, int enumIndex) throws Exception {
// Normalize attribute based upon attribute type...
String attValue = fStringPool.toString(attValueIndex);
if (attType == fStringPool.addSymbol("ID")) {
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
if (newAttValue != attValue && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ID_INVALID,
XMLMessages.VC_ID,
fStringPool.toString(attrNameIndex), newAttValue);
}
// ID - check that the id value is unique within the document (V_TAG8)
if (elementTypeIndex != -1 && !fElementDeclPool.addId(attValueIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ID_NOT_UNIQUE,
XMLMessages.VC_ID,
fStringPool.toString(attrNameIndex), newAttValue);
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
}
} else if (attType == fStringPool.addSymbol("IDREF")) {
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
if (newAttValue != attValue && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_IDREF_INVALID,
XMLMessages.VC_IDREF,
fStringPool.toString(attrNameIndex), newAttValue);
}
// IDREF - remember the id value
if (elementTypeIndex != -1)
fElementDeclPool.addIdRef(attValueIndex);
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
}
} else if (attType == fStringPool.addSymbol("IDREFS")) {
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String idName = tokenizer.nextToken();
if (fValidating) {
if (!XMLCharacterProperties.validName(idName)) {
ok = false;
}
// IDREFS - remember the id values
if (elementTypeIndex != -1)
fElementDeclPool.addIdRef(fStringPool.addSymbol(idName));
}
sb.append(idName);
if (!tokenizer.hasMoreTokens())
break;
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID,
XMLMessages.VC_IDREF,
fStringPool.toString(attrNameIndex), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueIndex = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
}
} else if (attType == fStringPool.addSymbol("ENTITY")) {
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
if (newAttValue != attValue && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
// ENTITY - check that the value is an unparsed entity name (V_TAGa)
int entity = fEntityPool.lookupEntity(attValueIndex);
if (entity == -1 || !fEntityPool.isUnparsedEntity(entity)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attrNameIndex), newAttValue);
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
}
} else if (attType == fStringPool.addSymbol("ENTITIES")) {
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String entityName = tokenizer.nextToken();
// ENTITIES - check that each value is an unparsed entity name (V_TAGa)
if (fValidating) {
int entity = fEntityPool.lookupEntity(fStringPool.addSymbol(entityName));
if (entity == -1 || !fEntityPool.isUnparsedEntity(entity)) {
ok = false;
}
}
sb.append(entityName);
if (!tokenizer.hasMoreTokens())
break;
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attrNameIndex), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueIndex = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
}
} else if (attType == fStringPool.addSymbol("NMTOKEN")) {
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
if (newAttValue != attValue && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
if (!XMLCharacterProperties.validNmtoken(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attrNameIndex), newAttValue);
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
}
} else if (attType == fStringPool.addSymbol("NMTOKENS")) {
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) {
ok = false;
}
sb.append(nmtoken);
if (!tokenizer.hasMoreTokens())
break;
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attrNameIndex), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueIndex = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
}
} else if (attType == fStringPool.addSymbol("NOTATION") ||
attType == fStringPool.addSymbol("ENUMERATION")) {
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
if (newAttValue != attValue && invalidStandaloneAttDef(elementTypeIndex, attrNameIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrNameIndex), attValue, newAttValue);
}
// NOTATION - check that the value is in the AttDef enumeration (V_TAGo)
// ENUMERATION - check that value is in the AttDef enumeration (V_TAG9)
if (!fStringPool.stringInList(enumIndex, attValueIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
attType == fStringPool.addSymbol("NOTATION") ?
XMLMessages.VC_NOTATION_ATTRIBUTES :
XMLMessages.VC_ENUMERATION,
fStringPool.toString(attrNameIndex),
newAttValue, fStringPool.stringListAsString(enumIndex));
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueIndex = fStringPool.addSymbol(newAttValue);
}
} else if (attType == fStringPool.addSymbol("DATATYPE")) {
try { // REVISIT - integrate w/ error handling
String type = fStringPool.toString(enumIndex);
DatatypeValidator v = fDatatypeRegistry.getValidatorFor(type);
if (v != null)
v.validate(attValue);
else
reportSchemaError(SchemaMessageProvider.NoValidatorFor,
new Object [] { type });
} catch (InvalidDatatypeValueException idve) {
reportSchemaError(SchemaMessageProvider.IncorrectDatatype,
new Object [] { idve.getMessage() });
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in attribute datatype validation");
}
} else {
throw new RuntimeException("cannot happen 1");
}
return attValueIndex;
}
// element stack
private void pushElement(int elementTypeIndex, int contentSpecType) {
if (fElementDepth >= 0) {
int[] children = fElementChildren[fElementDepth];
int childCount = fElementChildCount[fElementDepth];
if (children == null) {
children = fElementChildren[fElementDepth] = new int[8];
childCount = 0; // should really assert this...
} else if (childCount == children.length) {
int[] newChildren = new int[childCount * 2];
System.arraycopy(children, 0, newChildren, 0, childCount);
children = fElementChildren[fElementDepth] = newChildren;
}
children[childCount++] = elementTypeIndex;
fElementChildCount[fElementDepth] = childCount;
}
fElementDepth++;
if (fElementDepth == fElementTypeStack.length) {
int[] newStack = new int[fElementDepth * 2];
System.arraycopy(fElementTypeStack, 0, newStack, 0, fElementDepth);
fElementTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, fElementDepth);
fContentSpecTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fElementChildCount, 0, newStack, 0, fElementDepth);
fElementChildCount = newStack;
int[][] newContentStack = new int[fElementDepth * 2][];
System.arraycopy(fElementChildren, 0, newContentStack, 0, fElementDepth);
fElementChildren = newContentStack;
}
fElementTypeStack[fElementDepth] = elementTypeIndex;
fContentSpecTypeStack[fElementDepth] = contentSpecType;
fElementChildCount[fElementDepth] = 0;
}
private void charDataInContent() {
int[] children = fElementChildren[fElementDepth];
int childCount = fElementChildCount[fElementDepth];
if (children == null) {
children = fElementChildren[fElementDepth] = new int[8];
childCount = 0; // should really assert this...
} else if (childCount == children.length) {
int[] newChildren = new int[childCount * 2];
System.arraycopy(children, 0, newChildren, 0, childCount);
children = fElementChildren[fElementDepth] = newChildren;
}
children[childCount++] = -1;
fElementChildCount[fElementDepth] = childCount;
}
private int peekElementType() {
return fElementTypeStack[fElementDepth];
}
private int peekContentSpecType() {
if (fElementDepth < 0) return -1;
return fContentSpecTypeStack[fElementDepth];
}
private int peekChildCount() {
return fElementChildCount[fElementDepth];
}
private int[] peekChildren() {
return fElementChildren[fElementDepth];
}
private void popElement() throws Exception {
if (fElementDepth < 0)
throw new RuntimeException("Element stack underflow");
if (--fElementDepth < 0) {
// Check after document is fully parsed
// (1) check that there was an element with a matching id for every
// IDREF and IDREFS attr (V_IDREF0)
if (fValidating)
checkIDRefNames();
}
}
/**
* Check that the attributes for an element are valid.
* <p>
* This method is called as a convenience. The scanner will do any required
* checks for well-formedness on the attributes, as well as fill out any
* defaulted ones. However, if the validator has any other constraints or
* semantics it must enforce, it can use this API to do so.
* <p>
* The scanner provides the element index (within the decl pool, i.e. not the
* name index which is within the string pool), and the index of the first
* attribute within the attribute pool that holds the attributes of the element.
* By this time, all defaulted attributes are present and all fixed values have
* been confirmed. For most validators, this will be a no-op.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of
* this element.
* @param firstAttrIndex The index within the <code>AttrPool</code> of the
* first attribute of this element, or -1 if there are
* no attributes.
*
* @exception Exception Thrown on error.
*/
private void checkAttributes(int elementIndex, XMLAttrList attrList, int attrIndex) throws Exception
{
if (DEBUG_PRINT_ATTRIBUTES) {
int elementTypeIndex = fElementDeclPool.getElementType(elementIndex);
String elementType = fStringPool.toString(elementTypeIndex);
System.out.print("checkAttributes: <" + elementType);
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
int attNameIndex = attrList.getAttrName(index);
if (attNameIndex != -1) {
int adIndex = fElementDeclPool.getAttDef(elementTypeIndex, attNameIndex);
if (adIndex != -1)
System.out.println(fStringPool.toString(getAttName(adIndex))+" "+
fElementDeclPool.getAttType(adIndex)+" "+
fElementDeclPool.getEnumeration(adIndex));
else
System.out.println("Missing adIndex for "+fStringPool.toString(attNameIndex));
} else
System.out.println("Missing attNameIndex");
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
}
/**
* Check that the content of an element is valid.
* <p>
* This is the method of primary concern to the validator. This method is called
* upon the scanner reaching the end tag of an element. At that time, the
* element's children must be structurally validated, so it calls this method.
* The index of the element being checked (in the decl pool), is provided as
* well as an array of element name indexes of the children. The validator must
* confirm that this element can have these children in this order.
* <p>
* This can also be called to do 'what if' testing of content models just to see
* if they would be valid.
* <p>
* Note that the element index is an index into the element decl pool, whereas
* the children indexes are name indexes, i.e. into the string pool.
* <p>
* A value of -1 in the children array indicates a PCDATA node. All other
* indexes will be positive and represent child elements. The count can be
* zero, since some elements have the EMPTY content model and that must be
* confirmed.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of this
* element.
* @param childCount The number of entries in the <code>children</code> array.
* @param children The children of this element. Each integer is an index within
* the <code>StringPool</code> of the child element name. An index
* of -1 is used to indicate an occurrence of non-whitespace character
* data.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed. If the value returned is equal to the number
* of children, then additional content is required to reach a valid
* ending state.
*
* @exception Exception Thrown on error.
*/
public int checkContent(int elementIndex
, int childCount
, int[] children) throws Exception
{
// Get the element name index from the element
final int elementTypeIndex = fElementDeclPool.getElementType(elementIndex);
if (DEBUG_PRINT_CONTENT)
{
String strTmp = fStringPool.toString(elementTypeIndex);
System.out.println
(
"Name: "
+ strTmp
+ ", Count: "
+ childCount
+ ", ContentSpec: "
+ fElementDeclPool.getContentSpecAsString(elementIndex)
);
for (int index = 0; index < childCount && index < 10; index++) {
if (index == 0) System.out.print(" (");
String childName = (children[index] == -1) ? "#PCDATA" : fStringPool.toString(children[index]);
if (index + 1 == childCount)
System.out.println(childName + ")");
else if (index + 1 == 10)
System.out.println(childName + ",...)");
else
System.out.print(childName + ",");
}
}
// Get out the content spec for this element
final int contentSpec = fElementDeclPool.getContentSpecType(elementIndex);
// Deal with the possible types of content. We try to optimized here
// by dealing specially with content models that don't require the
// full DFA treatment.
if (contentSpec == fStringPool.addSymbol("EMPTY"))
{
// If the child count is greater than zero, then this is
// an error right off the bat at index 0.
if (childCount != 0)
return 0;
}
else if (contentSpec == fStringPool.addSymbol("ANY"))
{
// This one is open game so we don't pass any judgement on it
// at all. Its assumed to fine since it can hold anything.
}
else if (contentSpec == fStringPool.addSymbol("MIXED")
|| contentSpec == fStringPool.addSymbol("CHILDREN"))
{
// Get the content model for this element, faulting it in if needed
XMLContentModel cmElem = null;
try
{
cmElem = getContentModel(elementIndex);
return cmElem.validateContent(childCount, children);
}
catch(CMException excToCatch)
{
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
}
else if (contentSpec == -1)
{
Object[] args = { fStringPool.toString(elementTypeIndex) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
else if (contentSpec == fStringPool.addSymbol("DATATYPE"))
{
XMLContentModel cmElem = null;
try {
cmElem = getContentModel(elementIndex);
return cmElem.validateContent(1, new int[] { fStringPool.addString(fDatatypeBuffer.toString()) });
} catch (CMException cme) {
System.out.println("Internal Error in datatype validation");
} catch (InvalidDatatypeValueException idve) {
reportSchemaError(SchemaMessageProvider.DatatypeError,
new Object [] { idve.getMessage() });
}
/*
boolean DEBUG_DATATYPES = false;
if (DEBUG_DATATYPES) {
System.out.println("Checking content of datatype");
String strTmp = fStringPool.toString(elementTypeIndex);
int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex);
XMLContentSpecNode csn = new XMLContentSpecNode();
fElementDeclPool.getContentSpecNode(contentSpecIndex, csn);
String contentSpecString = fStringPool.toString(csn.value);
System.out.println
(
"Name: "
+ strTmp
+ ", Count: "
+ childCount
+ ", ContentSpec: "
+ contentSpecString
);
for (int index = 0; index < childCount && index < 10; index++) {
if (index == 0) System.out.print(" (");
String childName = (children[index] == -1) ? "#PCDATA" : fStringPool.toString(children[index]);
if (index + 1 == childCount)
System.out.println(childName + ")");
else if (index + 1 == 10)
System.out.println(childName + ",...)");
else
System.out.print(childName + ",");
}
}
try { // REVISIT - integrate w/ error handling
int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex);
XMLContentSpecNode csn = new XMLContentSpecNode();
fElementDeclPool.getContentSpecNode(contentSpecIndex, csn);
String type = fStringPool.toString(csn.value);
DatatypeValidator v = fDatatypeRegistry.getValidatorFor(type);
if (v != null)
v.validate(fDatatypeBuffer.toString());
else
System.out.println("No validator for datatype "+type);
} catch (InvalidDatatypeValueException idve) {
System.out.println("Incorrect datatype: "+idve.getMessage());
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in datatype validation");
}
*/
}
else
{
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_CST,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
// We succeeded
return -1;
}
/**
* Check that all ID references were to ID attributes present in the document.
* <p>
* This method is a convenience call that allows the validator to do any id ref
* checks above and beyond those done by the scanner. The scanner does the checks
* specificied in the XML spec, i.e. that ID refs refer to ids which were
* eventually defined somewhere in the document.
* <p>
* If the validator is for a Schema perhaps, which defines id semantics beyond
* those of the XML specificiation, this is where that extra checking would be
* done. For most validators, this is a no-op.
*
* @exception Exception Thrown on error.
*/
public void checkIDRefNames() throws Exception
{
fElementDeclPool.checkIdRefs();
}
public int whatCanGoHere(int elementIndex
, boolean fullyValid
, InsertableElementsInfo info) throws Exception
{
// Do some basic sanity checking on the info packet. First, make sure
// that insertAt is not greater than the child count. It can be equal,
// which means to get appendable elements, but not greater. Or, if
// the current children array is null, that's bad too.
// Since the current children array must have a blank spot for where
// the insert is going to be, the child count must always be at least
// one.
// Make sure that the child count is not larger than the current children
// array. It can be equal, which means get appendable elements, but not
// greater.
if ((info.insertAt > info.childCount)
|| (info.curChildren == null)
|| (info.childCount < 1)
|| (info.childCount > info.curChildren.length))
{
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_WCGHI,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
int retVal = 0;
try
{
// Get the content model for this element
final XMLContentModel cmElem = getContentModel(elementIndex);
// And delegate this call to it
retVal = cmElem.whatCanGoHere(fullyValid, info);
}
catch(CMException excToCatch)
{
// REVISIT - Translate caught error to the public error handler interface
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
return retVal;
}
// Private methods
// When the element has a 'CHILDREN' model, this method is called to
// create the content model object. It looks for some special case simple
// models and creates SimpleContentModel objects for those. For the rest
// it creates the standard DFA style model.
private final XMLContentModel createChildModel(int elementIndex) throws CMException
{
// Get the content spec node for the element we are working on.
// This will tell us what kind of node it is, which tells us what
// kind of model we will try to create.
XMLContentSpecNode specNode = new XMLContentSpecNode();
int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex);
fElementDeclPool.getContentSpecNode(contentSpecIndex, specNode);
// Check that the left value is not -1, since any content model
// with PCDATA should be MIXED, so we should not have gotten here.
if (specNode.value == -1)
throw new CMException(ImplementationMessages.VAL_NPCD);
if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
// Its a single leaf, so its an 'a' type of content model, i.e.
// just one instance of one element. That one is definitely a
// simple content model.
return new SimpleContentModel(specNode.value, -1, specNode.type);
}
else if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_SEQ))
{
// Lets see if both of the children are leafs. If so, then it
// it has to be a simple content model
XMLContentSpecNode specLeft = new XMLContentSpecNode();
XMLContentSpecNode specRight = new XMLContentSpecNode();
fElementDeclPool.getContentSpecNode(specNode.value, specLeft);
fElementDeclPool.getContentSpecNode(specNode.otherValue, specRight);
if ((specLeft.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
&& (specRight.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF))
{
// Its a simple choice or sequence, so we can do a simple
// content model for it.
return new SimpleContentModel
(
specLeft.value
, specRight.value
, specNode.type
);
}
}
else if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE))
{
// Its a repetition, so see if its one child is a leaf. If so
// its a repetition of a single element, so we can do a simple
// content model for that.
XMLContentSpecNode specLeft = new XMLContentSpecNode();
fElementDeclPool.getContentSpecNode(specNode.value, specLeft);
if (specLeft.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
// It is, so we can create a simple content model here that
// will check for this repetition. We pass -1 for the unused
// right node.
return new SimpleContentModel(specLeft.value, -1, specNode.type);
}
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
// Its not a simple content model, so here we have to create a DFA
// for this element. So we create a DFAContentModel object. He
// encapsulates all of the work to create the DFA.
fLeafCount = 0;
fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>");
CMNode cmn = buildSyntaxTree(contentSpecIndex, specNode);
return new DFAContentModel
(
fStringPool
, cmn
, fLeafCount
);
}
// This method will handle the querying of the content model for a
// particular element. If the element does not have a content model, then
// it will be created.
public XMLContentModel getContentModel(int elementIndex) throws CMException
{
// See if a content model already exists first
XMLContentModel cmRet = fElementDeclPool.getContentModel(elementIndex);
// If we have one, just return that. Otherwise, gotta create one
if (cmRet != null)
return cmRet;
// Get the type of content this element has
final int contentSpec = fElementDeclPool.getContentSpecType(elementIndex);
// And create the content model according to the spec type
if (contentSpec == fStringPool.addSymbol("MIXED"))
{
// Just create a mixel content model object. This type of
// content model is optimized for mixed content validation.
XMLContentSpecNode specNode = new XMLContentSpecNode();
int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex);
makeContentList(contentSpecIndex, specNode);
cmRet = new MixedContentModel(fCount, fContentList);
}
else if (contentSpec == fStringPool.addSymbol("CHILDREN"))
{
// This method will create an optimal model for the complexity
// of the element's defined model. If its simple, it will create
// a SimpleContentModel object. If its a simple list, it will
// create a SimpleListContentModel object. If its complex, it
// will create a DFAContentModel object.
cmRet = createChildModel(elementIndex);
}
else if (contentSpec == fStringPool.addSymbol("DATATYPE")) {
cmRet = new DatatypeContentModel(fDatatypeRegistry, fElementDeclPool, fStringPool, elementIndex);
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
// Add the new model to the content model for this element
fElementDeclPool.setContentModel(elementIndex, cmRet);
return cmRet;
}
// This method will build our syntax tree by recursively going though
// the element's content model and creating new CMNode type node for
// the model, and rewriting '?' and '+' nodes along the way.
// On final return, the head node of the syntax tree will be returned.
// This top node will be a sequence node with the left side being the
// rewritten content, and the right side being a special end of content
// node.
// We also count the non-epsilon leaf nodes, which is an important value
// that is used in a number of places later.
private int fLeafCount = 0;
private int fEpsilonIndex = -1;
private final CMNode
buildSyntaxTree(int startNode, XMLContentSpecNode specNode) throws CMException
{
// We will build a node at this level for the new tree
CMNode nodeRet = null;
getContentSpecNode(startNode, specNode);
// If this node is a leaf, then its an easy one. We just add it
// to the tree.
if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
// Create a new leaf node, and pass it the current leaf count,
// which is its DFA state position. Bump the leaf count after
// storing it. This makes the positions zero based since we
// store first and then increment.
nodeRet = new CMLeaf(specNode.type, specNode.value, fLeafCount++);
}
else
{
// Its not a leaf, so we have to recurse its left and maybe right
// nodes. Save both values before we recurse and trash the node.
final int leftNode = specNode.value;
final int rightNode = specNode.otherValue;
if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_SEQ))
{
// Recurse on both children, and return a binary op node
// with the two created sub nodes as its children. The node
// type is the same type as the source.
nodeRet = new CMBinOp
(
specNode.type
, buildSyntaxTree(leftNode, specNode)
, buildSyntaxTree(rightNode, specNode)
);
}
else if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE)
{
nodeRet = new CMUniOp
(
specNode.type
, buildSyntaxTree(leftNode, specNode)
);
}
else if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE)
{
// Convert to (x|epsilon)
nodeRet = new CMBinOp
(
XMLContentSpecNode.CONTENTSPECNODE_CHOICE
, buildSyntaxTree(leftNode, specNode)
, new CMLeaf(XMLContentSpecNode.CONTENTSPECNODE_LEAF, fEpsilonIndex)
);
}
else if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE)
{
// Convert to (x,x*)
nodeRet = new CMBinOp
(
XMLContentSpecNode.CONTENTSPECNODE_SEQ
, buildSyntaxTree(leftNode, specNode)
, new CMUniOp
(
XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE
, buildSyntaxTree(leftNode, specNode)
)
);
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
}
// And return our new node for this level
return nodeRet;
}
private int fCount = 0;
private int[] fContentList = new int[64];
private final void makeContentList(int startNode, XMLContentSpecNode specNode) throws CMException {
// Ok, we need to build up an array of the possible children
// under this element. The mixed content model can only be a
// repeated series of alternations with no numeration or ordering.
// So we call a local recursive method to iterate the tree and
// build up the array.
// So we get the content spec of the element, which gives us the
// starting node. Everything else kicks off from there. We pass
// along a content node for each iteration to use so that it does
// not have to create and trash lots of objects.
while (true)
{
fCount = 0;
try
{
fCount = buildContentList
(
startNode
, 0
, specNode
);
}
catch(IndexOutOfBoundsException excToCatch)
{
// Expand the array and try it again. Yes, this is
// piggy, but the odds of it ever actually happening
// are slim to none.
fContentList = new int[fContentList.length * 2];
fCount = 0;
continue;
}
// We survived, so break out
break;
}
}
private final int buildContentList( int startNode
, int count
, XMLContentSpecNode specNode) throws CMException
{
// Get the content spec for the passed start node
fElementDeclPool.getContentSpecNode(startNode, specNode);
// If this node is a leaf, then add it to our list and return.
if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
fContentList[count++] = specNode.value;
return count;
}
// Its not a leaf, so we have to recurse its left and maybe right
// nodes. Save both values before we recurse and trash the node.
final int leftNode = specNode.value;
final int rightNode = specNode.otherValue;
if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_SEQ))
{
// Recurse on the left and right nodes of this guy, making sure
// to keep the count correct.
count = buildContentList(leftNode, count, specNode);
count = buildContentList(rightNode, count, specNode);
}
else if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE))
{
// Just do the left node on this one
count = buildContentList(leftNode, count, specNode);
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
// And return our accumlated new count
return count;
}
protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
null,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception {
Object[] args = { string1 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception {
Object[] args = { string1, string2 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception {
Object[] args = { string1, string2, string3 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
// content spec node types
/** Occurrence count: [0, n]. */
private static final int CONTENTSPECNODE_ZERO_TO_N = XMLContentSpecNode.CONTENTSPECNODE_SEQ + 1;
/** Occurrence count: [m, n]. */
private static final int CONTENTSPECNODE_M_TO_N = CONTENTSPECNODE_ZERO_TO_N + 1;
/** Occurrence count: [m, *). */
private static final int CONTENTSPECNODE_M_OR_MORE = CONTENTSPECNODE_M_TO_N + 1;
private DOMParser fSchemaParser = null;
public void loadSchema(String uri) {
// get URI to schema file
//String uri = getSchemaURI(data);
//if (uri == null) {
// System.err.println("error: malformed href pseudo-attribute ("+data+')');
// return;
// resolve schema file relative to *this* file
String systemId = fEntityHandler.expandSystemId(uri);
// create parser for schema
if (fSchemaParser == null) {
fSchemaParser = new DOMParser() {
public void ignorableWhitespace(char ch[], int start, int length) {}
public void ignorableWhitespace(int dataIdx) {}
};
fSchemaParser.setEntityResolver(new Resolver());
fSchemaParser.setErrorHandler(new ErrorHandler());
}
// parser schema file
try {
fSchemaParser.setFeature("http://xml.org/sax/features/validation", true);
fSchemaParser.setFeature("http://apache.org/xml/features/dom/defer-node-expansion", false);
fSchemaParser.parse(systemId);
}
catch (SAXException se) {
se.getException().printStackTrace();
System.err.println("error parsing schema file");
// System.exit(1);
}
catch (Exception e) {
e.printStackTrace();
System.err.println("error parsing schema file");
// System.exit(1);
}
fSchemaDocument = fSchemaParser.getDocument();
if (fSchemaDocument == null) {
System.err.println("error: couldn't load schema file!");
return;
}
// traverse schema
try {
Element root = fSchemaDocument.getDocumentElement();
traverseSchema(root);
}
catch (Exception e) {
e.printStackTrace(System.err);
// System.exit(1);
}
}
private void traverseSchema(Element root) throws Exception {
// is there anything to do?
if (root == null) {
return;
}
// run through children
for (Element child = XUtil.getFirstChildElement(root);
child != null;
child = XUtil.getNextSiblingElement(child)) {
//System.out.println("child: "+child.getNodeName()+' '+child.getAttribute(ATT_NAME));
// Element type
String name = child.getNodeName();
if (name.equals(ELT_COMMENT)) {
traverseComment(child);
} else if (name.equals(ELT_DATATYPEDECL)) {
traverseDatatypeDecl(child);
} else if (name.equals(ELT_ARCHETYPEDECL)) {
traverseTypeDecl(child);
} else if (name.equals(ELT_ELEMENTDECL)) { // && child.getAttribute(ATT_REF).equals("")) {
traverseElementDecl(child);
} else if (name.equals(ELT_ATTRGROUPDECL)) {
traverseAttrGroup(child);
} else if (name.equals(ELT_MODELGROUPDECL)) {
traverseModelGroup(child);
}
// Entities
else if (name.equals(ELT_TEXTENTITYDECL) ||
name.equals(ELT_EXTERNALENTITYDECL) ||
name.equals(ELT_UNPARSEDENTITYDECL)) {
int entityName = fStringPool.addSymbol(child.getAttribute(ATT_NAME));
if (name.equals(ELT_TEXTENTITYDECL)) {
int value = fStringPool.addString(child.getFirstChild().getFirstChild().getNodeValue());
fEntityPool.addEntityDecl(entityName, value, -1, -1, -1, -1, true);
}
else {
int publicId = fStringPool.addString(child.getAttribute("public"));
int systemId = fStringPool.addString(child.getAttribute("system"));
if (name.equals(ELT_EXTERNALENTITYDECL)) {
fEntityPool.addEntityDecl(entityName, -1, -1, publicId, systemId, -1, true);
}
else {
int notationName = fStringPool.addSymbol(child.getAttribute("notation"));
fEntityPool.addEntityDecl(entityName, -1, -1, publicId, systemId, notationName, true);
}
}
}
// Notation
else if (name.equals(ELT_NOTATIONDECL)) {
int notationName = fStringPool.addSymbol(child.getAttribute(ATT_NAME));
int publicId = fStringPool.addString(child.getAttribute("public"));
int systemId = fStringPool.addString(child.getAttribute("system"));
fEntityPool.addNotationDecl(notationName, publicId, systemId, true);
}
} // for each child node
cleanupForwardReferences();
} // traverseSchema(Element)
/**
* this method is going to be needed to handle any elementDecl derived constructs which
* need to copy back attributes that haven't been declared yet.
* right now that's just attributeGroups and types -- grrr.
*/
private void cleanupForwardReferences() {
for (java.util.Enumeration keys = fForwardRefs.keys(); keys.hasMoreElements();) {
Object k = keys.nextElement();
int ik = ((Integer) k).intValue();
cleanupForwardReferencesTo(ik);
}
}
private void cleanupForwardReferencesTo(int r) {
Vector referrers = (Vector) fForwardRefs.get(new Integer(r));
if (referrers == null) return;
// System.out.println("referee "+r+" csnIndex= "+getContentSpec(getElement(r)));
for (int i = 0; i < referrers.size(); i++) {
int ref = ((Integer) referrers.elementAt(i)).intValue();
// System.out.println("referrer "+referrers.elementAt(i)+ " csnIndex = "+getContentSpec(getElement(((Integer)referrers.elementAt(i)).intValue())));
// System.out.println("copying from "+fStringPool.toString(r)+" to "+fStringPool.toString(ref));
fElementDeclPool.copyAtts(r, ((Integer) referrers.elementAt(i)).intValue());
// try {
// fElementDeclPool.fixupDeclaredElements(ref, r);
// } catch (Exception e) {
// System.out.println("Error while cleaning up");
// cleanupForwardReferencesTo(ref);
}
}
private void traverseComment(Element comment) {
return; // do nothing
}
private int traverseTypeDecl(Element typeDecl) throws Exception {
String typeName = typeDecl.getAttribute(ATT_NAME);
String content = typeDecl.getAttribute(ATT_CONTENT);
String model = typeDecl.getAttribute(ATT_MODEL);
String order = typeDecl.getAttribute(ATT_ORDER);
String type = typeDecl.getAttribute(ATT_TYPE);
String deflt = typeDecl.getAttribute(ATT_DEFAULT);
String fixed = typeDecl.getAttribute(ATT_FIXED);
String schemaAbbrev = typeDecl.getAttribute(ATT_SCHEMAABBREV);
String schemaName = typeDecl.getAttribute(ATT_SCHEMANAME);
if (typeName.equals("")) { // gensym a unique name
typeName = "http:
}
// integrity checks
if (type.equals("")) {
if (!schemaAbbrev.equals(""))
reportSchemaError(SchemaMessageProvider.AttMissingType,
new Object [] { "schemaAbbrev" });
if (!schemaName.equals(""))
reportSchemaError(SchemaMessageProvider.AttMissingType,
new Object [] { "schemaName" });
if (!deflt.equals(""))
reportSchemaError(SchemaMessageProvider.AttMissingType,
new Object [] { "default" });
if (!fixed.equals(""))
reportSchemaError(SchemaMessageProvider.AttMissingType,
new Object [] { "fixed" });
} else {
if (fDatatypeRegistry.getValidatorFor(type) != null) // must be datatype
reportSchemaError(SchemaMessageProvider.NotADatatype,
new Object [] { type }); //REVISIT check forward refs
if (!content.equals(ATTVAL_TEXTONLY)) //REVISIT: check if attribute was specified, if not, set
reportSchemaError(SchemaMessageProvider.TextOnlyContentWithType, null);
// REVISIT handle datatypes
}
Element child = XUtil.getFirstChildElement(typeDecl);
Element refines = null;
// skip the refines
if (child != null && child.getNodeName().equals(ELT_REFINES)) {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Refinement" });
refines = child;
child = XUtil.getNextSiblingElement(child);
}
int contentSpecType = 0;
int csnType = 0;
boolean mixedContent = false;
boolean elementContent = false;
boolean textContent = false;
boolean buildAll = false;
int allChildren[] = null;
int allChildCount = 0;
int left = -2;
int right = -2;
boolean hadContent = false;
if (order.equals(ATTVAL_CHOICE)) {
csnType = XMLContentSpecNode.CONTENTSPECNODE_CHOICE;
contentSpecType = fStringPool.addSymbol("CHILDREN");
} else if (order.equals(ATTVAL_SEQ)) {
csnType = XMLContentSpecNode.CONTENTSPECNODE_SEQ;
contentSpecType = fStringPool.addSymbol("CHILDREN");
} else if (order.equals(ATTVAL_ALL)) {
buildAll = true;
allChildren = new int[((org.apache.xerces.dom.NodeImpl)typeDecl).getLength()];
allChildCount = 0;
}
if (content.equals(ATTVAL_EMPTY)) {
contentSpecType = fStringPool.addSymbol("EMPTY");
left = -1; // no contentSpecNode needed
} else if (content.equals(ATTVAL_ANY)) {
contentSpecType = fStringPool.addSymbol("ANY");
left = -1; // no contentSpecNode needed
} else if (content.equals(ATTVAL_MIXED)) {
contentSpecType = fStringPool.addSymbol("MIXED");
mixedContent = true;
csnType = XMLContentSpecNode.CONTENTSPECNODE_CHOICE;
} else if (content.equals(ATTVAL_ELEMONLY)) {
elementContent = true;
} else if (content.equals(ATTVAL_TEXTONLY)) {
textContent = true;
}
if (mixedContent) {
// add #PCDATA leaf
left = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF,
-1, // -1 means "#PCDATA" is name
-1, false);
}
Vector uses = new Vector();
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
hadContent = true;
String childName = child.getNodeName();
if (childName.equals(ELT_ELEMENTDECL)) {
if (child.getAttribute(ATT_REF).equals("")) { // elt decl
if (elementContent) //REVISIT: no support for nested type declarations
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Nesting element declarations" });
else
reportSchemaError(SchemaMessageProvider.NestedOnlyInElemOnly, null);
} else if (mixedContent || elementContent) { // elt ref
index = traverseElementRef(child);
} else {
reportSchemaError(SchemaMessageProvider.EltRefOnlyInMixedElemOnly, null);
}
} else if (childName.equals(ELT_GROUP)) {
if (elementContent && !buildAll) {
int groupNameIndex = traverseGroup(child);
index = getContentSpec(getElement(groupNameIndex));
} else if (!elementContent)
reportSchemaError(SchemaMessageProvider.OnlyInEltContent,
new Object [] { "group" });
else // buildAll
reportSchemaError(SchemaMessageProvider.OrderIsAll,
new Object [] { "group" } );
} else if (childName.equals(ELT_MODELGROUPREF)) {
if (elementContent && !buildAll) {
int modelGroupNameIndex = traverseModelGroup(child);
index = getContentSpec(getElement(modelGroupNameIndex));
if (index == -1)
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Forward reference to model group" });
index = expandContentModel(index, child);
} else if (!elementContent)
reportSchemaError(SchemaMessageProvider.OnlyInEltContent,
new Object [] { "modelGroupRef" });
else // buildAll
reportSchemaError(SchemaMessageProvider.OrderIsAll,
new Object [] { "modelGroupRef" });
} else if (childName.equals(ELT_ATTRIBUTEDECL) || childName.equals(ELT_ATTRGROUPREF)) {
break; // attr processing is done below
} else { // datatype qual
if (type.equals(""))
reportSchemaError(SchemaMessageProvider.DatatypeWithType, null);
else
reportSchemaError(SchemaMessageProvider.DatatypeQualUnsupported,
new Object [] { childName });
}
uses.addElement(new Integer(index));
if (buildAll) {
allChildren[allChildCount++] = index;
} else if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fElementDeclPool.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (buildAll) {
left = buildAllModel(allChildren,allChildCount);
} else {
if (hadContent && right != -2)
left = fElementDeclPool.addContentSpecNode(csnType, left, right, false);
if (mixedContent && hadContent) {
// set occurrence count
left = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE,
left, -1, false);
}
}
// stick in ElementDeclPool as a hack
int typeNameIndex = fStringPool.addSymbol(typeName); //REVISIT namespace clashes possible
int typeIndex = fElementDeclPool.addElementDecl(typeNameIndex, contentSpecType, left, false);
for (int x = 0; x < uses.size(); x++)
addUse(typeNameIndex, (Integer)uses.elementAt(x));
// (attribute | attrGroupRef)*
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getNodeName();
if (childName.equals(ELT_ATTRIBUTEDECL)) {
traverseAttributeDecl(child, typeIndex);
} else if (childName.equals(ELT_ATTRGROUPREF)) {
int index = traverseAttrGroupRef(child);
if (getContentSpec(getElement(index)) == -1) {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Forward References to attrGroup" });
Vector v = null;
Integer i = new Integer(index);
if ((v = (Vector) fForwardRefs.get(i)) == null)
v = new Vector();
v.addElement(new Integer(typeNameIndex));
fForwardRefs.put(i,v);
addUse(typeNameIndex, index);
} else
fElementDeclPool.copyAtts(index, typeNameIndex);
}
}
return typeNameIndex;
}
private int traverseGroup(Element groupDecl) throws Exception {
String groupName = groupDecl.getAttribute(ATT_NAME);
String collection = groupDecl.getAttribute(ATT_COLLECTION);
String order = groupDecl.getAttribute(ATT_ORDER);
if (groupName.equals("")) { // gensym a unique name
groupName = "http:
}
Element child = XUtil.getFirstChildElement(groupDecl);
int contentSpecType = 0;
int csnType = 0;
boolean buildAll = false;
int allChildren[] = null;
int allChildCount = 0;
if (order.equals(ATTVAL_CHOICE)) {
csnType = XMLContentSpecNode.CONTENTSPECNODE_CHOICE;
contentSpecType = fStringPool.addSymbol("CHILDREN");
} else if (order.equals(ATTVAL_SEQ)) {
csnType = XMLContentSpecNode.CONTENTSPECNODE_SEQ;
contentSpecType = fStringPool.addSymbol("CHILDREN");
} else if (order.equals(ATTVAL_ALL)) {
buildAll = true;
allChildren = new int[((org.apache.xerces.dom.NodeImpl)groupDecl).getLength()];
allChildCount = 0;
}
int left = -2;
int right = -2;
boolean hadContent = false;
int groupIndices[] = new int [((org.apache.xerces.dom.NodeImpl)groupDecl).getLength()];
int numGroups = 0;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
hadContent = true;
String childName = child.getNodeName();
if (childName.equals(ELT_ELEMENTDECL)) {
if (child.getAttribute(ATT_REF).equals(""))
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Nesting element declarations" });
else
index = traverseElementRef(child);
} else if (childName.equals(ELT_GROUP)) {
if (!buildAll) {
int groupNameIndex = traverseGroup(child);
groupIndices[numGroups++] = groupNameIndex;
index = getContentSpec(getElement(groupNameIndex));
} else
reportSchemaError(SchemaMessageProvider.OrderIsAll,
new Object [] { "group" } );
} else if (childName.equals(ELT_MODELGROUPREF)) {
if (!buildAll) {
int modelGroupNameIndex = traverseModelGroupRef(child);
index = getContentSpec(getElement(modelGroupNameIndex));
index = expandContentModel(index, child);
} else
reportSchemaError(SchemaMessageProvider.OrderIsAll,
new Object [] { "modelGroupRef" });
} else {
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "group", childName });
}
if (buildAll) {
allChildren[allChildCount++] = index;
} else if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fElementDeclPool.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (buildAll) {
left = buildAllModel(allChildren,allChildCount);
} else {
if (hadContent && right != -2)
left = fElementDeclPool.addContentSpecNode(csnType, left, right, false);
}
left = expandContentModel(left, groupDecl);
// stick in ElementDeclPool as a hack
int groupNameIndex = fStringPool.addSymbol(groupName); //REVISIT namespace clashes possible
int groupIndex = fElementDeclPool.addElementDecl(groupNameIndex, contentSpecType, left, false);
return groupNameIndex;
}
private int traverseModelGroup(Element modelGroupDecl) throws Exception {
String modelGroupName = modelGroupDecl.getAttribute(ATT_NAME);
String order = modelGroupDecl.getAttribute(ATT_ORDER);
if (modelGroupName.equals("")) { // gensym a unique name
modelGroupName = "http:
}
Element child = XUtil.getFirstChildElement(modelGroupDecl);
int contentSpecType = 0;
int csnType = 0;
boolean buildAll = false;
int allChildren[] = null;
int allChildCount = 0;
if (order.equals(ATTVAL_CHOICE)) {
csnType = XMLContentSpecNode.CONTENTSPECNODE_CHOICE;
contentSpecType = fStringPool.addSymbol("CHILDREN");
} else if (order.equals(ATTVAL_SEQ)) {
csnType = XMLContentSpecNode.CONTENTSPECNODE_SEQ;
contentSpecType = fStringPool.addSymbol("CHILDREN");
} else if (order.equals(ATTVAL_ALL)) {
buildAll = true;
allChildren = new int[((org.apache.xerces.dom.NodeImpl)modelGroupDecl).getLength()];
allChildCount = 0;
}
int left = -2;
int right = -2;
boolean hadContent = false;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
int index = -2;
hadContent = true;
String childName = child.getNodeName();
if (childName.equals(ELT_ELEMENTDECL)) {
if (child.getAttribute(ATT_REF).equals(""))
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Nesting element declarations" });
else {
index = traverseElementRef(child);
}
} else if (childName.equals(ELT_GROUP)) {
int groupNameIndex = traverseGroup(child);
index = getContentSpec(getElement(groupNameIndex));
} else if (childName.equals(ELT_MODELGROUPREF)) {
int modelGroupNameIndex = traverseModelGroupRef(child);
index = getContentSpec(getElement(modelGroupNameIndex));
index = expandContentModel(index, child);
} else {
reportSchemaError(SchemaMessageProvider.GroupContentRestricted,
new Object [] { "modelGroup", childName });
}
if (buildAll) {
allChildren[allChildCount++] = index;
} else if (left == -2) {
left = index;
} else if (right == -2) {
right = index;
} else {
left = fElementDeclPool.addContentSpecNode(csnType, left, right, false);
right = index;
}
}
if (buildAll) {
left = buildAllModel(allChildren,allChildCount);
} else {
if (hadContent && right != -2)
left = fElementDeclPool.addContentSpecNode(csnType, left, right, false);
}
left = expandContentModel(left, modelGroupDecl);
// stick in ElementDeclPool as a hack
int modelGroupNameIndex = fStringPool.addSymbol(modelGroupName); //REVISIT namespace clashes possible
int modelGroupIndex = fElementDeclPool.addElementDecl(modelGroupNameIndex, contentSpecType, left, false);
return modelGroupNameIndex;
}
private int traverseModelGroupRef(Element modelGroupRef) {
String name = modelGroupRef.getAttribute(ATT_NAME);
int index = fStringPool.addSymbol(name);
// if (getContentSpec(getElement(index)) == -1) fElementDeclPool.setContentSpec(index, -2);
return index;
}
public int traverseDatatypeDecl(Element datatypeDecl) throws Exception {
int newTypeName = fStringPool.addSymbol(datatypeDecl.getAttribute(ATT_NAME));
int export = fStringPool.addSymbol(datatypeDecl.getAttribute(ATT_EXPORT));
Element datatypeChild = XUtil.getFirstChildElement(datatypeDecl);
int basetype = fStringPool.addSymbol(datatypeChild.getNodeName());
// check that base type is defined
//REVISIT: how do we do the extension mechanism? hardwired type name?
DatatypeValidator baseValidator = fDatatypeRegistry.getValidatorFor(datatypeChild.getAttribute(ATT_NAME));
if (baseValidator == null) {
reportSchemaError(SchemaMessageProvider.UnknownBaseDatatype,
new Object [] { datatypeChild.getAttribute(ATT_NAME), datatypeDecl.getAttribute(ATT_NAME) });
return -1;
}
// build facet list
int numFacets = 0;
int numEnumerationLiterals = 0;
Hashtable facetData = new Hashtable();
Vector enumData = new Vector();
Node facet = datatypeChild.getNextSibling();
while (facet != null) {
if (facet.getNodeType() == Node.ELEMENT_NODE) {
numFacets++;
if (facet.getNodeName().equals(DatatypeValidator.ENUMERATION)) {
Node literal = XUtil.getFirstChildElement(facet);
while (literal != null) {
numEnumerationLiterals++;
enumData.addElement(literal.getFirstChild().getNodeValue());
literal = XUtil.getNextSiblingElement(literal);
}
} else {
facetData.put(facet.getNodeName(),facet.getFirstChild().getNodeValue());
}
}
facet = facet.getNextSibling();
}
if (numEnumerationLiterals > 0) {
facetData.put(DatatypeValidator.ENUMERATION, enumData);
}
// create & register validator for "generated" type if it doesn't exist
try {
DatatypeValidator newValidator = (DatatypeValidator) baseValidator.getClass().newInstance();
if (numFacets > 0)
newValidator.setFacets(facetData);
fDatatypeRegistry.addValidator(fStringPool.toString(newTypeName),newValidator);
} catch (Exception e) {
reportSchemaError(SchemaMessageProvider.DatatypeError,
new Object [] { e.getMessage() });
}
return -1;
}
private int traverseElementDecl(Element elementDecl) throws Exception {
int contentSpecType = -1;
int contentSpecNodeIndex = -1;
int typeNameIndex = -1;
String name = elementDecl.getAttribute(ATT_NAME);
String ref = elementDecl.getAttribute(ATT_REF);
String archRef = elementDecl.getAttribute(ATT_ARCHREF);
String type = elementDecl.getAttribute(ATT_TYPE);
String schemaAbbrev = elementDecl.getAttribute(ATT_SCHEMAABBREV);
String schemaName = elementDecl.getAttribute(ATT_SCHEMANAME);
String minOccurs = elementDecl.getAttribute(ATT_MINOCCURS);
String maxOccurs = elementDecl.getAttribute(ATT_MAXOCCURS);
String export = elementDecl.getAttribute(ATT_EXPORT);
int attrCount = 0;
if (!ref.equals("")) attrCount++;
if (!type.equals("")) attrCount++;
if (!archRef.equals("")) attrCount++;
//REVISIT top level check for ref & archref
if (attrCount > 1)
reportSchemaError(SchemaMessageProvider.OneOfTypeRefArchRef, null);
if (!ref.equals("") || !archRef.equals("")) {
if (XUtil.getFirstChildElement(elementDecl) != null)
reportSchemaError(SchemaMessageProvider.NoContentForRef, null);
int typeName = (!ref.equals("")) ? fStringPool.addSymbol(ref) : fStringPool.addSymbol(archRef);
contentSpecNodeIndex = getContentSpec(getElement(typeName));
contentSpecType = getContentSpecType(getElement(typeName));
int elementNameIndex = fStringPool.addSymbol(name);
int elementIndex = -1;
if (contentSpecNodeIndex == -1) {
contentSpecType = XMLContentSpecNode.CONTENTSPECNODE_LEAF;
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF,
elementNameIndex, -1, false);
fElementDeclPool.addElementDecl(elementNameIndex, contentSpecType, contentSpecNodeIndex, true);
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Forward references to archetypes" });
Vector v = null;
Integer i = new Integer(typeName);
if ((v = (Vector) fForwardRefs.get(i)) == null)
v = new Vector();
v.addElement(new Integer(elementNameIndex));
fForwardRefs.put(i,v);
addUse(elementNameIndex, typeName);
} else {
fElementDeclPool.addElementDecl(elementNameIndex, contentSpecType, contentSpecNodeIndex, true);
// copy up attribute decls from type object
fElementDeclPool.copyAtts(typeName, elementNameIndex);
}
return elementNameIndex;
}
// element has a single child element, either a datatype or a type, null if primitive
Element content = XUtil.getFirstChildElement(elementDecl);
if (content != null) {
String contentName = content.getNodeName();
if (contentName.equals(ELT_ARCHETYPEDECL)) {
typeNameIndex = traverseTypeDecl(content);
contentSpecNodeIndex = getContentSpec(getElement(typeNameIndex));
contentSpecType = getContentSpecType(getElement(typeNameIndex));
} else if (contentName.equals(ELT_DATATYPEDECL)) {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Nesting datatype declarations" });
// contentSpecNodeIndex = traverseDatatypeDecl(content);
// contentSpecType = fStringPool.addSymbol("DATATYPE");
} else if (!type.equals("")) { // datatype
contentSpecType = fStringPool.addSymbol("DATATYPE");
// set content spec node index to leaf
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF,
fStringPool.addSymbol(content.getAttribute(ATT_NAME)),
-1, false);
// set occurrance count
contentSpecNodeIndex = expandContentModel(contentSpecNodeIndex, content);
} else if (type.equals("")) { // "untyped" leaf
// untyped leaf element decl
contentSpecType = fStringPool.addSymbol("CHILDREN");
// add leaf
int leftIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF,
fStringPool.addSymbol(content.getAttribute(ATT_NAME)),
-1, false);
// set occurrence count
contentSpecNodeIndex = expandContentModel(contentSpecNodeIndex, content);
} else {
System.out.println("unhandled case in element decl code");
}
} else if (!type.equals("")) { // type specified in attribute, not content
contentSpecType = fStringPool.addSymbol("DATATYPE");
// set content spec node index to leaf
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF,
fStringPool.addSymbol(type),
-1, false);
// set occurrance count
contentSpecNodeIndex = expandContentModel(contentSpecNodeIndex, elementDecl);
}
// Create element decl
int elementNameIndex = fStringPool.addSymbol(elementDecl.getAttribute(ATT_NAME));
// add element decl to pool
int elementIndex = fElementDeclPool.addElementDecl(elementNameIndex, contentSpecType, contentSpecNodeIndex, true);
// System.out.println("elementIndex:"+elementIndex+" "+elementDecl.getAttribute(ATT_NAME)+" eltType:"+elementName+" contentSpecType:"+contentSpecType+
// " SpecNodeIndex:"+ contentSpecNodeIndex);
// copy up attribute decls from type object
fElementDeclPool.copyAtts(typeNameIndex, elementNameIndex);
return elementNameIndex;
}
private int traverseElementRef(Element elementRef) {
String elementName = elementRef.getAttribute(ATT_REF);
int elementTypeIndex = fStringPool.addSymbol(elementName);
int contentSpecNodeIndex = 0;
try {
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF,
elementTypeIndex, -1, false);
contentSpecNodeIndex = expandContentModel(contentSpecNodeIndex, elementRef);
} catch (Exception e) {
//REVISIT: integrate w/ error handling
e.printStackTrace();
}
return contentSpecNodeIndex;
}
//REVISIT: elementIndex API is ugly
private void traverseAttributeDecl(Element attrDecl, int elementIndex) throws Exception {
// attribute name
int attName = fStringPool.addSymbol(attrDecl.getAttribute(ATT_NAME));
// attribute type
int attType = -1;
int enumeration = -1;
String datatype = attrDecl.getAttribute(ATT_TYPE);
if (datatype.equals("")) {
attType = fStringPool.addSymbol("CDATA");
} else {
if (datatype.equals("string")) {
attType = fStringPool.addSymbol("CDATA");
} else if (datatype.equals("ID")) {
attType = fStringPool.addSymbol("ID");
} else if (datatype.equals("IDREF")) {
attType = fStringPool.addSymbol("IDREF");
} else if (datatype.equals("IDREFS")) {
attType = fStringPool.addSymbol("IDREFS");
} else if (datatype.equals("ENTITY")) {
attType = fStringPool.addSymbol("ENTITY");
} else if (datatype.equals("ENTITIES")) {
attType = fStringPool.addSymbol("ENTITIES");
} else if (datatype.equals("NMTOKEN")) {
Element e = XUtil.getFirstChildElement(attrDecl, "enumeration");
if (e == null) {
attType = fStringPool.addSymbol("NMTOKEN");
} else {
attType = fStringPool.addSymbol("ENUMERATION");
enumeration = fStringPool.startStringList();
for (Element literal = XUtil.getFirstChildElement(e, "literal");
literal != null;
literal = XUtil.getNextSiblingElement(literal, "literal")) {
int stringIndex = fStringPool.addSymbol(literal.getFirstChild().getNodeValue());
fStringPool.addStringToList(enumeration, stringIndex);
}
fStringPool.finishStringList(enumeration);
}
} else if (datatype.equals("NMTOKENS")) {
attType = fStringPool.addSymbol("NMTOKENS");
} else if (datatype.equals(ELT_NOTATIONDECL)) {
attType = fStringPool.addSymbol("NOTATION");
} else { // REVISIT: Danger: assuming all other ATTR types are datatypes
//REVISIT check against list of validators to ensure valid type name
attType = fStringPool.addSymbol("DATATYPE");
enumeration = fStringPool.addSymbol(datatype);
}
}
// attribute default type
int attDefaultType = -1;
int attDefaultValue = -1;
boolean required = attrDecl.getAttribute("minoccurs").equals("1");
if (required) {
attDefaultType = fStringPool.addSymbol("#REQUIRED");
} else {
String fixed = attrDecl.getAttribute(ATT_FIXED);
if (!fixed.equals("")) {
attDefaultType = fStringPool.addSymbol("#FIXED");
attDefaultValue = fStringPool.addString(fixed);
} else {
// attribute default value
String defaultValue = attrDecl.getAttribute(ATT_DEFAULT);
if (!defaultValue.equals("")) {
attDefaultType = fStringPool.addSymbol("");
attDefaultValue = fStringPool.addString(defaultValue);
} else {
attDefaultType = fStringPool.addSymbol("#IMPLIED");
}
}
if (attType == fStringPool.addSymbol("DATATYPE") && attDefaultValue != -1) {
try { // REVISIT - integrate w/ error handling
String type = fStringPool.toString(enumeration);
DatatypeValidator v = fDatatypeRegistry.getValidatorFor(type);
if (v != null)
v.validate(fStringPool.toString(attDefaultValue));
else
reportSchemaError(SchemaMessageProvider.NoValidatorFor,
new Object [] { type });
} catch (InvalidDatatypeValueException idve) {
reportSchemaError(SchemaMessageProvider.IncorrectDefaultType,
new Object [] { attrDecl.getAttribute(ATT_NAME), idve.getMessage() });
} catch (Exception e) {
e.printStackTrace();
System.out.println("Internal error in attribute datatype validation");
}
}
}
// add attribute to element decl pool
fElementDeclPool.addAttDef(elementIndex, attName, attType, enumeration, attDefaultType, attDefaultValue, true, true, true);
}
private int traverseAttrGroup(Element attrGroupDecl) throws Exception {
String attrGroupName = attrGroupDecl.getAttribute(ATT_NAME);
if (attrGroupName.equals("")) { // gensym a unique name
attrGroupName = "http:
}
Element child = XUtil.getFirstChildElement(attrGroupDecl);
int groupIndices[] = new int [((org.apache.xerces.dom.NodeImpl)attrGroupDecl).getLength()];
int numGroups = 0;
for (;
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getNodeName();
if (childName.equals(ELT_ATTRGROUPREF)) {
groupIndices[numGroups++] = traverseAttrGroupRef(child);
if (getContentSpec(getElement(groupIndices[numGroups-1])) == -1) {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Forward reference to AttrGroup" });
}
} else if (childName.equals(ELT_ATTRIBUTEDECL)) {
continue;
} else {
reportSchemaError(SchemaMessageProvider.IllegalAttContent,
new Object [] { childName });
}
}
// stick in ElementDeclPool as a hack
int attrGroupNameIndex = fStringPool.addSymbol(attrGroupName); //REVISIT namespace clashes possible
int attrGroupIndex = fElementDeclPool.addElementDecl(attrGroupNameIndex, 0, 0, false);
// System.out.println("elementIndex:"+groupIndex+" "+groupName+" eltType:"+groupNameIndex+" SpecType:"+contentSpecType+
// " SpecNodeIndex:"+ left);
// (attribute | attrGroupRef)*
for (child = XUtil.getFirstChildElement(attrGroupDecl); // start from the beginning to just do attrs
child != null;
child = XUtil.getNextSiblingElement(child)) {
String childName = child.getNodeName();
if (childName.equals(ELT_ATTRIBUTEDECL)) {
traverseAttributeDecl(child, attrGroupIndex);
} else if (childName.equals(ELT_ATTRGROUPDECL)) {
int index = traverseAttrGroupRef(child);
if (getContentSpec(getElement(index)) == -1) {
reportSchemaError(SchemaMessageProvider.FeatureUnsupported,
new Object [] { "Forward reference to AttrGroup" });
Vector v = null;
Integer i = new Integer(index);
if ((v = (Vector) fForwardRefs.get(i)) == null)
v = new Vector();
v.addElement(new Integer(attrGroupNameIndex));
fForwardRefs.put(i,v);
addUse(attrGroupNameIndex, index);
} else
groupIndices[numGroups++] = getContentSpec(getElement(index));
}
}
// copy up attribute decls from nested groups
for (int i = 0; i < numGroups; i++) {
fElementDeclPool.copyAtts(groupIndices[i], attrGroupNameIndex);
}
return attrGroupNameIndex;
}
private int traverseAttrGroupRef(Element attrGroupRef) {
String name = attrGroupRef.getAttribute(ATT_NAME);
int index = fStringPool.addSymbol(name);
return index;
}
private void addUse(int def, int use) {
addUse(def, new Integer(use));
}
private void addUse(int def, Integer use) {
Vector v = (Vector) fAttrGroupUses.get(new Integer(def));
if (v == null) v = new Vector();
v.addElement(use);
}
/** builds the all content model */
private int buildAllModel(int children[], int count) throws Exception {
// build all model
if (count > 1) {
// create and initialize singletons
XMLContentSpecNode choice = new XMLContentSpecNode();
choice.type = XMLContentSpecNode.CONTENTSPECNODE_CHOICE;
choice.value = -1;
choice.otherValue = -1;
// build all model
sort(children, 0, count);
int index = buildAllModel(children, 0, choice);
return index;
}
if (count > 0) {
return children[0];
}
return -1;
}
/** Builds the all model. */
private int buildAllModel(int src[], int offset,
XMLContentSpecNode choice) throws Exception {
// swap last two places
if (src.length - offset == 2) {
int seqIndex = createSeq(src);
if (choice.value == -1) {
choice.value = seqIndex;
}
else {
if (choice.otherValue != -1) {
choice.value = fElementDeclPool.addContentSpecNode(choice.type, choice.value, choice.otherValue, false);
}
choice.otherValue = seqIndex;
}
swap(src, offset, offset + 1);
seqIndex = createSeq(src);
if (choice.value == -1) {
choice.value = seqIndex;
}
else {
if (choice.otherValue != -1) {
choice.value = fElementDeclPool.addContentSpecNode(choice.type, choice.value, choice.otherValue, false);
}
choice.otherValue = seqIndex;
}
return fElementDeclPool.addContentSpecNode(choice.type, choice.value, choice.otherValue, false);
}
// recurse
for (int i = offset; i < src.length - 1; i++) {
choice.value = buildAllModel(src, offset + 1, choice);
choice.otherValue = -1;
sort(src, offset, src.length - offset);
shift(src, offset, i + 1);
}
int choiceIndex = buildAllModel(src, offset + 1, choice);
sort(src, offset, src.length - offset);
return choiceIndex;
} // buildAllModel(int[],int,ContentSpecNode,ContentSpecNode):int
/** Creates a sequence. */
private int createSeq(int src[]) throws Exception {
int left = src[0];
int right = src[1];
for (int i = 2; i < src.length; i++) {
left = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
left, right, false);
right = src[i];
}
return fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
left, right, false);
} // createSeq(int[]):int
/** Shifts a value into position. */
private void shift(int src[], int pos, int offset) {
int temp = src[offset];
for (int i = offset; i > pos; i
src[i] = src[i - 1];
}
src[pos] = temp;
} // shift(int[],int,int)
/** Simple sort. */
private void sort(int src[], final int offset, final int length) {
for (int i = offset; i < offset + length - 1; i++) {
int lowest = i;
for (int j = i + 1; j < offset + length; j++) {
if (src[j] < src[lowest]) {
lowest = j;
}
}
if (lowest != i) {
int temp = src[i];
src[i] = src[lowest];
src[lowest] = temp;
}
}
} // sort(int[],int,int)
/** Swaps two values. */
private void swap(int src[], int i, int j) {
int temp = src[i];
src[i] = src[j];
src[j] = temp;
} // swap(int[],int,int)
/** Builds the children content model. */
/* private int buildChildrenModel(Element model, int type) throws Exception {
// is there anything to do?
if (model == null) {
return -1;
}
// fill parent node
int parentValue = -1;
int parentOtherValue = -1;
// build content model bottom-up
int index = -1;
for (Element child = XUtil.getFirstChildElement(model);
child != null;
child = XUtil.getNextSiblingElement(child)) {
//
// leaf
//
String childName = child.getNodeName();
if (childName.equals("elementTypeRef")) {
// add element name to symbol table
String elementType = child.getAttribute(ATT_NAME);
int elementTypeIndex = fStringPool.addSymbol(elementType);
// create leaf node
index = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF,
elementTypeIndex, -1, false);
// set occurrence count
index = expandContentModel(index, child);
}
//
// all
//
else if (childName.equals(ATTVAL_ALL)) {
index = buildAllModel(child);
}
//
// choice or sequence
//
else {
int childType = childName.equals(ATTVAL_CHOICE)
? XMLContentSpecNode.CONTENTSPECNODE_CHOICE
: XMLContentSpecNode.CONTENTSPECNODE_SEQ;
index = buildChildrenModel(child, childType);
}
// add to parent node
if (parentValue == -1) {
parentValue = index;
}
else if (parentOtherValue == -1) {
parentOtherValue = index;
}
else {
parentValue = fElementDeclPool.addContentSpecNode(type, parentValue, parentOtherValue, false);
parentOtherValue = index;
}
} // for all children
// set model type
index = fElementDeclPool.addContentSpecNode(type, parentValue, parentOtherValue, false);
// set occurrence count
index = expandContentModel(index, model);
// return last content spec node
return index;
} // buildChildrenModel(Element,int):int
*/
private int expandContentModel(int contentSpecNodeIndex, Element element) throws Exception {
// set occurrence count
int occurs = getOccurrenceCount(element);
int m = 1, n = 1;
if (!isSimpleOccurrenceCount(occurs)) {
try { m = Integer.parseInt(element.getAttribute(ATT_MINOCCURS)); }
catch (NumberFormatException e) {
reportSchemaError(SchemaMessageProvider.ValueNotInteger,
new Object [] { ATT_MINOCCURS });
}
try { n = Integer.parseInt(element.getAttribute(ATT_MAXOCCURS)); }
catch (NumberFormatException e) {
reportSchemaError(SchemaMessageProvider.ValueNotInteger,
new Object [] { ATT_MAXOCCURS });
}
}
switch (occurs) {
case XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE: {
//System.out.println("occurs = +");
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE,
contentSpecNodeIndex, -1, false);
break;
}
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE: {
//System.out.println("occurs = *");
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE,
contentSpecNodeIndex, -1, false);
break;
}
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE: {
//System.out.println("occurs = ?");
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE,
contentSpecNodeIndex, -1, false);
break;
}
case CONTENTSPECNODE_M_OR_MORE: {
//System.out.println("occurs = "+m+" -> *");
// create sequence node
int value = contentSpecNodeIndex;
int otherValue = -1;
// add required number
for (int i = 1; i < m; i++) {
if (otherValue != -1) {
value = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
}
otherValue = contentSpecNodeIndex;
}
// create optional content model node
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE,
contentSpecNodeIndex, -1, false);
// add optional part
if (otherValue != -1) {
value = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
}
otherValue = contentSpecNodeIndex;
// set expanded content model index
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
break;
}
// M -> N
case CONTENTSPECNODE_M_TO_N: {
//System.out.println("occurs = "+m+" -> "+n);
// create sequence node
int value = contentSpecNodeIndex;
int otherValue = -1;
// add required number
for (int i = 1; i < m; i++) {
if (otherValue != -1) {
value = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
}
otherValue = contentSpecNodeIndex;
}
// create optional content model node
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE,
contentSpecNodeIndex, -1, false);
// add optional number
for (int i = n; i > m; i
if (otherValue != -1) {
value = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
}
otherValue = contentSpecNodeIndex;
}
// set expanded content model index
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
break;
}
// 0 -> N
case CONTENTSPECNODE_ZERO_TO_N: {
//System.out.println("occurs = 0 -> "+n);
// create optional content model node
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE,
contentSpecNodeIndex, -1, false);
int value = contentSpecNodeIndex;
int otherValue = -1;
// add optional number
for (int i = 1; i < n; i++) {
if (otherValue != -1) {
value = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
}
otherValue = contentSpecNodeIndex;
}
// set expanded content model index
contentSpecNodeIndex = fElementDeclPool.addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_SEQ,
value, otherValue, false);
break;
}
} // switch
//System.out.println("content = "+getContentSpecNodeAsString(contentSpecNodeIndex));
return contentSpecNodeIndex;
} // expandContentModel(int,int,int,int):int
private boolean isSimpleOccurrenceCount(int occurs) {
return occurs == -1 ||
occurs == XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE ||
occurs == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE ||
occurs == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE;
}
private int getOccurrenceCount(Element element) {
String minOccur = element.getAttribute(ATT_MINOCCURS);
String maxOccur = element.getAttribute(ATT_MAXOCCURS);
if (minOccur.equals("0")) {
if (maxOccur.equals("1") || maxOccur.length() == 0) {
return XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE;
}
else if (maxOccur.equals("*")) {
return XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE;
}
else {
return CONTENTSPECNODE_ZERO_TO_N;
}
}
else if (minOccur.equals("1") || minOccur.length() == 0) {
if (maxOccur.equals("*")) {
return XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE;
}
else if (!maxOccur.equals("1") && maxOccur.length() > 0) {
return CONTENTSPECNODE_M_TO_N;
}
}
else {
if (maxOccur.equals("*")) {
return CONTENTSPECNODE_M_OR_MORE;
}
else {
return CONTENTSPECNODE_M_TO_N;
}
}
// exactly one
return -1;
}
private void reportSchemaError(int major, Object args[]) throws Exception {
// try {
fErrorReporter.reportError(fErrorReporter.getLocator(),
SchemaMessageProvider.SCHEMA_DOMAIN,
major,
SchemaMessageProvider.MSG_NONE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
// } catch (Exception e) {
// e.printStackTrace();
}
// Classes
static class Resolver implements EntityResolver {
private static final String SYSTEM[] = {
"http:
"http:
};
private static final String PATH[] = {
"structures.dtd",
"datatypes.dtd",
};
public InputSource resolveEntity(String publicId, String systemId)
throws IOException {
// looking for the schema DTDs?
for (int i = 0; i < SYSTEM.length; i++) {
if (systemId.equals(SYSTEM[i])) {
InputSource source = new InputSource(getClass().getResourceAsStream(PATH[i]));
source.setPublicId(publicId);
source.setSystemId(systemId);
return source;
}
}
// use default resolution
return null;
} // resolveEntity(String,String):InputSource
} // class Resolver
static class ErrorHandler implements org.xml.sax.ErrorHandler {
/** Warning. */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Error. */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** Fatal error. */
public void fatalError(SAXParseException ex) throws SAXException {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
throw ex;
}
// Private methods
/** Returns a string of the location. */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId_ = ex.getSystemId();
if (systemId_ != null) {
int index = systemId_.lastIndexOf('/');
if (index != -1)
systemId_ = systemId_.substring(index + 1);
str.append(systemId_);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
} // getLocationString(SAXParseException):String
}
class DatatypeValidatorRegistry {
Hashtable fRegistry = new Hashtable();
String integerSubtypeTable[][] = {
{ "non-negative-integer", DatatypeValidator.MININCLUSIVE , "0"},
{ "positive-integer", DatatypeValidator.MININCLUSIVE, "1"},
{ "non-positive-integer", DatatypeValidator.MAXINCLUSIVE, "0"},
{ "negative-integer", DatatypeValidator.MAXINCLUSIVE, "-1"}
};
void initializeRegistry() {
Hashtable facets = null;
fRegistry.put("boolean", new BooleanValidator());
DatatypeValidator integerValidator = new IntegerValidator();
fRegistry.put("integer", integerValidator);
fRegistry.put("string", new StringValidator());
fRegistry.put("decimal", new DecimalValidator());
fRegistry.put("float", new FloatValidator());
fRegistry.put("double", new DoubleValidator());
//REVISIT - enable the below
//fRegistry.put("binary", new BinaryValidator());
//fRegistry.put("date", new DateValidator());
//fRegistry.put("timePeriod", new TimePeriodValidator());
//fRegistry.put("time", new TimeValidator());
//fRegistry.put("uri", new URIValidator());
DatatypeValidator v = null;
for (int i = 0; i < integerSubtypeTable.length; i++) {
v = new IntegerValidator();
facets = new Hashtable();
facets.put(integerSubtypeTable[i][1],integerSubtypeTable[i][2]);
v.setBasetype(integerValidator);
try {
v.setFacets(facets);
} catch (IllegalFacetException ife) {
System.out.println("Internal error initializing registry - Illegal facet: "+integerSubtypeTable[i][0]);
} catch (IllegalFacetValueException ifve) {
System.out.println("Internal error initializing registry - Illegal facet value: "+integerSubtypeTable[i][0]);
} catch (UnknownFacetException ufe) {
System.out.println("Internal error initializing registry - Unknown facet: "+integerSubtypeTable[i][0]);
}
fRegistry.put(integerSubtypeTable[i][0], v);
}
}
DatatypeValidator getValidatorFor(String type) {
return (DatatypeValidator) fRegistry.get(type);
}
void addValidator(String name, DatatypeValidator v) {
fRegistry.put(name,v);
}
}
} |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check that all tables have data.
*/
public class EmptyTables extends SingleDatabaseTestCase {
/**
* Creates a new instance of EmptyTablesTestCase
*/
public EmptyTables() {
addToGroup("post_genebuild");
addToGroup("release");
setDescription("Checks that all tables have data");
}
/**
* Define what tables are to be checked.
*/
private String[] getTablesToCheck(final DatabaseRegistryEntry dbre) {
String[] tables = getTableNames(dbre.getConnection());
Species species = dbre.getSpecies();
DatabaseType type = dbre.getType();
if (type == DatabaseType.CORE || type == DatabaseType.VEGA) {
// the following tables are allowed to be empty
String[] allowedEmpty = { "alt_allele", "assembly_exception", "dnac", "density_feature", "density_type" };
tables = remove(tables, allowedEmpty);
// ID mapping related tables are checked in a separate test case
String[] idMapping = { "gene_archive", "peptide_archive", "mapping_session", "stable_id_event" };
tables = remove(tables, idMapping);
// only rat has entries in QTL tables
if (species != Species.RATTUS_NORVEGICUS) {
String[] qtlTables = { "qtl", "qtl_feature", "qtl_synonym" };
tables = remove(tables, qtlTables);
}
// seq_region_attrib only filled in for human and mouse
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS) {
tables = remove(tables, "seq_region_attrib");
}
// map, marker etc
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS
&& species != Species.DANIO_RERIO) {
String[] markerTables = { "map", "marker", "marker_map_location", "marker_synonym", "marker_feature" };
tables = remove(tables, markerTables);
}
// misc_feature etc
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.ANOPHELES_GAMBIAE) {
String[] miscTables = { "misc_feature", "misc_feature_misc_set", "misc_set", "misc_attrib" };
tables = remove(tables, miscTables);
}
// for imported gene sets, supporting_feature is empty
if (species == Species.TETRAODON_NIGROVIRIDIS || species == Species.SACCHAROMYCES_CEREVISIAE || species == Species.CAENORHABDITIS_ELEGANS) {
tables = remove(tables, "supporting_feature");
}
// only look for Affy features in human, mouse, rat, chicken, danio
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS
&& species != Species.GALLUS_GALLUS && species != Species.DANIO_RERIO) {
tables = remove(tables, "oligo_array");
tables = remove(tables, "oligo_feature");
tables = remove(tables, "oligo_probe");
}
// only look for transcript & translation attribs in human, mouse, rat
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS) {
tables = remove(tables, "transcript_attrib");
tables = remove(tables, "translation_attrib");
}
// drosophila is imported, so no supporting features.
if (species == Species.DROSOPHILA_MELANOGASTER) {
tables = remove(tables, "supporting_feature");
}
// most species don't have regulatory features yet
if (species != Species.HOMO_SAPIENS) {
tables = remove(tables, "regulatory_feature");
tables = remove(tables, "regulatory_factor");
tables = remove(tables, "regulatory_factor_coding");
tables = remove(tables, "regulatory_feature_object");
tables = remove(tables, "regulatory_search_region");
}
// only human and mouse currently have ditag data
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS) {
tables = remove(tables, "ditag");
tables = remove(tables, "ditag_feature");
}
} else if (type == DatabaseType.EST || type == DatabaseType.OTHERFEATURES) {
// Only a few tables need to be filled in EST
String[] est = { "dna_align_feature", "meta_coord", "meta", "coord_system" };
tables = est;
} else if (type == DatabaseType.ESTGENE) {
// Only a few tables need to be filled in ESTGENE
String[] estGene = { "gene", "transcript", "exon", "meta_coord", "coord_system", "gene_stable_id", "exon_stable_id",
"translation_stable_id", "transcript_stable_id", "karyotype" };
tables = estGene;
} else if (type == DatabaseType.CDNA) {
// Only a few tables need to be filled in cDNA databases
String[] cdna = { "assembly", "attrib_type", "dna_align_feature", "meta", "meta_coord", "seq_region", "seq_region_attrib" };
tables = cdna;
}
// many tables are allowed to be empty in vega databases
if (type == DatabaseType.VEGA) {
String[] allowedEmpty = { "affy_array", "affy_feature", "affy_probe", "analysis_description", "dna", "external_synonym", "go_xref",
"identity_xref", "karyotype", "map", "marker", "marker_feature", "marker_map_location", "marker_synonym", "misc_attrib",
"misc_feature", "misc_feature_misc_set", "misc_set", "prediction_exon", "prediction_transcript", "regulatory_factor",
"regulatory_factor_coding", "regulatory_feature", "regulatory_feature_object", "repeat_consensus", "repeat_feature",
"simple_feature", "transcript_attrib", "transcript_supporting_feature", "translation_attrib" };
tables = remove(tables, allowedEmpty);
}
return tables;
}
/**
* Check that every table has more than 0 rows.
*
* @param dbre The database to check.
* @return true if the test passed.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
String[] tables = getTablesToCheck(dbre);
Connection con = dbre.getConnection();
// if there is only one coordinate system then there's no assembly
if (getRowCount(con, "SELECT COUNT(*) FROM coord_system") == 1) {
tables = remove(tables, "assembly");
logger.finest(dbre.getName() + " has only one coord_system, assembly table can be empty");
}
for (int i = 0; i < tables.length; i++) {
String table = tables[i];
// logger.finest("Checking that " + table + " has rows");
if (!tableHasRows(con, table)) {
ReportManager.problem(this, con, table + " has zero rows");
result = false;
}
}
if (result) {
ReportManager.correct(this, con, "All required tables have data");
}
return result;
} // run
private String[] remove(final String[] tables, final String table) {
String[] result = new String[tables.length - 1];
int j = 0;
for (int i = 0; i < tables.length; i++) {
if (!tables[i].equalsIgnoreCase(table)) {
if (j < result.length) {
result[j++] = tables[i];
} else {
logger.severe("Cannot remove " + table + " since it's not in the list!");
}
}
}
return result;
}
private String[] remove(final String[] src, final String[] tablesToRemove) {
String[] result = src;
for (int i = 0; i < tablesToRemove.length; i++) {
result = remove(result, tablesToRemove[i]);
}
return result;
}
} // EmptyTablesTestCase |
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Species;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check that all tables have data.
*/
public class EmptyTables extends SingleDatabaseTestCase {
/**
* Creates a new instance of EmptyTablesTestCase
*/
public EmptyTables() {
addToGroup("post_genebuild");
addToGroup("release");
setDescription("Checks that all tables have data");
}
/**
* Define what tables are to be checked.
*/
private String[] getTablesToCheck(final DatabaseRegistryEntry dbre) {
String[] tables = getTableNames(dbre.getConnection());
Species species = dbre.getSpecies();
DatabaseType type = dbre.getType();
if (type == DatabaseType.CORE || type == DatabaseType.VEGA) {
// the following tables are allowed to be empty
String[] allowedEmpty = { "alt_allele", "assembly_exception", "dnac", "density_feature", "density_type" };
tables = remove(tables, allowedEmpty);
// ID mapping related tables are checked in a separate test case
String[] idMapping = { "gene_archive", "peptide_archive", "mapping_session", "stable_id_event" };
tables = remove(tables, idMapping);
// only rat has entries in QTL tables
if (species != Species.RATTUS_NORVEGICUS) {
String[] qtlTables = { "qtl", "qtl_feature", "qtl_synonym" };
tables = remove(tables, qtlTables);
}
// seq_region_attrib only filled in for human and mouse
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS) {
tables = remove(tables, "seq_region_attrib");
}
// map, marker etc
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS
&& species != Species.DANIO_RERIO) {
String[] markerTables = { "map", "marker", "marker_map_location", "marker_synonym", "marker_feature" };
tables = remove(tables, markerTables);
}
// misc_feature etc
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.ANOPHELES_GAMBIAE) {
String[] miscTables = { "misc_feature", "misc_feature_misc_set", "misc_set", "misc_attrib" };
tables = remove(tables, miscTables);
}
// certain species can have empty karyotype table
if (species == Species.CAENORHABDITIS_BRIGGSAE || species == Species.CAENORHABDITIS_ELEGANS || species == Species.DANIO_RERIO
|| species == Species.FUGU_RUBRIPES || species == Species.XENOPUS_TROPICALIS || species == Species.APIS_MELLIFERA
|| species == Species.PAN_TROGLODYTES || species == Species.SACCHAROMYCES_CEREVISIAE || species == Species.CANIS_FAMILIARIS
|| species == Species.BOS_TAURUS || species == Species.CIONA_INTESTINALIS || species == Species.TETRAODON_NIGROVIRIDIS
|| species == Species.GALLUS_GALLUS) {
tables = remove(tables, "karyotype");
}
// for imported gene sets, supporting_feature is empty
if (species == Species.TETRAODON_NIGROVIRIDIS || species == Species.SACCHAROMYCES_CEREVISIAE || species == Species.CAENORHABDITIS_ELEGANS) {
tables = remove(tables, "supporting_feature");
}
// only look for Affy features in human, mouse, rat, chicken, danio
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS
&& species != Species.GALLUS_GALLUS && species != Species.DANIO_RERIO) {
tables = remove(tables, "affy_array");
tables = remove(tables, "affy_feature");
tables = remove(tables, "affy_probe");
}
// only look for transcript & translation attribs in human, mouse, rat
if (species != Species.HOMO_SAPIENS && species != Species.MUS_MUSCULUS && species != Species.RATTUS_NORVEGICUS) {
tables = remove(tables, "transcript_attrib");
tables = remove(tables, "translation_attrib");
}
// drosophila is imported, so no supporting features.
if (species == Species.DROSOPHILA_MELANOGASTER) {
tables = remove(tables, "supporting_feature");
}
// most species don't have regulatory features yet
if (species != Species.HOMO_SAPIENS) {
tables = remove(tables, "regulatory_feature");
tables = remove(tables, "regulatory_factor");
tables = remove(tables, "regulatory_factor_coding");
tables = remove(tables, "regulatory_feature_object");
}
} else if (type == DatabaseType.EST) {
// Only a few tables need to be filled in EST
String[] est = { "dna_align_feature", "meta_coord", "meta", "coord_system" };
tables = est;
} else if (type == DatabaseType.ESTGENE) {
// Only a few tables need to be filled in ESTGENE
String[] estGene = { "gene", "transcript", "exon", "meta_coord", "coord_system", "gene_stable_id", "exon_stable_id",
"translation_stable_id", "transcript_stable_id", "karyotype" };
tables = estGene;
} else if (type == DatabaseType.CDNA) {
// Only a few tables need to be filled in cDNA databases
String[] cdna = { "assembly", "attrib_type", "dna_align_feature", "meta", "meta_coord", "seq_region", "seq_region_attrib" };
tables = cdna;
}
// many tables are allowed to be empty in vega databases
if (type == DatabaseType.VEGA) {
String[] allowedEmpty = { "affy_array", "affy_feature", "affy_probe", "analysis_description", "dna", "external_synonym", "go_xref",
"identity_xref", "karyotype", "map", "marker", "marker_feature", "marker_map_location", "marker_synonym", "misc_attrib",
"misc_feature", "misc_feature_misc_set", "misc_set", "prediction_exon", "prediction_transcript", "regulatory_factor",
"regulatory_factor_coding", "regulatory_feature", "regulatory_feature_object", "repeat_consensus", "repeat_feature",
"simple_feature", "transcript_attrib", "transcript_supporting_feature", "translation_attrib" };
tables = remove(tables, allowedEmpty);
}
return tables;
}
/**
* Check that every table has more than 0 rows.
*
* @param dbre The database to check.
* @return true if the test passed.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
String[] tables = getTablesToCheck(dbre);
Connection con = dbre.getConnection();
// if there is only one coordinate system then there's no assembly
if (getRowCount(con, "SELECT COUNT(*) FROM coord_system") == 1) {
tables = remove(tables, "assembly");
logger.finest(dbre.getName() + " has only one coord_system, assembly table can be empty");
}
for (int i = 0; i < tables.length; i++) {
String table = tables[i];
// logger.finest("Checking that " + table + " has rows");
if (!tableHasRows(con, table)) {
ReportManager.problem(this, con, table + " has zero rows");
result = false;
}
}
if (result) {
ReportManager.correct(this, con, "All required tables have data");
}
return result;
} // run
private String[] remove(final String[] tables, final String table) {
String[] result = new String[tables.length - 1];
int j = 0;
for (int i = 0; i < tables.length; i++) {
if (!tables[i].equalsIgnoreCase(table)) {
if (j < result.length) {
result[j++] = tables[i];
} else {
logger.severe("Cannot remove " + table + " since it's not in the list!");
}
}
}
return result;
}
private String[] remove(final String[] src, final String[] tablesToRemove) {
String[] result = src;
for (int i = 0; i < tablesToRemove.length; i++) {
result = remove(result, tablesToRemove[i]);
}
return result;
}
} // EmptyTablesTestCase |
package org.jitsi.impl.neomedia.codec.video.vp8;
import org.jitsi.impl.neomedia.codec.*;
import org.jitsi.service.neomedia.codec.*;
import org.jitsi.util.*;
import javax.media.*;
import javax.media.format.*;
import java.util.*;
import java.util.concurrent.*;
public class DePacketizer
extends AbstractCodec2
{
/**
* The <tt>Logger</tt> used by the <tt>DePacketizer</tt> class and its
* instances for logging output.
*/
private static final Logger logger = Logger.getLogger(DePacketizer.class);
/**
* Whether trace logging is enabled.
*/
private static final boolean TRACE = logger.isTraceEnabled();
/**
* A <tt>Comparator</tt> implementation for RTP sequence numbers.
* Compares <tt>a</tt> and <tt>b</tt>, taking into account the wrap at 2^16.
*
* IMPORTANT: This is a valid <tt>Comparator</tt> implementation only if
* used for subsets of [0, 2^16) which don't span more than 2^15 elements.
*
* E.g. it works for: [0, 2^15-1] and ([50000, 2^16) u [0, 10000])
* Doesn't work for: [0, 2^15] and ([0, 2^15-1] u {2^16-1}) and [0, 2^16)
*/
private static final Comparator<? super Long> seqNumComparator
= new Comparator<Long>() {
@Override
public int compare(Long a, Long b)
{
if (a.equals(b))
return 0;
else if (a > b)
{
if (a - b < 32768)
return 1;
else
return -1;
}
else //a < b
{
if (b - a < 32768)
return -1;
else
return 1;
}
}
};
/**
* Stores the RTP payloads (VP8 payload descriptor stripped) from RTP packets
* belonging to a single VP8 compressed frame.
*/
private SortedMap<Long, Container> data
= new TreeMap<Long, Container>(seqNumComparator);
/**
* Stores unused <tt>Container</tt>'s.
*/
private Queue<Container> free = new ArrayBlockingQueue<Container>(100);
/**
* Stores the first (earliest) sequence number stored in <tt>data</tt>, or
* -1 if <tt>data</tt> is empty.
*/
private long firstSeq = -1;
/**
* Stores the last (latest) sequence number stored in <tt>data</tt>, or -1
* if <tt>data</tt> is empty.
*/
private long lastSeq = -1;
/**
* Stores the value of the <tt>PictureID</tt> field for the VP8 compressed
* frame, parts of which are currently stored in <tt>data</tt>, or -1 if
* the <tt>PictureID</tt> field is not in use or <tt>data</tt> is empty.
*/
private int pictureId = -1;
/**
* Stores the RTP timestamp of the packets stored in <tt>data</tt>, or -1
* if they don't have a timestamp set.
*/
private long timestamp = -1;
/**
* Whether we have stored any packets in <tt>data</tt>. Equivalent to
* <tt>data.isEmpty()</tt>.
*/
private boolean empty = true;
/**
* Whether we have stored in <tt>data</tt> the last RTP packet of the VP8
* compressed frame, parts of which are currently stored in <tt>data</tt>.
*/
private boolean haveEnd = false;
/**
* Whether we have stored in <tt>data</tt> the first RTP packet of the VP8
* compressed frame, parts of which are currently stored in <tt>data</tt>.
*/
private boolean haveStart = false;
/**
* Stores the sum of the lengths of the data stored in <tt>data</tt>, that
* is the total length of the VP8 compressed frame to be constructed.
*/
private int frameLength = 0;
/**
* The sequence number of the last RTP packet, which was included in the
* output.
*/
private long lastSentSeq = -1;
/**
* Initializes a new <tt>JNIEncoder</tt> instance.
*/
public DePacketizer()
{
super("VP8 RTP DePacketizer",
VideoFormat.class,
new VideoFormat[]{ new VideoFormat(Constants.VP8) });
inputFormats = new VideoFormat[] { new VideoFormat(Constants.VP8_RTP) };
}
/**
* {@inheritDoc}
*/
@Override
protected void doClose()
{
}
/**
* {@inheritDoc}
*/
@Override
protected void doOpen() throws ResourceUnavailableException
{
if(logger.isInfoEnabled())
logger.info("Opened VP8 depacketizer");
}
/**
* Re-initializes the fields which store information about the currently
* held data. Empties <tt>data</tt>.
*/
private void reinit()
{
firstSeq = lastSeq = timestamp = -1;
pictureId = -1;
empty = true;
haveEnd = haveStart = false;
frameLength = 0;
Iterator<Map.Entry<Long,Container>> it = data.entrySet().iterator();
Map.Entry<Long, Container> e;
while (it.hasNext())
{
e = it.next();
free.offer(e.getValue());
it.remove();
}
}
/**
* Checks whether the currently held VP8 compressed frame is complete (e.g
* all its packets are stored in <tt>data</tt>).
* @return <tt>true</tt> if the currently help VP8 compressed frame is
* complete, <tt>false</tt> otherwise.
*/
private boolean frameComplete()
{
return haveStart && haveEnd && !haveMissing();
}
/**
* Checks whether there are packets with sequence numbers between
* <tt>firstSeq</tt> and <tt>lastSeq</tt> which are *not* stored in
* <tt>data</tt>.
* @return <tt>true</tt> if there are packets with sequence numbers between
* <tt>firstSeq</tt> and <tt>lastSeq</tt> which are *not* stored in
* <tt>data</tt>.
*/
private boolean haveMissing()
{
Set<Long> seqs = data.keySet();
long s = firstSeq;
while (s != lastSeq)
{
if (!seqs.contains(s))
return true;
s = (s+1) % (1<<16);
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
protected int doProcess(Buffer inBuffer, Buffer outBuffer)
{
byte[] inData = (byte[])inBuffer.getData();
int inOffset = inBuffer.getOffset();
if (!VP8PayloadDescriptor.isValid(inData, inOffset))
{
logger.warn("Invalid RTP/VP8 packet discarded.");
outBuffer.setDiscard(true);
return BUFFER_PROCESSED_FAILED; //XXX: FAILED or OK?
}
long inSeq = inBuffer.getSequenceNumber();
long inRtpTimestamp = inBuffer.getRtpTimeStamp();
int inPictureId = VP8PayloadDescriptor.getPictureId(inData, inOffset);
boolean inMarker = (inBuffer.getFlags() & Buffer.FLAG_RTP_MARKER) != 0;
boolean inIsStartOfFrame
= VP8PayloadDescriptor.isStartOfFrame(inData, inOffset);
int inLength = inBuffer.getLength();
int inPdSize = VP8PayloadDescriptor.getSize(inData, inOffset);
int inPayloadLength = inLength - inPdSize;
if (empty
&& lastSentSeq != -1
&& seqNumComparator.compare(inSeq, lastSentSeq) != 1)
{
if (logger.isInfoEnabled())
logger.info("Discarding old packet (while empty) " + inSeq);
outBuffer.setDiscard(true);
return BUFFER_PROCESSED_OK;
}
if (!empty)
{
// if the incoming packet has a different PictureID or timestamp
// than those of the current frame, then it belongs to a different
// frame.
if ( (inPictureId != -1 && pictureId != -1
&& inPictureId != pictureId)
| (timestamp != -1 && inRtpTimestamp != -1
&& inRtpTimestamp != timestamp) )
{
if (seqNumComparator
.compare(inSeq, firstSeq) != 1) //inSeq <= firstSeq
{
// the packet belongs to a previous frame. discard it
if (logger.isInfoEnabled())
logger.info("Discarding old packet " + inSeq);
outBuffer.setDiscard(true);
return BUFFER_PROCESSED_OK;
}
else //inSeq > firstSeq (and also presumably isSeq > lastSeq)
{
// the packet belongs to a subsequent frame (to the one
// currently being held). Drop the current frame.
if (logger.isInfoEnabled())
logger.info("Discarding saved packets on arrival of" +
" a packet for a subsequent frame: " + inSeq);
// TODO: this would be the place to complain about the
// not-well-received PictureID by sending a RTCP SLI or NACK.
reinit();
}
}
}
// a whole frame in a single packet. avoid the extra copy to
// this.data and output it immediately.
if (empty && inMarker && inIsStartOfFrame)
{
byte[] outData
= validateByteArraySize(outBuffer, inPayloadLength, false);
System.arraycopy(
inData,
inOffset + inPdSize,
outData,
0,
inPayloadLength);
outBuffer.setOffset(0);
outBuffer.setLength(inPayloadLength);
outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp());
if (TRACE)
logger.trace("Out PictureID=" + inPictureId);
lastSentSeq = inSeq;
return BUFFER_PROCESSED_OK;
}
// add to this.data
Container container = free.poll();
if (container == null)
container = new Container();
if (container.buf == null || container.buf.length < inPayloadLength)
container.buf = new byte[inPayloadLength];
if (data.get(inSeq) != null)
{
if (logger.isInfoEnabled())
logger.info("(Probable) duplicate packet detected, discarding "
+ inSeq);
outBuffer.setDiscard(true);
return BUFFER_PROCESSED_OK;
}
System.arraycopy(
inData,
inOffset + inPdSize,
container.buf,
0,
inPayloadLength);
container.len = inPayloadLength;
data.put(inSeq, container);
// update fields
frameLength += inPayloadLength;
if (firstSeq == -1
|| (seqNumComparator.compare(firstSeq, inSeq) == 1))
firstSeq = inSeq;
if (lastSeq == -1
|| (seqNumComparator.compare(inSeq, lastSeq) == 1))
lastSeq = inSeq;
if (empty)
{
// the first received packet for the current frame was just added
empty = false;
timestamp = inRtpTimestamp;
pictureId = inPictureId;
}
if (inMarker)
haveEnd = true;
if (inIsStartOfFrame)
haveStart = true;
// check if we have a full frame
if (frameComplete())
{
byte[] outData
= validateByteArraySize(outBuffer, frameLength, false);
int ptr = 0;
Container b;
for (Map.Entry<Long, Container> entry : data.entrySet())
{
b = entry.getValue();
System.arraycopy(
b.buf,
0,
outData,
ptr,
b.len);
ptr += b.len;
}
outBuffer.setOffset(0);
outBuffer.setLength(frameLength);
outBuffer.setRtpTimeStamp(inBuffer.getRtpTimeStamp());
if (TRACE)
logger.trace("Out PictureID=" + inPictureId);
lastSentSeq = lastSeq;
// prepare for the next frame
reinit();
return BUFFER_PROCESSED_OK;
}
else
{
// frame not complete yet
outBuffer.setDiscard(true);
return OUTPUT_BUFFER_NOT_FILLED;
}
}
static class VP8PayloadDescriptor
{
/**
* I bit from the X byte of the Payload Descriptor.
*/
private static final byte I_BIT = (byte) 0x80;
/**
* K bit from the X byte of the Payload Descriptor.
*/
private static final byte K_BIT = (byte) 0x10;
/**
* L bit from the X byte of the Payload Descriptor.
*/
private static final byte L_BIT = (byte) 0x40;
/**
* I bit from the I byte of the Payload Descriptor.
*/
private static final byte M_BIT = (byte) 0x80;
/**
* Maximum length of a VP8 Payload Descriptor.
*/
public static final int MAX_LENGTH = 6;
/**
* S bit from the first byte of the Payload Descriptor.
*/
private static final byte S_BIT = (byte) 0x10;
/**
* T bit from the X byte of the Payload Descriptor.
*/
private static final byte T_BIT = (byte) 0x20;
/**
* X bit from the first byte of the Payload Descriptor.
*/
private static final byte X_BIT = (byte) 0x80;
/**
* Returns a simple Payload Descriptor, with PartID = 0, the 'start
* of partition' bit set according to <tt>startOfPartition</tt>, and
* all other bits set to 0.
* @param startOfPartition whether to 'start of partition' bit should be
* set
* @return a simple Payload Descriptor, with PartID = 0, the 'start
* of partition' bit set according to <tt>startOfPartition</tt>, and
* all other bits set to 0.
*/
public static byte[] create(boolean startOfPartition)
{
byte[] pd = new byte[1];
pd[0] = startOfPartition ? (byte) 0x10 : 0;
return pd;
}
/**
* The size in bytes of the Payload Descriptor at offset
* <tt>offset</tt> in <tt>input</tt>. The size is between 1 and 6.
*
* @param input input
* @param offset offset
* @return The size in bytes of the Payload Descriptor at offset
* <tt>offset</tt> in <tt>input</tt>, or -1 if the input is not a valid
* VP8 Payload Descriptor. The size is between 1 and 6.
*/
public static int getSize(byte[] input, int offset)
{
if (!isValid(input, offset))
return -1;
if ((input[offset] & X_BIT) == 0)
return 1;
int size = 2;
if ((input[offset+1] & I_BIT) != 0)
{
size++;
if ((input[offset+2] & M_BIT) != 0)
size++;
}
if ((input[offset+1] & L_BIT) != 0)
size++;
if ((input[offset+1] & (T_BIT | K_BIT)) != 0)
size++;
return size;
}
/**
* Gets the value of the PictureID field of a VP8 Payload Descriptor.
* @param input
* @param offset
* @return the value of the PictureID field of a VP8 Payload Descriptor,
* or -1 if the fields is not present.
*/
private static int getPictureId(byte[] input, int offset)
{
if (!isValid(input, offset))
return -1;
if ((input[offset] & X_BIT) == 0
|| (input[offset+1] & I_BIT) == 0)
return -1;
boolean isLong = (input[offset+2] & M_BIT) != 0;
if (isLong)
return (input[offset+2] & 0x7f) << 8
| (input[offset+3] & 0xff);
else
return input[offset+2] & 0x7f;
}
private static boolean isValid(byte[] input, int offset)
{
return true;
}
/**
* Checks whether the '<tt>start of partition</tt>' bit is set in the
* VP8 Payload Descriptor at offset <tt>offset</tt> in <tt>input</tt>.
* @param input input
* @param offset offset
* @return <tt>true</tt> if the '<tt>start of partition</tt>' bit is set,
* <tt>false</tt> otherwise.
*/
public static boolean isStartOfPartition(byte[] input, int offset)
{
return (input[offset] & S_BIT) != 0;
}
/**
* Returns <tt>true</tt> if both the '<tt>start of partition</tt>' bit
* is set and the <tt>PID</tt> fields has value 0 in the VP8 Payload
* Descriptor at offset <tt>offset</tt> in <tt>input</tt>.
* @param input
* @param offset
* @return <tt>true</tt> if both the '<tt>start of partition</tt>' bit
* is set and the <tt>PID</tt> fields has value 0 in the VP8 Payload
* Descriptor at offset <tt>offset</tt> in <tt>input</tt>.
*/
public static boolean isStartOfFrame(byte[] input, int offset)
{
return isStartOfPartition(input, offset)
&& getPartitionId(input, offset) == 0;
}
/**
* Returns the value of the <tt>PID</tt> (partition ID) field of the
* VP8 Payload Descriptor at offset <tt>offset</tt> in <tt>input</tt>.
* @param input
* @param offset
* @return the value of the <tt>PID</tt> (partition ID) field of the
* VP8 Payload Descriptor at offset <tt>offset</tt> in <tt>input</tt>.
*/
public static int getPartitionId(byte[] input, int offset)
{
return input[offset] & 0x07;
}
}
/**
* A simple container for a <tt>byte[]</tt> and an integer.
*/
private class Container
{
/**
* This <tt>Container</tt>'s data.
*/
private byte[] buf;
/**
* Length used.
*/
private int len = 0;
}
} |
package org.opencms.gwt.shared.alias;
import org.opencms.util.CmsUUID;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* A class containing the data for a row of the rewrite alias table.<p>
*/
public class CmsRewriteAliasTableRow implements IsSerializable {
/** The error message for this rewrite alias. */
private String m_error;
/** The id of the alias. */
private CmsUUID m_id;
/** The alias mode. */
private CmsAliasMode m_mode;
/** The regular expression string used for matching. */
private String m_patternString;
/** The replacement string used when the regular expression matches. */
private String m_replacementString;
/**
* Default constructor, used for serialization.<p>
*/
public CmsRewriteAliasTableRow() {
// nothing
}
/**
* Creates a new instance.<p>
*
* @param id the id of the alias
* @param patternString the regular expression used for matching the URI
* @param replacementString the replacement string used when the URI is matched
* @param mode the alias mode for this row
*/
public CmsRewriteAliasTableRow(CmsUUID id, String patternString, String replacementString, CmsAliasMode mode) {
m_id = id;
m_patternString = patternString;
m_replacementString = replacementString;
m_mode = mode;
}
/**
* Gets the error message for this row.<p>
*
* @return the error message for this row
*/
public String getError() {
return m_error;
}
/**
* Gets the id of the alias.<p>
*
* @return the id of the alias
*/
public CmsUUID getId() {
return m_id;
}
/**
* Gets the alias mode for this row.<p>
*
* @return the alias mode for this row
*/
public CmsAliasMode getMode() {
return m_mode;
}
/**
* Gets the regular expression string.<p>
*
* @return the regular expression string
*/
public String getPatternString() {
return m_patternString;
}
/**
* Gets the string used to replace the string matching the regex.<p>
*
* @return the replacement string
*/
public String getReplacementString() {
return m_replacementString;
}
/**
* Sets the error message for this row.<p>
*
* @param error the new error message
*/
public void setError(String error) {
m_error = error;
}
/**
* Sets the id of this row.<p>
*
* @param id the new id
*/
public void setId(CmsUUID id) {
m_id = id;
}
/**
* Sets the mode of this row.<p>
*
* @param mode the new mode
*/
public void setMode(CmsAliasMode mode) {
m_mode = mode;
}
/**
* Sets the pattern of this row.<p>
*
* @param patternString the new pattern
*/
public void setPatternString(String patternString) {
m_patternString = patternString;
}
/**
* Sets the replacement string for this row.<p>
*
* @param replacementString the new replacement string
*/
public void setReplacementString(String replacementString) {
m_replacementString = replacementString;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.