answer
stringlengths
17
10.2M
package fr.univnantes.atal.web.piubella.model; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.datastore.Key; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Model class to store metadata about the dataset JSON blob. * * Contains the key of the JSON dataset blob in the blobstore. */ @PersistenceCapable public class JSONInfo { /** * ID for the datastore. */ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key key; /** * Key of the JSON dataset blob in the blobstore. */ @Persistent private BlobKey blobKey = null; /** * Getter for the JSON dataset blob key in the blobstore. * @return the JSON dataset blob key in the blobstore. */ public BlobKey getBlobKey() { return blobKey; } /** * Setter for the JSON dataset blob key in the blobstore. * * @param blobKey the new blob key to store. */ public void setBlobKey(BlobKey blobKey) { this.blobKey = blobKey; } }
package fr.wseduc.webutils.eventbus; import org.vertx.java.core.AsyncResult; import org.vertx.java.core.Handler; import org.vertx.java.core.buffer.Buffer; import org.vertx.java.core.eventbus.EventBus; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.eventbus.ReplyException; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; public class EventBusWithLogger implements EventBus { private final EventBus eb; private static final Logger logger = LoggerFactory.getLogger(EventBusWithLogger.class); private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm.ss.SSS"); public EventBusWithLogger(EventBus eb) { this.eb = eb; } private static String formatDate(Date date) { return df.format(date); } private void sendLog(String address, String message) { logger.info(formatDate(new Date()) + " send : " + address + " - " + message); } private void publishLog(String address, String message) { logger.info(formatDate(new Date()) + " publish : " + address + " - " + message); } private String sendLogwithResponse(String address, String message) { String logMessageId = UUID.randomUUID().toString(); logger.info(formatDate(new Date()) + " send : " + logMessageId + " - " + address + " - " + message); return logMessageId; } private <T> void responseLog(String logMessageId, T response) { String r; if (response instanceof JsonObject) { r = ((JsonObject) response).encode(); } else if (response instanceof JsonArray) { r = ((JsonArray) response).encode(); } else if (response instanceof Buffer) { r = "Buffer not displayed"; } else { r = response.toString(); } logger.info(formatDate(new Date()) + " response : " + logMessageId + " - " + r); } @Override public void close(Handler<AsyncResult<Void>> doneHandler) { eb.close(doneHandler); } @Override public EventBus send(String address, Object message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public EventBus send(String address, Object message, final Handler<Message> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); if (replyHandler != null) { return eb.send(address, message, new Handler<Message>() { @Override public void handle(Message event) { responseLog(logMessageId, event.body()); replyHandler.handle(event); } }); } else { return eb.send(address, message, null); } } @Override public <T> EventBus sendWithTimeout(String address, Object message, long timeout, final Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus send(String address, JsonObject message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.encode()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, JsonObject message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.encode()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } private <T> Handler<Message<T>> replyHandler( final Handler<Message<T>> replyHandler, final String logMessageId) { if (replyHandler == null) { return null; } return new Handler<Message<T>>() { @Override public void handle(Message<T> event) { responseLog(logMessageId, event.body()); replyHandler.handle(event); } }; } private <T> Handler<AsyncResult<Message<T>>> timoutReplyHandler( final Handler<AsyncResult<Message<T>>> replyHandler, final String logMessageId) { if (replyHandler == null) { return null; } return new Handler<AsyncResult<Message<T>>>() { @Override public void handle(AsyncResult<Message<T>> event) { if (event.succeeded()) { responseLog(logMessageId, event.result().body()); } else { ReplyException ex = (ReplyException)event.cause(); logger.error("MessageId : " + logMessageId); logger.error("Failure type: " + ex.failureType()); logger.error("Failure code: " + ex.failureCode()); logger.error("Failure message: " + ex.getMessage()); } replyHandler.handle(event); } }; } @Override public EventBus send(String address, JsonObject message) { sendLog(address, message.encode()); return eb.send(address, message); } @Override public <T> EventBus send(String address, JsonArray message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.encode()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, JsonArray message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.encode()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, JsonArray message) { sendLog(address, message.encode()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Buffer message, final Handler<Message<T>> replyHandler) { // final String logMessageId = sendLogwithResponse(address, message.toString()); // return eb.send(address, message, replyHandler(replyHandler, logMessageId)); return eb.send(address, message, replyHandler); } @Override public <T> EventBus sendWithTimeout(String address, Buffer message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { return eb.sendWithTimeout(address, message, timeout, replyHandler); } @Override public EventBus send(String address, Buffer message) { //sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, byte[] message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, new String(message)); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, byte[] message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, new String(message)); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, byte[] message) { sendLog(address, new String(message)); return eb.send(address, message); } @Override public <T> EventBus send(String address, String message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, String message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, String message) { sendLog(address, message); return eb.send(address, message); } @Override public <T> EventBus send(String address, Integer message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Integer message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Integer message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Long message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Long message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Long message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Float message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Float message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Float message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Double message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Double message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Double message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Boolean message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Boolean message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Boolean message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Short message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Short message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Short message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Character message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Character message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Character message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public <T> EventBus send(String address, Byte message, final Handler<Message<T>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.send(address, message, replyHandler(replyHandler, logMessageId)); } @Override public <T> EventBus sendWithTimeout(String address, Byte message, long timeout, Handler<AsyncResult<Message<T>>> replyHandler) { final String logMessageId = sendLogwithResponse(address, message.toString()); return eb.sendWithTimeout(address, message, timeout, timoutReplyHandler(replyHandler, logMessageId)); } @Override public EventBus send(String address, Byte message) { sendLog(address, message.toString()); return eb.send(address, message); } @Override public EventBus publish(String address, Object message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, JsonObject message) { publishLog(address, message.encode()); return eb.publish(address, message); } @Override public EventBus publish(String address, JsonArray message) { publishLog(address, message.encode()); return eb.publish(address, message); } @Override public EventBus publish(String address, Buffer message) { //publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, byte[] message) { publishLog(address, new String(message)); return eb.publish(address, message); } @Override public EventBus publish(String address, String message) { publishLog(address, message); return eb.publish(address, message); } @Override public EventBus publish(String address, Integer message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, Long message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, Float message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, Double message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, Boolean message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, Short message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, Character message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus publish(String address, Byte message) { publishLog(address, message.toString()); return eb.publish(address, message); } @Override public EventBus unregisterHandler(String address, Handler<? extends Message> handler, Handler<AsyncResult<Void>> resultHandler) { return eb.unregisterHandler(address, handler, resultHandler); } @Override public EventBus unregisterHandler(String address, Handler<? extends Message> handler) { return eb.unregisterHandler(address, handler); } @Override public EventBus registerHandler(String address, Handler<? extends Message> handler, Handler<AsyncResult<Void>> resultHandler) { return eb.registerHandler(address, handler, resultHandler); } @Override public EventBus registerHandler(String address, Handler<? extends Message> handler) { return eb.registerHandler(address, handler); } @Override public EventBus registerLocalHandler(String address, Handler<? extends Message> handler) { return eb.registerLocalHandler(address, handler); } @Override public EventBus setDefaultReplyTimeout(long timeoutMs) { return eb.setDefaultReplyTimeout(timeoutMs); } @Override public long getDefaultReplyTimeout() { return eb.getDefaultReplyTimeout(); } }
package hudson.plugins.blazemeter; import com.cloudbees.plugins.credentials.CredentialsProvider; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.Item; import hudson.model.Job; import hudson.model.Result; import hudson.plugins.blazemeter.api.AggregateTestResult; import hudson.plugins.blazemeter.api.BlazemeterApi; import hudson.plugins.blazemeter.api.TestInfo; import hudson.security.ACL; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Notifier; import hudson.tasks.Publisher; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.json.JSONException; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import javax.mail.MessagingException; import javax.servlet.ServletException; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; 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.regex.Matcher; import java.util.regex.Pattern; public class PerformancePublisher extends Notifier { DateFormat df = new SimpleDateFormat("dd/MM/yy"); private String apiKey; private String testId = ""; private String testDuration = "180"; private String mainJMX = ""; private String dataFolder = ""; private int errorFailedThreshold = 0; private int errorUnstableThreshold = 0; private int responseTimeFailedThreshold = 0; private int responseTimeUnstableThreshold = 0; /** * @deprecated as of 1.3. for compatibility */ private transient String filename; /** * Configured report parsers. */ private List<PerformanceReportParser> parsers = null; @DataBoundConstructor public PerformancePublisher(String apiKey, String testDuration, String mainJMX, String dataFolder, String testId, int errorFailedThreshold, int errorUnstableThreshold, int responseTimeFailedThreshold, int responseTimeUnstableThreshold) { this.apiKey = apiKey; this.errorFailedThreshold = errorFailedThreshold; this.errorUnstableThreshold = errorUnstableThreshold; this.testId = testId; this.testDuration = testDuration; this.mainJMX = mainJMX; this.dataFolder = dataFolder; this.responseTimeFailedThreshold = responseTimeFailedThreshold; this.responseTimeUnstableThreshold = responseTimeUnstableThreshold; } public static File getPerformanceReport(AbstractBuild<?, ?> build, String parserDisplayName, String performanceReportName) { return new File(build.getRootDir(), PerformanceReportMap.getPerformanceReportFileRelativePath( parserDisplayName, getPerformanceReportBuildFileName(performanceReportName))); } List<PerformanceProjectAction> performanceProjectActions = new ArrayList<PerformanceProjectAction>(); private String blazeMeterURL; public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.BUILD; } public List<PerformanceReportParser> getParsers() { return parsers; } /** * <p> * Delete the date suffix appended to the Performance result files by the * Maven Performance plugin * </p> * * @param performanceReportWorkspaceName self explanatory. * @return the name of the PerformanceReport in the Build */ public static String getPerformanceReportBuildFileName( String performanceReportWorkspaceName) { String result = performanceReportWorkspaceName; if (performanceReportWorkspaceName != null) { Pattern p = Pattern.compile("-[0-9]*\\.xml"); Matcher matcher = p.matcher(performanceReportWorkspaceName); if (matcher.find()) { result = matcher.replaceAll(".xml"); } } return result; } /** * look for blazemeter reports based in the configured parameter includes. * 'includes' is - an Ant-style pattern - a list of files and folders * separated by the characters ;:, */ protected static List<FilePath> locatePerformanceReports(FilePath workspace, String includes) throws IOException, InterruptedException { // First use ant-style pattern try { FilePath[] ret = workspace.list(includes); if (ret.length > 0) { return Arrays.asList(ret); } } catch (IOException e) { // Do nothing. } // If it fails, do a legacy search ArrayList<FilePath> files = new ArrayList<FilePath>(); String parts[] = includes.split("\\s*[;:,]+\\s*"); for (String path : parts) { FilePath src = workspace.child(path); if (src.exists()) { if (src.isDirectory()) { files.addAll(Arrays.asList(src.list("**/*"))); } else { files.add(src); } } } return files; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { PrintStream logger = listener.getLogger(); Result result; // Result.SUCCESS; String session; int runDurationSeconds = Integer.parseInt(testDuration) * 60; if ((result = validateThresholds(logger)) != Result.SUCCESS){ // input parameters error. build.setResult(Result.ABORTED); return true; } String apiKeyId = StringUtils.defaultIfEmpty(getApiKey(), getDescriptor().getApiKey()); String apiKey = null; for (BlazemeterCredential c : CredentialsProvider .lookupCredentials(BlazemeterCredential.class, build.getProject(), ACL.SYSTEM)) { if (StringUtils.equals(apiKeyId, c.getId())) { apiKey = c.getApiKey().getPlainText(); break; } } // ideally, at this point we'd look up the credential based on the API key to find the secret // but there are no secrets, so no need to! BlazemeterApi bmAPI = new BlazemeterApi(); uploadDataFolderFiles(apiKey, testId, bmAPI, logger); org.json.JSONObject json; int countStartRequests = 0; do { logger.print("."); json = bmAPI.startTest(apiKey, testId); countStartRequests++; if (json == null && countStartRequests > 5) { logger.println("Could not start BlazeMeter Test"); build.setResult(Result.NOT_BUILT); return false; } } while (json == null); try { if (!json.get("response_code").equals(200)) { if (json.get("response_code").equals(500) && json.get("error").toString().startsWith("Test already running")) { // bmAPI.stopTest(apiKey, testId); logger.println("Test already running, please stop it first"); build.setResult(Result.NOT_BUILT); return false; } //Try again. logger.print("."); json = bmAPI.startTest(apiKey, testId); if (json == null) { logger.println("Could not start BlazeMeter Test"); build.setResult(Result.NOT_BUILT); return false; } if (!json.get("response_code").equals(200)) { logger.println("Could not start BlazeMeter Test -" + json.get("error").toString()); build.setResult(Result.NOT_BUILT); return false; } } session = json.get("session_id").toString(); } catch (JSONException e) { e.printStackTrace(); logger.println("Error: Exception while starting BlazeMeter Test [" + e.getMessage() + "]"); return false; } // add the report to the build object. PerformanceBuildAction a = new PerformanceBuildAction(build, logger, parsers); a.setSession(session); a.setBlazeMeterURL(DESCRIPTOR.blazeMeterURL); build.addAction(a); Date start = null; long lastPrint = 0; while (true) { TestInfo info = bmAPI.getTestRunStatus(apiKey, testId); //if drupal works hard //Thread.sleep(1000); if (info.getStatus().equals(BlazemeterApi.TestStatus.Error)) { build.setResult(Result.NOT_BUILT); logger.println("Error while running a test - please try to run the same test on BlazeMeter"); return true; } if (info.getStatus().equals(BlazemeterApi.TestStatus.NotFound)) { build.setResult(Result.NOT_BUILT); logger.println("Test not found error"); return true; } if (info.getStatus().equals(BlazemeterApi.TestStatus.Running)) { if (start == null) start = Calendar.getInstance().getTime(); build.setResult(Result.SUCCESS); long now = Calendar.getInstance().getTime().getTime(); long diffInSec = (now - start.getTime()) / 1000; if (now - lastPrint > 10000) { //print every 10 sec. logger.println("BlazeMeter test running from " + start + " - for " + diffInSec + " seconds"); lastPrint = now; } if (diffInSec >= runDurationSeconds) { bmAPI.stopTest(apiKey, testId); logger.println("BlazeMeter test stopped due to user test duration setup reached"); break; } continue; } if (info.getStatus().equals(BlazemeterApi.TestStatus.NotRunning)) break; } logger.println("BlazeMeter test running terminated at " + Calendar.getInstance().getTime()); //TODO: loop probe with special response code. or loop for certain time on 404 error code. Thread.sleep(10 * 1000); // Wait for the report to generate. //get testGetArchive information json = bmAPI.aggregateReport(apiKey, session); for (int i = 0; i < 200; i++) { try { if (json.get("response_code").equals(404)) json = bmAPI.aggregateReport(apiKey, session); else break; } catch (JSONException e) { } finally { Thread.sleep(5 * 1000); } } String aggregate = "null"; for (int i = 0; i < 30; i++) { try { if (!json.get("response_code").equals(200)) { logger.println("Error: Requesting aggregate report response code:" + json.get("response_code")); } else if (json.has("error") && !json.getString("error").equals("null")){ logger.println("Error: Requesting aggregate report. Error received :" + json.getString("error")); } else { aggregate = json.getJSONObject("report").get("aggregate").toString(); } } catch (JSONException e) { logger.println("Error: Exception while parsing aggregate report [" + e.getMessage() + "]"); } if (!aggregate.equals("null")) break; Thread.sleep(2 * 1000); json = bmAPI.aggregateReport(apiKey, session); } if (aggregate == null || aggregate.equals("null")) { logger.println("Error: Requesting aggregate is not available"); build.setResult(Result.NOT_BUILT); return false; } AggregateTestResult aggregateTestResult = AggregateTestResult.generate(aggregate); if (aggregateTestResult == null) { logger.println("Error: Requesting aggregate Test Result is not available"); build.setResult(Result.NOT_BUILT); return false; } if (performanceProjectActions.size() > 0) { performanceProjectActions.get(performanceProjectActions.size() - 1).lastReportSession = session; performanceProjectActions.get(performanceProjectActions.size() - 1).lastBlazeMeterURL = DESCRIPTOR.blazeMeterURL; } double thresholdTolerance = 0.00005; //null hypothesis double errorPercent = aggregateTestResult.getErrorPercentage(); double AverageResponseTime = aggregateTestResult.getAverage(); if (errorFailedThreshold >= 0 && errorPercent - errorFailedThreshold > thresholdTolerance) { result = Result.FAILURE; logger.println("Test ended with " + Result.FAILURE + " on error percentage threshold"); } else if (errorUnstableThreshold >= 0 && errorPercent - errorUnstableThreshold > thresholdTolerance) { logger.println("Test ended with " + Result.UNSTABLE + " on error percentage threshold"); result = Result.UNSTABLE; } if (responseTimeFailedThreshold >= 0 && AverageResponseTime - responseTimeFailedThreshold > thresholdTolerance) { result = Result.FAILURE; build.setResult(Result.FAILURE); logger.println("Test ended with " + Result.FAILURE + " on response time threshold"); } else if (responseTimeUnstableThreshold >= 0 && AverageResponseTime - responseTimeUnstableThreshold > thresholdTolerance) { result = Result.UNSTABLE; logger.println("Test ended with " + Result.UNSTABLE + " on response time threshold"); } build.setResult(result); return true; } private void uploadDataFolderFiles(String apiKey, String testId, BlazemeterApi bmAPI, PrintStream logger) { if (dataFolder == null || dataFolder.isEmpty()) return; File folder = new File(dataFolder); if (!folder.exists() || !folder.isDirectory()){ logger.println("dataFolder " + dataFolder + " could not be found on local file system, please check that the folder exists."); return; } File[] listOfFiles = folder.listFiles(); if (listOfFiles != null) { for (File file : listOfFiles) { String fileName; if (file.isFile()) { fileName = file.getName(); if (fileName.endsWith(mainJMX)) bmAPI.uploadJmx(apiKey, testId, file); else uploadFile(apiKey, testId, bmAPI, file, logger); } } } } private void uploadFile(String apiKey, String testId, BlazemeterApi bmAPI, File file, PrintStream logger) { String fileName = file.getName(); org.json.JSONObject json = bmAPI.uploadBinaryFile(apiKey, testId, file); try { if (!json.get("response_code").equals(200)) { logger.println("Could not upload file " + fileName + " " + json.get("error").toString()); } } catch (JSONException e) { logger.println("Could not upload file " + fileName + " " + e.getMessage()); e.printStackTrace(); } } private Result validateThresholds(PrintStream logger) { Result result = Result.SUCCESS; if(testDuration.equals("0")){ logger.println("BlazeMeter: Test duration should be more than ZERO, build is considered as " +Result.NOT_BUILT.toString().toLowerCase()); return Result.ABORTED; } if (errorUnstableThreshold >= 0 && errorUnstableThreshold <= 100) { logger.println("BlazeMeter: Errors percentage greater or equal than " + errorUnstableThreshold + " % will be considered as " + Result.UNSTABLE.toString().toLowerCase()); } else { logger.println("BlazeMeter: ErrorUnstableThreshold percentage should be between 0 to 100"); return Result.ABORTED; } if (errorFailedThreshold >= 0 && errorFailedThreshold <= 100) { logger.println("BlazeMeter: ErrorFailedThreshold percentage greater or equal than " + errorFailedThreshold + " % will be considered as " + Result.FAILURE.toString().toLowerCase()); } else { logger.println("BlazeMeter: ErrorFailedThreshold percentage should be between 0 to 100"); return Result.ABORTED; } if (responseTimeUnstableThreshold > 0) { logger.println("BlazeMeter: ResponseTimeUnstable greater or equal than " + responseTimeUnstableThreshold + " millis will be considered as " + Result.UNSTABLE.toString().toLowerCase()); } else { logger.println("BlazeMeter: ResponseTimeUnstable should be greater than 0"); return Result.ABORTED; } if (responseTimeFailedThreshold > 0) { logger.println("BlazeMeter: ResponseTimeFailed greater than " + responseTimeFailedThreshold + " millis will be considered as " + Result.FAILURE.toString().toLowerCase()); } else { logger.println("BlazeMeter: ResponseTimeFailed should be greater than 0"); return Result.ABORTED; } return result; } private List<File> copyReportsToMaster(AbstractBuild<?, ?> build, PrintStream logger, List<FilePath> files, String parserDisplayName) throws IOException, InterruptedException { List<File> localReports = new ArrayList<File>(); for (FilePath src : files) { final File localReport = getPerformanceReport(build, parserDisplayName, src.getName()); if (src.isDirectory()) { logger.println("Performance: File '" + src.getName() + "' is a directory, not a Performance Report"); continue; } src.copyTo(new FilePath(localReport)); localReports.add(localReport); } return localReports; } public Object readResolve() { return this; } public String getApiKey() { return apiKey; } public int getResponseTimeFailedThreshold() { return responseTimeFailedThreshold; } public void setResponseTimeFailedThreshold(int responseTimeFailedThreshold) { this.responseTimeFailedThreshold = responseTimeFailedThreshold; } public int getResponseTimeUnstableThreshold() { return responseTimeUnstableThreshold; } public void setResponseTimeUnstableThreshold(int responseTimeUnstableThreshold) { this.responseTimeUnstableThreshold = responseTimeUnstableThreshold; } public String getTestDuration() { return testDuration; } public void setTestDuration(String testDuration) { this.testDuration = testDuration; } public String getMainJMX() { return mainJMX; } public void setMainJMX(String mainJMX) { this.mainJMX = mainJMX; } public String getDataFolder() { return dataFolder; } public void setDataFolder(String dataFolder) { this.dataFolder = dataFolder; } public int getErrorFailedThreshold() { return errorFailedThreshold; } public void setErrorFailedThreshold(int errorFailedThreshold) { this.errorFailedThreshold = Math.max(0, Math.min(errorFailedThreshold, 100)); } public int getErrorUnstableThreshold() { return errorUnstableThreshold; } public void setErrorUnstableThreshold(int errorUnstableThreshold) { this.errorUnstableThreshold = Math.max(0, Math.min(errorUnstableThreshold, 100)); } public String getTestId() { return testId; } public void setTestId(String testId) { this.testId = testId; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } @Override public BlazeMeterPerformancePublisherDescriptor getDescriptor() { return DESCRIPTOR; } @Extension public static final BlazeMeterPerformancePublisherDescriptor DESCRIPTOR = new BlazeMeterPerformancePublisherDescriptor(); // The descriptor has been moved but we need to maintain the old descriptor for backwards compatibility reasons. @SuppressWarnings({"UnusedDeclaration"}) public static final class DescriptorImpl extends BlazeMeterPerformancePublisherDescriptor { } public static class BlazeMeterPerformancePublisherDescriptor extends BuildStepDescriptor<Publisher> { private String blazeMeterURL = "https://a.blazemeter.com"; private String name = "My BlazeMeter Account"; private String apiKey; public BlazeMeterPerformancePublisherDescriptor() { super(PerformancePublisher.class); load(); } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } @Override public String getDisplayName() { return "BlazeMeter"; } // Used by config.jelly to display the test list. public ListBoxModel doFillTestIdItems(@QueryParameter String apiKey) throws FormValidation { if (StringUtils.isBlank(apiKey)) { apiKey = getApiKey(); } Secret apiSecret = null; Item item = Stapler.getCurrentRequest().findAncestorObject(Item.class); for (BlazemeterCredential c : CredentialsProvider .lookupCredentials(BlazemeterCredential.class, item, ACL.SYSTEM)) { if (StringUtils.equals(apiKey, c.getId())) { apiSecret = c.getApiKey(); break; } } ListBoxModel items = new ListBoxModel(); if (apiSecret == null) { items.add("No API Key", "-1"); } else { BlazemeterApi bzm = new BlazemeterApi(); try { HashMap<String, String> testList = bzm.getTestList(apiSecret.getPlainText()); if (testList == null){ items.add("Invalid API key ", "-1"); } else if (testList.isEmpty()){ items.add("No tests", "-1"); } else { Set set = testList.entrySet(); for (Object test : set) { Map.Entry me = (Map.Entry) test; items.add((String) me.getKey(), String.valueOf(me.getValue())); } } } catch (Exception e) { throw FormValidation.error(e.getMessage(), e); } } return items; } public ListBoxModel doFillApiKeyItems() { ListBoxModel items = new ListBoxModel(); Set<String> apiKeys = new HashSet<String>(); Item item = Stapler.getCurrentRequest().findAncestorObject(Item.class); if (item instanceof Job) { List<BlazemeterCredential> global = CredentialsProvider .lookupCredentials(BlazemeterCredential.class, Jenkins.getInstance(), ACL.SYSTEM); if (!global.isEmpty() && !StringUtils.isEmpty(getApiKey())) { items.add("Default API Key", ""); } } for (BlazemeterCredential c : CredentialsProvider .lookupCredentials(BlazemeterCredential.class, item, ACL.SYSTEM)) { String id = c.getId(); if (!apiKeys.contains(id)) { items.add(StringUtils.defaultIfEmpty(c.getDescription(), id), id); apiKeys.add(id); } } return items; } public List<BlazemeterCredential> getCredentials(Object scope) { List<BlazemeterCredential> result = new ArrayList<BlazemeterCredential>(); Set<String> apiKeys = new HashSet<String>(); Item item = scope instanceof Item ? (Item) scope : null; for (BlazemeterCredential c : CredentialsProvider .lookupCredentials(BlazemeterCredential.class, item, ACL.SYSTEM)) { String id = c.getId(); if (!apiKeys.contains(id)) { result.add(c); apiKeys.add(id); } } return result; } // Used by global.jelly to authenticate User key public FormValidation doTestConnection(@QueryParameter("apiKey") final String userKey) throws MessagingException, IOException, JSONException, ServletException { BlazemeterApi bzm = new BlazemeterApi(); int testCount = bzm.getTestCount(userKey); if (testCount < 0) { return FormValidation.errorWithMarkup("An error as occurred, check proxy settings"); } else if (testCount == 0) { return FormValidation.errorWithMarkup("User Key Invalid Or No Available Tests"); } else { return FormValidation.ok("User Key Valid. " + testCount + " Available Tests"); } } public FormValidation doCheckTestDuration(@QueryParameter String value) throws IOException, ServletException { if(value.equals("0")) { return FormValidation.warning("TestDuration should be more than ZERO"); } return FormValidation.ok(); } /* public FormValidation doCheckResponseTimeUnstableThreshold(@QueryParameter String value) throws IOException, ServletException { if(value.equals("0")) { return FormValidation.warning("Value should be more than ZERO"); } return FormValidation.ok(); }*/ @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { apiKey = formData.optString("apiKey"); save(); return true; } public String getBlazeMeterURL() { return blazeMeterURL; } public void setBlazeMeterURL(String blazeMeterURL) { this.blazeMeterURL = blazeMeterURL; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getApiKey() { List<BlazemeterCredential> credentials = CredentialsProvider .lookupCredentials(BlazemeterCredential.class, Jenkins.getInstance(), ACL.SYSTEM); if (StringUtils.isBlank(apiKey) && !credentials.isEmpty()) { return credentials.get(0).getId(); } if (credentials.size() == 1) { return credentials.get(0).getId(); } for (BlazemeterCredential c: credentials) { if (StringUtils.equals(c.getId(), apiKey)) { return apiKey; } } // API key is not valid any more return ""; } public void setApiKey(String apiKey) { this.apiKey = apiKey; } } }
package com.nerodesk.takes; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.jcabi.http.Request; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.response.RestResponse; import com.jcabi.http.response.XmlResponse; import com.jcabi.http.wire.VerboseWire; import com.nerodesk.om.Base; import com.nerodesk.om.mock.MkBase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.util.Locale; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHeaders; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; import org.takes.http.FtRemote; @SuppressWarnings("PMD.TooManyMethods") public final class TkAppTest { /** * Fake URN. */ private static final String FAKE_URN = "urn:test:1"; /** * File query param. */ private static final String FILE = "file"; /** * Launches web server on random port. * @throws Exception If fails */ @Test public void launchesOnRandomPort() throws Exception { final TkApp app = new TkApp(new MkBase()); new FtRemote(app).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .assertXPath("/xhtml:html"); new JdkRequest(home) .through(VerboseWire.class) .header("Accept", "application/xml") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .assertXPath("/page/version"); } } ); } /** * TsApp can launch web server in non-latin locale. * @throws Exception If fails */ @Test public void launchesWebServerInNonLatinLocale() throws Exception { final Locale def = Locale.getDefault(); try { Locale.setDefault(Locale.CHINESE); final TkApp app = new TkApp(new MkBase()); new FtRemote(app).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .assertXPath("/xhtml:html"); } } ); } finally { Locale.setDefault(def); } } /** * Application can return file content. * @throws Exception If fails */ @Test public void returnsFileContent() throws Exception { final Base base = new MkBase(); final String name = "test.txt"; base.user(TkAppTest.FAKE_URN).docs().doc(name).write( new ByteArrayInputStream("hello, world!".getBytes()) ); final TkApp app = new TkApp(base); new FtRemote(app).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .uri().path("/doc/read") .queryParam(TkAppTest.FILE, name).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.startsWith("hello, world")); } } ); } /** * TsApp can read file with special characters in its name. * @throws Exception If fails */ @Test @Ignore public void readsFileWithSpecialCharactersInName() throws Exception { final Base base = new MkBase(); final String name = "[][].txt"; final String data = "fake data"; base.user(TkAppTest.FAKE_URN).docs().doc(name).write( new ByteArrayInputStream(data.getBytes()) ); new FtRemote(new TkApp(base)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .uri().path("/doc/read") .queryParam(TkAppTest.FILE, name).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.startsWith(data)); } } ); } /** * TsApp can delete file with special characters in its name. * @throws Exception If fails */ @Test @Ignore public void deletesFileWithSpecialCharactersInName() throws Exception { final Base base = new MkBase(); final String name = "[][].txt"; final String data = "fake data"; base.user(TkAppTest.FAKE_URN).docs().doc(name).write( new ByteArrayInputStream(data.getBytes()) ); MatcherAssert.assertThat( base.user(TkAppTest.FAKE_URN).docs().names(), Matchers.not(Matchers.emptyIterable()) ); new FtRemote(new TkApp(base)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .uri().path("/doc/delete") .queryParam(TkAppTest.FILE, name).back() .fetch().as(RestResponse.class).follow() .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } } ); MatcherAssert.assertThat( base.user(TkAppTest.FAKE_URN).docs().names(), Matchers.emptyIterable() ); } /** * Application can return file content in binary form. * @throws Exception If something goes wrong */ @Test public void returnsBinaryContent() throws Exception { final Base base = new MkBase(); final String name = "test.dat"; final byte[] content = new byte[]{0x00, 0x0a, (byte) 0xff, (byte) 0xfe}; base.user(TkAppTest.FAKE_URN).docs().doc(name).write( new ByteArrayInputStream(content) ); new FtRemote(new TkApp(base)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { MatcherAssert.assertThat( new JdkRequest(home) .uri().path("/doc/read") .queryParam(TkAppTest.FILE, name).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .binary(), Matchers.is(content) ); } } ); } /** * Application can return static image. * @throws Exception If something goes wrong */ @Test public void returnsStaticImage() throws Exception { final String name = "/images/logo.png"; new FtRemote(new TkApp(new MkBase())).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { MatcherAssert.assertThat( new JdkRequest(home) .uri().path(name) .back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertHeader("Content-Type", "image/png") .binary(), Matchers.is( IOUtils.toByteArray( TkAppTest.class.getResource(name) ) ) ); } } ); } /** * Application can upload file content. * @throws Exception If fails */ @Test public void uploadsFileContent() throws Exception { final Base base = new MkBase(); final String name = "small.txt"; final String file = "uploaded by client"; new FtRemote(new TkApp(base)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { TkAppTest.write(home) .fetch( new ByteArrayInputStream( TkAppTest.multipart(name, file).getBytes() ) ) .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_SEE_OTHER); } } ); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); base.user(TkAppTest.FAKE_URN).docs().doc(name).read(stream); MatcherAssert.assertThat( IOUtils.toString(stream.toByteArray(), Charsets.UTF_8.name()), Matchers.containsString(file) ); } @Test @Ignore public void uploadsBigFile() throws Exception { final int psize = 5; final Base base = new MkBase(); final String name = "large.txt"; final String file = "123451234512345"; new FtRemote(new TkApp(base)).exec( // @checkstyle AnonInnerLengthCheck (30 lines) new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { int pos = 0; while (pos < file.length() - 1) { TkAppTest.write(home) .header( HttpHeaders.CONTENT_RANGE, String.format( "bytes %d-%d/%d", pos, pos + psize, file.length() ) ) .fetch( new ByteArrayInputStream( TkAppTest.multipart(name, file).getBytes() ) ) .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); pos += psize; } } } ); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); base.user(TkAppTest.FAKE_URN).docs().doc(name).read(stream); MatcherAssert.assertThat( IOUtils.toString(stream.toByteArray(), Charsets.UTF_8.name()), Matchers.containsString(file) ); } /** * Application can show error page. * @throws Exception If fails */ @Test public void showsErrorPage() throws Exception { final Base base = new MkBase(); new FtRemote(new TkApp(base)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .uri().path("/page-is-absent").back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.startsWith("oops, something ")); } } ); } /** * Create request to add a file. * @param home URI home * @return Request */ private static Request write(final URI home) { return new JdkRequest(home) .method("POST") .uri().path("/doc/write").back() .header( HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=AaB03x" ); } /** * Multipart request body. * @param name File name * @param content File content * @return Request body */ private static String multipart(final String name, final String content) { return Joiner.on("\r\n").join( " --AaB03x", "Content-Disposition: form-data; name=\"name\"", "", name, "--AaB03x", Joiner.on("; ").join( "Content-Disposition: form-data", "name=\"file\"", String.format("filename=\"%s\"", name) ), "Content-Transfer-Encoding: utf-8", "", content, "--AaB03x ); } }
package demos.components; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXDrawer; import com.jfoenix.controls.JFXDrawer.DrawerDirection; import com.jfoenix.controls.JFXDrawersStack; import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.layout.FlowPane; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import static javafx.scene.input.MouseEvent.MOUSE_PRESSED; public class DrawerDemo extends Application { private static final String LEFT = "LEFT"; private static final String TOP = "TOP"; private static final String RIGHT = "RIGHT"; private static final String BOTTOM = "BOTTOM"; @Override public void start(Stage stage) { FlowPane content = new FlowPane(); JFXButton leftButton = new JFXButton(LEFT); JFXButton topButton = new JFXButton(TOP); JFXButton rightButton = new JFXButton(RIGHT); JFXButton bottomButton = new JFXButton(BOTTOM); content.getChildren().addAll(leftButton, topButton, rightButton, bottomButton); content.setMaxSize(200, 200); JFXDrawer leftDrawer = new JFXDrawer(); StackPane leftDrawerPane = new StackPane(); leftDrawerPane.getStyleClass().add("red-400"); leftDrawerPane.getChildren().add(new JFXButton("Left Content")); leftDrawer.setSidePane(leftDrawerPane); leftDrawer.setDefaultDrawerSize(150); leftDrawer.setResizeContent(true); leftDrawer.setOverLayVisible(false); leftDrawer.setResizableOnDrag(true); JFXDrawer bottomDrawer = new JFXDrawer(); StackPane bottomDrawerPane = new StackPane(); bottomDrawerPane.getStyleClass().add("deep-purple-400"); bottomDrawerPane.getChildren().add(new JFXButton("Bottom Content")); bottomDrawer.setDefaultDrawerSize(150); bottomDrawer.setDirection(DrawerDirection.BOTTOM); bottomDrawer.setSidePane(bottomDrawerPane); bottomDrawer.setResizeContent(true); bottomDrawer.setOverLayVisible(false); bottomDrawer.setResizableOnDrag(true); JFXDrawer rightDrawer = new JFXDrawer(); StackPane rightDrawerPane = new StackPane(); rightDrawerPane.getStyleClass().add("blue-400"); rightDrawerPane.getChildren().add(new JFXButton("Right Content")); rightDrawer.setDirection(DrawerDirection.RIGHT); rightDrawer.setDefaultDrawerSize(150); rightDrawer.setSidePane(rightDrawerPane); rightDrawer.setOverLayVisible(false); rightDrawer.setResizableOnDrag(true); JFXDrawer topDrawer = new JFXDrawer(); StackPane topDrawerPane = new StackPane(); topDrawerPane.getStyleClass().add("green-400"); topDrawerPane.getChildren().add(new JFXButton("Top Content")); topDrawer.setDirection(DrawerDirection.TOP); topDrawer.setDefaultDrawerSize(150); topDrawer.setSidePane(topDrawerPane); topDrawer.setOverLayVisible(false); topDrawer.setResizableOnDrag(true); JFXDrawersStack drawersStack = new JFXDrawersStack(); drawersStack.setContent(content); leftDrawer.setId(LEFT); rightDrawer.setId(RIGHT); bottomDrawer.setId(BOTTOM); topDrawer.setId(TOP); leftButton.addEventHandler(MOUSE_PRESSED, e -> drawersStack.toggle(leftDrawer)); bottomButton.addEventHandler(MOUSE_PRESSED, e -> drawersStack.toggle(bottomDrawer)); rightButton.addEventHandler(MOUSE_PRESSED, e -> drawersStack.toggle(rightDrawer)); topButton.addEventHandler(MOUSE_PRESSED, e -> drawersStack.toggle(topDrawer)); final Scene scene = new Scene(drawersStack, 800, 800); final ObservableList<String> stylesheets = scene.getStylesheets(); stylesheets.addAll(DrawerDemo.class.getResource("/css/jfoenix-components.css").toExternalForm(), DrawerDemo.class.getResource("/css/jfoenix-design.css").toExternalForm()); stage.setTitle("JFX Drawer Demo"); stage.setScene(scene); stage.setResizable(true); stage.show(); } public static void main(String[] args) { launch(args); } }
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.arguments.ParamValue; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; /** * <p>Zips two lines on a common field.</p> * @see ILineOperation * @author Innovimax * @version 1.0 */ public class DefaultLineZipping extends AbstractLineOperation { private final ZipType type; private final String sep; /** * Constructor * @param type The type of zip to process * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.operation.ZipType * @see innovimax.mixthem.arguments.RuleParam * @see innovimax.mixthem.arguments.ParamValue */ public DefaultLineZipping(final ZipType type, final Map<RuleParam, ParamValue> params) { super(params); this.type = type; this.sep = params.getOrDefault(RuleParam.ZIP_SEP, ZipOperation.DEFAULT_ZIP_SEPARATOR.getValue()).asString(); } @Override public void process(final String line1, final String line2, final LineResult result) throws MixException { result.reset(); switch (this.type) { case LINE: result.setResult((line1 != null ? line1 : "") + this.sep + (line2 != null ? line2 : "")); break; case CELL: final Iterator<String> iterator1 = line1 != null ? Arrays.asList(line1.split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.getValue().asString())).iterator() : Collections.emptyIterator(); final Iterator<String> iterator2 = line2 != null ? Arrays.asList(line2.split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.getValue().asString())).iterator() : Collections.emptyIterator(); final StringBuffer buf = new StringBuffer(); while (iterator1.hasNext() || iterator2.hasNext()) { final String cell1 = iterator1.hasNext() ? iterator1.next() : ""; final String cell2 = iterator2.hasNext() ? iterator2.next() : ""; if (buf.length() > 0) { buf.append(CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString()); } buf.append(cell1 + this.sep + cell2); } result.setResult(buf.toString()); } } @Override public void process(final List<String> lineRange, final LineResult result) throws MixException { //process(lineRange.get(0), lineRange.get(1), result); result.reset(); System.out.println("RANGE="+lineRange.toString()); switch (this.type) { case LINE: if (lineZipable(lineRange)) { StringBuilder zip = new StringBuilder(); int index = 0; for (String line : lineRange) { if (index > 0) { zip.append(this.sep); } zip.append(line); index++; } result.setResult(zip.toString()); } break; case CELL: if (cellZipable(lineRange)) { //TODO } } } private boolean lineZipable(final List<String> lineRange) { for (int i=0; i < lineRange.size(); i++) { if (lineRange.get(i) == null) { return false; } } return true; } private boolean cellZipable(final List<String> lineRange) { return false; } }
package com.opentok.test; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.opentok.Archive; import com.opentok.Archive.OutputMode; import com.opentok.ArchiveLayout; import com.opentok.ArchiveList; import com.opentok.ArchiveMode; import com.opentok.ArchiveProperties; import com.opentok.MediaMode; import com.opentok.OpenTok; import com.opentok.Role; import com.opentok.Session; import com.opentok.SessionProperties; import com.opentok.SignalProperties; import com.opentok.Stream; import com.opentok.StreamList; import com.opentok.TokenOptions; import com.opentok.exception.InvalidArgumentException; import com.opentok.exception.OpenTokException; import com.opentok.exception.RequestException; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class OpenTokTest { private final String SESSION_CREATE = "/session/create"; private int apiKey = 123456; private String archivePath = "/v2/project/" + apiKey + "/archive"; private String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; private String apiUrl = "http://localhost:8080"; private OpenTok sdk; @Rule public WireMockRule wireMockRule = new WireMockRule(8080); @Before public void setUp() throws OpenTokException { // read system properties for integration testing int anApiKey = 0; boolean useMockKey = false; String anApiKeyProp = System.getProperty("apiKey"); String anApiSecret = System.getProperty("apiSecret"); try { anApiKey = Integer.parseInt(anApiKeyProp); } catch (NumberFormatException e) { useMockKey = true; } if (!useMockKey && anApiSecret != null && !anApiSecret.isEmpty()) { // TODO: figure out when to turn mocking off based on this apiKey = anApiKey; apiSecret = anApiSecret; archivePath = "/v2/project/" + apiKey + "/archive"; } sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(apiUrl).build(); } @Test public void testSignalAllConnections() throws OpenTokException { String sessionId = "SESSIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); sdk.signal(sessionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testSignalWithEmptySessionID() throws OpenTokException { String sessionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session string null or empty"); } } @Test public void testSignalWithEmoji() throws OpenTokException { String sessionId = "SESSIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/signal"; Boolean exceptionThrown = false; SignalProperties properties = new SignalProperties.Builder().type("test").data("\uD83D\uDE01").build(); try { sdk.signal(sessionId, properties); } catch (RequestException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } @Test public void testSignalSingleConnection() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; stubFor(post(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204))); SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); sdk.signal(sessionId, connectionId, properties); verify(postRequestedFor(urlMatching(path))); verify(postRequestedFor(urlMatching(path)) .withHeader("Content-Type", equalTo("application/json"))); verify(postRequestedFor(urlMatching(path)) .withRequestBody(equalToJson("{ \"type\":\"test\",\"data\":\"Signal test string\" }"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testSignalWithEmptyConnectionID() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithConnectionIDAndEmptySessionID() throws OpenTokException { String sessionId = ""; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testSignalWithEmptySessionAndConnectionID() throws OpenTokException { String sessionId = ""; String connectionId = ""; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId +"/signal"; SignalProperties properties = new SignalProperties.Builder().type("test").data("Signal test string").build(); try { sdk.signal(sessionId, connectionId, properties); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session or Connection string null or empty"); } } @Test public void testCreateDefaultSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(ArchiveMode.MANUAL, session.getProperties().archiveMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) .withRequestBody(matching(".*p2p.preference=enabled.*")) .withRequestBody(matching(".*archiveMode=manual.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateRoutedSession() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .mediaMode(MediaMode.ROUTED) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.ROUTED, session.getProperties().mediaMode()); assertNull(session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // NOTE: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*p2p.preference=disabled.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateLocationHintSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .location(locationHint) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(MediaMode.RELAYED, session.getProperties().mediaMode()); assertEquals(locationHint, session.getProperties().getLocation()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*location="+locationHint+".*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test public void testCreateAlwaysArchivedSession() throws OpenTokException { String sessionId = "SESSIONID"; String locationHint = "12.34.56.78"; stubFor(post(urlEqualTo(SESSION_CREATE)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); SessionProperties properties = new SessionProperties.Builder() .archiveMode(ArchiveMode.ALWAYS) .build(); Session session = sdk.createSession(properties); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); assertEquals(ArchiveMode.ALWAYS, session.getProperties().archiveMode()); verify(postRequestedFor(urlMatching(SESSION_CREATE)) // TODO: this is a pretty bad way to verify, ideally we can decode the body and then query the object .withRequestBody(matching(".*archiveMode=always.*"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } @Test(expected = InvalidArgumentException.class) public void testCreateBadSession() throws OpenTokException { SessionProperties properties = new SessionProperties.Builder() .location("NOT A VALID IP") .build(); } // This is not part of the API because it would introduce a backwards incompatible change. // @Test(expected = InvalidArgumentException.class) // public void testCreateInvalidAlwaysArchivedAndRelayedSession() throws OpenTokException { // SessionProperties properties = new SessionProperties.Builder() // .mediaMode(MediaMode.RELAYED) // .archiveMode(ArchiveMode.ALWAYS) // .build(); // TODO: test session creation conditions that result in errors @Test public void testTokenDefault() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = opentok.generateToken(sessionId); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals(Integer.toString(apiKey), tokenData.get("partner_id")); assertNotNull(tokenData.get("create_time")); assertNotNull(tokenData.get("nonce")); } @Test public void testTokenLayoutClass() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; String token = sdk.generateToken(sessionId, new TokenOptions.Builder() .initialLayoutClassList(Arrays.asList("full", "focus")) .build()); assertNotNull(token); assertTrue(Helpers.verifyTokenSignature(token, apiSecret)); Map<String, String> tokenData = Helpers.decodeToken(token); assertEquals("full focus", tokenData.get("initial_layout_class_list")); } @Test public void testTokenRoles() throws OpenTokException, UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; Role role = Role.SUBSCRIBER; String defaultToken = opentok.generateToken(sessionId); String roleToken = sdk.generateToken(sessionId, new TokenOptions.Builder() .role(role) .build()); assertNotNull(defaultToken); assertNotNull(roleToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(roleToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals("publisher", defaultTokenData.get("role")); Map<String, String> roleTokenData = Helpers.decodeToken(roleToken); assertEquals(role.toString(), roleTokenData.get("role")); } @Test public void testTokenExpireTime() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); long now = System.currentTimeMillis() / 1000L; long inOneHour = now + (60 * 60); long inOneDay = now + (60 * 60 * 24); long inThirtyDays = now + (60 * 60 * 24 * 30); ArrayList<Exception> exceptions = new ArrayList<Exception>(); String defaultToken = opentok.generateToken(sessionId); String oneHourToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inOneHour) .build()); try { String earlyExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(now - 10) .build()); } catch (Exception exception) { exceptions.add(exception); } try { String lateExpireTimeToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .expireTime(inThirtyDays + (60 * 60 * 24) /* 31 days */) .build()); } catch (Exception exception) { exceptions.add(exception); } assertNotNull(defaultToken); assertNotNull(oneHourToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(oneHourToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertEquals(Long.toString(inOneDay), defaultTokenData.get("expire_time")); Map<String, String> oneHourTokenData = Helpers.decodeToken(oneHourToken); assertEquals(Long.toString(inOneHour), oneHourTokenData.get("expire_time")); assertEquals(2, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } @Test public void testTokenConnectionData() throws OpenTokException, SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; String sessionId = "1_MX4xMjM0NTZ-flNhdCBNYXIgMTUgMTQ6NDI6MjMgUERUIDIwMTR-MC40OTAxMzAyNX4"; OpenTok opentok = new OpenTok(apiKey, apiSecret); // purposely contains some exotic characters String actualData = "{\"name\":\"%foo ç &\"}"; Exception tooLongException = null; String defaultToken = opentok.generateToken(sessionId); String dataBearingToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(actualData) .build()); try { String dataTooLongToken = opentok.generateToken(sessionId, new TokenOptions.Builder() .data(StringUtils.repeat("x", 1001)) .build()); } catch (InvalidArgumentException e) { tooLongException = e; } assertNotNull(defaultToken); assertNotNull(dataBearingToken); assertTrue(Helpers.verifyTokenSignature(defaultToken, apiSecret)); assertTrue(Helpers.verifyTokenSignature(dataBearingToken, apiSecret)); Map<String, String> defaultTokenData = Helpers.decodeToken(defaultToken); assertNull(defaultTokenData.get("connection_data")); Map<String, String> dataBearingTokenData = Helpers.decodeToken(dataBearingToken); assertEquals(actualData, dataBearingTokenData.get("connection_data")); assertEquals(InvalidArgumentException.class, tooLongException.getClass()); } @Test public void testTokenBadSessionId() throws OpenTokException { int apiKey = 123456; String apiSecret = "1234567890abcdef1234567890abcdef1234567890"; OpenTok opentok = new OpenTok(apiKey, apiSecret); ArrayList<Exception> exceptions = new ArrayList<Exception>(); try { String nullSessionToken = opentok.generateToken(null); } catch (Exception e) { exceptions.add(e); } try { String emptySessionToken = opentok.generateToken(""); } catch (Exception e) { exceptions.add(e); } try { String invalidSessionToken = opentok.generateToken("NOT A VALID SESSION ID"); } catch (Exception e) { exceptions.add(e); } assertEquals(3, exceptions.size()); for (Exception e : exceptions) { assertEquals(InvalidArgumentException.class, e.getClass()); } } /* TODO: find a way to match JSON without caring about spacing .withRequestBody(matching("."+".")) in the following archive tests */ @Test public void testGetArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F" + archiveId + "%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Si" + "gnature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(apiKey, archive.getPartnerId()); assertEquals(archiveId, archive.getId()); assertEquals(1395187836000L, archive.getCreatedAt()); assertEquals(62, archive.getDuration()); assertEquals("", archive.getName()); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(8347554, archive.getSize()); assertEquals(Archive.Status.AVAILABLE, archive.getStatus()); assertEquals("http://tokbox.com.archive2.s3.amazonaws.com/123456%2F"+archiveId +"%2Farchive.mp4?Expires=13951" + "94362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", archive.getUrl()); verify(getRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test get archive failure scenarios @Test public void testListArchives() throws OpenTokException { stubFor(get(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionIdOffSetCount() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?offset=1&count=1&sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId, 1, 1); assertNotNull(archives); assertEquals(1, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithSessionId() throws OpenTokException { String sessionId = "SESSIONID"; String url = archivePath + "?sessionId=" + sessionId; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 60,\n" + " \"items\" : [ {\n" + " \"createdAt\" : 1395187930000,\n" + " \"duration\" : 22,\n" + " \"id\" : \"ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2909274,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5" + "a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187910000,\n" + " \"duration\" : 14,\n" + " \"id\" : \"5350f06f-0166-402e-bc27-09ba54948512\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 1952651,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06" + "f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"f6e7ee58-d6cf-4a59-896b-6d56b158ec71\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee5" + "8-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 544,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 78499758,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf" + "1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394396753000,\n" + " \"duration\" : 24,\n" + " \"id\" : \"b8f64de1-e218-4091-9544-4cbf369fc238\",\n" + " \"name\" : \"showtime again\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 2227849,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de" + "1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " }, {\n" + " \"createdAt\" : 1394321113000,\n" + " \"duration\" : 1294,\n" + " \"id\" : \"832641bf-5dbf-41a1-ad94-fea213e59a92\",\n" + " \"name\" : \"showtime\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 42165242,\n" + " \"status\" : \"available\",\n" + " \"url\" : \"http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641b" + "f-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6" + "LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n" + " } ]\n" + " }"))); ArchiveList archives = sdk.listArchives(sessionId); assertNotNull(archives); assertEquals(6, archives.size()); assertEquals(60, archives.getTotalCount()); assertThat(archives.get(0), instanceOf(Archive.class)); assertEquals("ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", archives.get(0).getId()); verify(getRequestedFor(urlEqualTo(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListArchivesWithEmptySessionID() throws OpenTokException { int exceptionCount = 0; int testCount = 2; try { ArchiveList archives = sdk.listArchives(""); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session Id cannot be null or empty"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(null); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Session Id cannot be null or empty"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testListArchivesWithWrongOffsetCountValues() throws OpenTokException { int exceptionCount = 0; int testCount = 4; try { ArchiveList archives = sdk.listArchives(-2,0); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(0,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,12); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } try { ArchiveList archives = sdk.listArchives(-10,1200); } catch (InvalidArgumentException e) { assertEquals(e.getMessage(),"Make sure count parameter value is >= 0 and/or offset parameter value is <=1000"); exceptionCount++; } assertTrue(exceptionCount == testCount); } @Test public void testStartArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().name(null).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartArchiveWithName() throws OpenTokException { String sessionId = "SESSIONID"; String name = "archive_name"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"archive_name\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.startArchive(sessionId, name); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertEquals(name, archive.getName()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartVoiceOnlyArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"hasVideo\" : false,\n" + " \"hasAudio\" : true\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().hasVideo(false).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartComposedArchiveWithLayout() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"composed\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder() .outputMode(OutputMode.COMPOSED) .layout(new ArchiveLayout(ArchiveLayout.Type.CUSTOM, "stream { position: absolute; }")) .build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.COMPOSED, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } @Test public void testStartIndividualArchive() throws OpenTokException { String sessionId = "SESSIONID"; stubFor(post(urlEqualTo(archivePath)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243556,\n" + " \"duration\" : 0,\n" + " \"id\" : \"30b3ebf1-ba36-4f5b-8def-6f70d9986fe9\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"started\",\n" + " \"url\" : null,\n" + " \"outputMode\" : \"individual\"\n" + " }"))); ArchiveProperties properties = new ArchiveProperties.Builder().outputMode(OutputMode.INDIVIDUAL).build(); Archive archive = sdk.startArchive(sessionId, properties); assertNotNull(archive); assertEquals(sessionId, archive.getSessionId()); assertNotNull(archive.getId()); assertEquals(OutputMode.INDIVIDUAL, archive.getOutputMode()); verify(postRequestedFor(urlMatching(archivePath))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath))))); Helpers.verifyUserAgent(); } // TODO: test start archive with name // TODO: test start archive failure scenarios @Test public void testStopArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(post(urlEqualTo(archivePath + "/" + archiveId + "/stop")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395183243000,\n" + " \"duration\" : 0,\n" + " \"id\" : \"ARCHIVEID\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 0,\n" + " \"status\" : \"stopped\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.stopArchive(archiveId); assertNotNull(archive); assertEquals("SESSIONID", archive.getSessionId()); assertEquals(archiveId, archive.getId()); verify(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(archivePath + "/" + archiveId + "/stop"))))); Helpers.verifyUserAgent(); } // TODO: test stop archive failure scenarios @Test public void testDeleteArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(delete(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.deleteArchive(archiveId); verify(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(archivePath + "/" + archiveId))))); Helpers.verifyUserAgent(); } // TODO: test delete archive failure scenarios // NOTE: this test is pretty sloppy @Test public void testGetExpiredArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.EXPIRED, archive.getStatus()); } // NOTE: this test is pretty sloppy @Test public void testGetPausedArchive() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"paused\",\n" + " \"url\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); assertEquals(Archive.Status.PAUSED, archive.getStatus()); } @Test public void testGetArchiveWithUnknownProperties() throws OpenTokException { String archiveId = "ARCHIVEID"; stubFor(get(urlEqualTo(archivePath + "/" + archiveId)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"createdAt\" : 1395187836000,\n" + " \"duration\" : 62,\n" + " \"id\" : \"" + archiveId + "\",\n" + " \"name\" : \"\",\n" + " \"partnerId\" : 123456,\n" + " \"reason\" : \"\",\n" + " \"sessionId\" : \"SESSIONID\",\n" + " \"size\" : 8347554,\n" + " \"status\" : \"expired\",\n" + " \"url\" : null,\n" + " \"thisisnotaproperty\" : null\n" + " }"))); Archive archive = sdk.getArchive(archiveId); assertNotNull(archive); } @Test public void testGetStreamWithId() throws OpenTokException { String sessionID = "SESSIONID"; String streamID = "STREAMID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream/" + streamID; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"id\" : \"" + streamID + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }"))); Stream stream = sdk.getStream(sessionID, streamID); assertNotNull(stream); assertEquals(streamID, stream.getId()); assertEquals("", stream.getName()); assertEquals("camera", stream.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testListStreams() throws OpenTokException { String sessionID = "SESSIONID"; String url = "/v2/project/" + this.apiKey + "/session/" + sessionID + "/stream"; stubFor(get(urlEqualTo(url)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\n" + " \"count\" : 2,\n" + " \"items\" : [ {\n" + " \"id\" : \"" + 1234 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"camera\",\n" + " \"layoutClassList\" : [] \n" + " }, {\n" + " \"id\" : \"" + 5678 + "\",\n" + " \"name\" : \"\",\n" + " \"videoType\" : \"screen\",\n" + " \"layoutClassList\" : [] \n" + " } ]\n" + " }"))); StreamList streams = sdk.listStreams(sessionID); assertNotNull(streams); assertEquals(2,streams.getTotalCount()); Stream stream1 = streams.get(0); Stream stream2 = streams.get(1); assertEquals("1234", stream1.getId()); assertEquals("", stream1.getName()); assertEquals("camera", stream1.getVideoType()); assertEquals("5678", stream2.getId()); assertEquals("", stream2.getName()); assertEquals("screen", stream2.getVideoType()); verify(getRequestedFor(urlMatching(url))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(getRequestedFor(urlMatching(url))))); Helpers.verifyUserAgent(); } @Test public void testforceDisconnect() throws OpenTokException { String sessionId = "SESSIONID"; String connectionId = "CONNECTIONID"; String path = "/v2/project/" + apiKey + "/session/" + sessionId + "/connection/" + connectionId ; stubFor(delete(urlEqualTo(path)) .willReturn(aResponse() .withStatus(204) .withHeader("Content-Type", "application/json"))); sdk.forceDisconnect(sessionId,connectionId); verify(deleteRequestedFor(urlMatching(path))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(deleteRequestedFor(urlMatching(path))))); Helpers.verifyUserAgent(); } @Test public void testCreateSessionWithProxy() throws OpenTokException, UnknownHostException { WireMockConfiguration proxyConfig = WireMockConfiguration.wireMockConfig(); proxyConfig.dynamicPort(); WireMockServer proxyingService = new WireMockServer(proxyConfig); proxyingService.start(); WireMock proxyingServiceAdmin = new WireMock(proxyingService.port()); String targetServiceBaseUrl = "http://localhost:" + wireMockRule.port(); proxyingServiceAdmin.register(any(urlMatching(".*")).atPriority(10) .willReturn(aResponse() .proxiedFrom(targetServiceBaseUrl))); String sessionId = "SESSIONID"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getLocalHost(), proxyingService.port())); sdk = new OpenTok.Builder(apiKey, apiSecret).apiUrl(targetServiceBaseUrl).proxy(proxy).build(); stubFor(post(urlEqualTo("/session/create")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("[{\"session_id\":\"" + sessionId + "\",\"project_id\":\"00000000\"," + "\"partner_id\":\"123456\"," + "\"create_dt\":\"Mon Mar 17 00:41:31 PDT 2014\"," + "\"media_server_url\":\"\"}]"))); Session session = sdk.createSession(); assertNotNull(session); assertEquals(apiKey, session.getApiKey()); assertEquals(sessionId, session.getSessionId()); verify(postRequestedFor(urlMatching(SESSION_CREATE))); assertTrue(Helpers.verifyTokenAuth(apiKey, apiSecret, findAll(postRequestedFor(urlMatching(SESSION_CREATE))))); Helpers.verifyUserAgent(); } }
package io.github.ihongs; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Locale; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; /** * * * <p> * Servlet , * ; * Core , , * , * getInstance . * Core Core.getInstance() * </p> * * <p> * : , . * THREAD_CORE ThreadLocal, * , * ; * GLOBAL_CORE , , * Closeable,Singleton . * </p> * * <h3>:</h3> * <pre> * ENVIR (0 cmd, 1 web) * DEBUG (0 , 1 , 2 , 4 8 ; 3 ) * BASE_HREF (WEBContextPath) * BASE_PATH (WEBRealPath(/)) * CORE_PATH (WEBWEB-INF) * CONF_PATH * DATA_PATH * SERVER_ID ID( Core.getUniqueId() ) * : Servlet/Filter/Cmdlet . * </pre> * * <h3>:</h3> * <pre> * 0x24 * 0x25 * 0x26 * 0x27 * 0x28 * </pre> * * @author Hongs */ public final class Core extends HashMap<String, Object> implements AutoCloseable { /** * * * @param <T> * @param klass [.].class * @return */ public <T> T get(Class<T> klass) { String name = klass.getName( ); Core core = Core.GLOBAL_CORE ; Object inst = check(core, name); return (T) (inst != null ? inst : build(core, name, klass)); } /** * * * @param name [.] * @return */ public Object get(String name) { Core core = Core.GLOBAL_CORE ; Object inst = check(core, name); return inst != null ? inst : build(core, name); } /** * get * * @param name * @return , */ public Object got(String name) { return super.get(name); } /** * get(Object), got(String),get(String|Class) * * @param name * @return , * @throws UnsupportedOperationException * @deprecated */ @Override public Object get(Object name) { throw new UnsupportedOperationException( "May cause an error on 'get(Object)', use 'got(String)' or 'get(String|Class)'"); } /** * clear, close, * * @throws UnsupportedOperationException * @deprecated */ @Override public void clear() { throw new UnsupportedOperationException( "May cause an error on 'clear', use the 'close'"); } @Override public void close() { if (this.isEmpty()) { return; } /** * ConcurrentModificationException, * . */ Object[] a = this.values().toArray(); for (int i = 0; i < a.length; i ++ ) { Object o = a [i]; try { if (o instanceof AutoCloseable ) { ((AutoCloseable) o ).close( ); } } catch ( Throwable x ) { x.printStackTrace ( System.err ); } } super.clear(); } /** * Closeable */ public void cloze() { if (this.isEmpty()) { return; } Iterator i = this.entrySet().iterator(); while ( i.hasNext( ) ) { Entry e = (Entry)i.next(); Object o = e . getValue(); try { if (o instanceof Closeable) { Closeable c = (Closeable) o; if (c.closeable() ) { c.close( ); i.remove(); } } } catch ( Throwable x ) { x.printStackTrace ( System.err ); } } } @Override protected void finalize() throws Throwable { try { this.close( ); } finally { super.finalize(); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for(Map.Entry<String, Object> et : entrySet()) { Object ob = et.getValue(); if (ob instanceof Singleton) { if (ob instanceof Closeable) { sb.append("[Z]"); } else { sb.append("[S]"); } } else if (ob instanceof Closeable) { sb.append("[D]"); } else if (ob instanceof AutoCloseable) { sb.append("[C]"); } sb.append(et.getKey()).append( ", "); } int sl = sb.length(); if (sl > 0 ) { sb.delete(sb.length() - 2 , sb.length()); } return sb.toString(); } private Object check(Core core, String name) { if (super.containsKey(name)) { return super.get(name); } if ( core.containsKey(name)) { return core.get(name); } if ( name == null || name.length() == 0) { throw new HongsError(0x24, "Instance name can not be empty."); } return null; } private Object build(Core core, String name) { Class klass; try { klass = Class.forName( name ); } catch (ClassNotFoundException ex) { throw new HongsError(0x25, "Can not find class by name '" + name + "'."); } return build( core, name, klass ); } private Object build(Core core, String name, Class klass) { try { Method method = klass.getMethod("getInstance", new Class[] {}); try { Object object = method.invoke(null, new Object[] {}); if (object instanceof Singleton) { core.put(name, object); } else { this.put(name, object); } return object; } catch (IllegalAccessException ex) { throw new HongsError(0x27, "Can not build "+name, ex); } catch (IllegalArgumentException ex) { throw new HongsError(0x27, "Can not build "+name, ex); } catch (InvocationTargetException ex) { Throwable ta = ex.getCause(); if (ta instanceof StackOverflowError) { throw ( StackOverflowError ) ta ; } throw new HongsError(0x27, "Can not build "+name, ta); } } catch (NoSuchMethodException ez) { try { Object object = klass.newInstance(); if (object instanceof Singleton) { core.put(name, object); } else { this.put(name, object); } return object; } catch (IllegalAccessException ex) { throw new HongsError(0x28, "Can not build "+name, ex); } catch (InstantiationException ex) { Throwable ta = ex.getCause(); if (ta instanceof StackOverflowError) { throw ( StackOverflowError ) ta ; } throw new HongsError(0x28, "Can not build "+name, ex); } } catch (SecurityException se) { throw new HongsError(0x26, "Can not build "+name, se); } } / /** * (0 Cmd , 1 Web ) */ public static byte ENVIR; /** * (0 , 1 , 2 , 4 Trace, 8 Debug) * : */ public static byte DEBUG; /** * WEB, : , */ public static String BASE_HREF = null; /** * WEB, : , */ public static String BASE_PATH = null; public static String CORE_PATH = null; public static String CONF_PATH; public static String DATA_PATH; public static String SERVER_ID; public static final long STARTS_TIME = System.currentTimeMillis(); public static final Core GLOBAL_CORE = new Core(); public static ThreadLocal<Core> THREAD_CORE = new ThreadLocal() { @Override protected Core initialValue() { return new Core(); } @Override public void remove() { try { ( (Core) get()).close(); } catch (Throwable ex) { throw new Error(ex); } super.remove(); } }; public static InheritableThreadLocal< Long > ACTION_TIME = new InheritableThreadLocal(); public static InheritableThreadLocal<String> ACTION_ZONE = new InheritableThreadLocal(); public static InheritableThreadLocal<String> ACTION_LANG = new InheritableThreadLocal(); public static InheritableThreadLocal<String> ACTION_NAME = new InheritableThreadLocal(); public static InheritableThreadLocal<String> CLIENT_ADDR = new InheritableThreadLocal(); /** * * @return */ public static Core getInstance() { return THREAD_CORE.get(); } /** * * * @param <T> * @param clas * @return */ public static <T>T getInstance(Class<T> clas) { return getInstance().get(clas); } /** * * * @param name * @return */ public static Object getInstance(String name) { return getInstance().get(name); } /** * * * 3612(ID), * "2059/01/01 00:00:00". * : 0~9A~Z * * @param svid ID * @return */ public static String newIdentity(String svid) { long n; n = System.currentTimeMillis( ); String time = String.format("%8s", Long.toString(n, 36)); n = Thread.currentThread().getId(); String trid = String.format("%4s", Long.toString(n, 36)); n = (long) ( Math.random() * 1679615); //36^4-1 String rand = String.format("%4s", Long.toString(n, 36)); if (time.length() > 8) time = time.substring(time.length() - 8); if (trid.length() > 4) trid = trid.substring(trid.length() - 4); if (rand.length() > 4) rand = rand.substring(rand.length() - 4); return new StringBuilder() .append(time).append(trid) .append(rand).append(svid) .toString().toUpperCase( ) .replace ( ' ' , '0' ); } /** * * * ID(Core.SERVER_ID) * * @return */ public static String newIdentity() { return Core.newIdentity(Core.SERVER_ID); } /** * * @return */ public static Locale getLocality() { Core core = Core.getInstance(); String name = Locale.class.getName(); Locale inst = (Locale)core.got(name); if (null != inst) { return inst; } String[] lang = Core.ACTION_LANG.get().split("_",2); if (2 <= lang.length) { inst = new Locale(lang[0],lang[1]); } else { inst = new Locale(lang[0]); } core.put(name, inst); return inst; } /** * * @return */ public static TimeZone getTimezone() { Core core = Core.getInstance(); String name = TimeZone.class.getName(); TimeZone inst = (TimeZone)core.got(name); if (null != inst) { return inst; } inst = TimeZone.getTimeZone(Core.ACTION_ZONE.get()); core.put(name, inst); return inst; } / static public interface Closeable extends AutoCloseable { public boolean closeable (); } /** * * , (, Core.getInstance) */ static public interface Singleton {} }
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import innovimax.mixthem.MixThem; import java.util.logging.Level; /** * <p>Zips two lines on a common field.</p> * @see ILineOperation * @author Innovimax * @version 1.0 */ public class DefaultLineZipping implements ILineOperation { /** * Returns the result of zipping two lines. * @param line1 The first line to zip * @param line2 The second line to zip * @return The result of zipping two lines * @throws MixException - If an mixing error occurs */ @Override public String process(String line1, String line2) throws MixException { String zippedLine = null; if (line1 != null && line2 != null) { MixThem.LOGGER.logp(Level.INFO, "DefaultLineZipping", "zip", "TO IMPLEMENT"); } return zippedLine; } }
package com.countrygamer.pvz.client.gui; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.countrygamer.countrygamer_core.Client.Gui.GuiButtonArrow; import com.countrygamer.countrygamer_core.Client.Gui.GuiButtonArrow.ButtonType; import com.countrygamer.pvz.items.ItemGuideBook; import com.countrygamer.pvz.lib.Reference; public class GuiGuide extends GuiScreen { private static final ResourceLocation book = new ResourceLocation( Reference.MOD_ID, "textures/gui/book1.png"); private int bookImageWidth = 256; private int bookImageHeight = 256; private int page = 0; private int totalPage = 20; private GuiButtonArrow nextRecipeButtonIndex; private GuiButtonArrow previousRecipeButtonIndex; private GuiButton a; private GuiButton b; private GuiButton c; private GuiButton d; private GuiButton e; private GuiButton f; public ItemGuideBook itemBook; public GuiGuide(ItemGuideBook itemBook) { this.itemBook = itemBook; } public void initGui() { super.initGui(); int i = this.width / 2 - this.bookImageWidth / 2; int j = this.height / 2 - this.bookImageHeight / 2; this.buttonList.add(this.nextRecipeButtonIndex = new GuiButtonArrow(1, i + this.bookImageWidth - 30, j + 190, ButtonType.RIGHT)); this.buttonList .add(this.previousRecipeButtonIndex = new GuiButtonArrow(2, i + 17, j + 190, ButtonType.LEFT)); this.nextRecipeButtonIndex.enabled = false; this.previousRecipeButtonIndex.enabled = false; String table = "Table of Contents"; int butW = table.length() * 6; int x = this.width / 2 - butW / 2; this.buttonList.add(new GuiButton(3, x, 20, butW, 20, table)); } protected void actionPerformed(GuiButton gB) { int i = gB.id; switch (i) { case 0: this.page = 0; initGui(); break; case 1: if (this.page >= this.totalPage) break; this.page += 1; break; case 2: if (this.page <= 0) break; this.page -= 1; break; case 4: this.page = 2; break; case 5: this.page = 4; break; case 6: this.page = 10; break; case 7: this.page = 12; break; case 8: this.page = 14; break; case 9: this.page = 17; case 3: } } public void updateScreen() { this.nextRecipeButtonIndex.enabled = (this.page < this.totalPage); this.previousRecipeButtonIndex.enabled = (this.page > 0); } public boolean doesGuiPauseGame() { return false; } public void drawScreen(int i, int j, float f) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.mc.getTextureManager().bindTexture(book); int k = this.width / 2 - this.bookImageWidth / 2; byte b0 = 30; drawTexturedModalRect(k, b0, 0, 0, this.bookImageWidth, this.bookImageHeight); initGui(); int xl = k + 15; String[] str; int y1; switch (this.page) { case 0: string("TABLE OF CONTENTS", xl + 65, b0 + 15); break; case 1: str = new String[] { "Crazy Dave's Plant Guide", "By: TheCountryGamer", "Mod Website:", "plantsvszombies-minecraft.com", "I hope you enjoy the mod!" }; int pCe = this.width / 2; string(str[0], xl + 55, b0 + 15); string(str[1], xl + 65, b0 + 30); string(str[2], xl + 80, b0 + 45); string(str[3], xl + 40, b0 + 55); string(str[4], xl + 50, b0 + 75); break; case 2: str = new String[] { "Getting Started", "First, you will need to collect some", "Chlorophyll. (insert picture)", "This can be CRAFTED from many natural", "things from the Vanilla (Not Modded) game.", "The full list is as follows:", "Seeds, Carrots, and Potato ITEMS will each", "output 2 Chlorophyll when CRAFTED.", "The Tall Grass BLOCK will give you 3", "Chlorophyll when CRAFTED." }; string(str[0], xl + 75, b0 + 15); y1 = 20; for (int index = 1; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 3: str = new String[] { "Getting Started", "(continued)", "Any Leaves BLOCK", "will give you 4", "Chlorophyll when", "CRAFTED. The Cactus", "BLOCK will give you", "5 Chlorophyll when", "CRAFTED." }; string(str[0], xl + 75, b0 + 15); string(str[1], xl + 80, b0 + 25); y1 = 30; for (int index = 2; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 4: str = new String[] { "Getting the Utilities", "Chlorophyll Bowl", "First, you will need a Chlorophyll Bowl. This", "block allows you to produce Sunlight (During", "Daytime) and Moonlight (During Nighttime).", "HINT: You might try using a daytime", "controller like the CommandBlock to control", "production. To CRAFT a Chlorophyll Bowl,", "you will need 4 Chlorophyll and 1 Wooden", "Bowl. Place these in any old Crafting Bench", "in any slot." }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 15, b0 + 25); y1 = 30; for (int index = 2; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 5: str = new String[] { "Getting the Utilities", "(continued)", "Crazy Dave's Box", "Next up is Crazy Dave's Box. This box allows", "you to get the Tier 1 Plant(s), some Plant", "Food and the Recipes for Special Plants", "(All of these are described in the", "Greenhouse Section)." }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 80, b0 + 25); string(str[2], xl + 15, b0 + 35); y1 = 40; for (int index = 3; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 6: str = new String[] { "Getting the Utilities", "(continued)", "If you (right) click on Crazy Dave's Box,", "you will open the GUI. You will find that on", "the bottom half is your inventory/hot-bar,", "and the top half consists 2 input slots and", "1 output slot. One of the input slots has", "the background of a Sunlight Item. This slot", "is where you will place either Sunlight or", "Moonlight, depending on the desired output.", "The other input slot is where you will put", "your modifier. This modifier helps determine", "which item will be outputted." }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 80, b0 + 25); y1 = 30; for (int index = 3; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 7: str = new String[] { "Getting the Utilities", "(continued)", "Greenhouse", "Now that you have Crazy Dave's Box, you", "can get the first Tier of items. These can", "later be upgraded using this block", "First things first. You can CRAFT the", "Greenhouse by putting 5 Glass Pane's, 1", "block of Dirt, and 2 blocks of Cobblestone", "in a Crafting Bench as so: (insert picture)" }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 80, b0 + 25); string(str[2], xl + 15, b0 + 35); y1 = 40; for (int index = 3; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 8: str = new String[] { "Getting the Utilities", "(continued)", "After you place your Greenhouse, you can", "(right) click on the block to find this GUI:", "(insert picture)", "Here, you will find 1 input slot, 2 modifier", "slots, and 1 output slot (for now ;D). As of", "now, Plant Food and Special Recipes are NOT", "implemented." }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 80, b0 + 25); y1 = 30; for (int index = 3; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 9: str = new String[] { "Getting the Utilities", "(continued)", "To use the Greenhouse, first find your targeted", "output below. To get that output, you must", "put the appropriate; input item in the input", "(the slot with the pea shooter plant),", "modifier1 item in the modifier1 slot (the slot", "with the sunlight item), modifier2 item in the", "modifier2 slot (the slot with the snowball).", "Normally, each upgrade take approximately", "600 ticks (thats about 300 seconds)" }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 80, b0 + 25); y1 = 30; for (int index = 3; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 10: str = new String[] { "Getting Ready", "Alright. Cool. Now that you have at least the", "Pea Shooter plant (Tier 1: Day Faction), we", "can get ready to spawn him into the world.", "Assuming you have the PeaShooterPlant Item,", "we want to get the Grass that he needs to", "spawn on." }; string(str[0], xl + 65, b0 + 15); y1 = 20; for (int index = 1; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 11: str = new String[] { "Getting Ready", "(continued)", "Endowed Grass", "When you (right) click with the Sunlight Item,", "you will spawn the Sunlight Projectile. If this", "hits Grass, Dirt or Mycelium, it will turn it", "into Endowed Grass.", "Darkened Grass", "When you (right) click with the Moonlight", "Item, you will spawn the Moonlight Projectile.", "If this hits Grass, Dirt or Mycelium, it", "will turn it into Darkened Grass." }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 80, b0 + 25); string(str[2], xl + 15, b0 + 40); y1 = 40; for (int index = 3; index < 7; index++) { y1 += 10; string(str[index], xl, b0 + y1); } string(str[7], xl + 15, b0 + 90); y1 = 90; for (int index = 8; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 12: str = new String[] { "Spawning your Plant", "To spawn your plant, you must get the", "corresponding Plant Item (in this case; Pea", "Shooter Plant). With the Pea Shooter Plant,", "you will see above that it is a Tier 1: Day", "Faction Plant. This means it is a very basic", "Plant in the Faction of Day Plants. You will", "also note that the Block it spawns on is", "Endowed Grass. You will now want to place", "your Endowed Grass, that you made in", "'Getting Ready', right below where you want", "your Plant to spawn. When you spawn a Plant,", "it will turn the block below it into regular" }; string(str[0], xl + 65, b0 + 15); y1 = 20; for (int index = 1; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 13: str = new String[] { "Spawing your Plant", "(continued)", "Grass, UNLESS it is said differently in the", "Notes section of that Plant in the 'Almanac'.", "On placing your Plant, you will note that the", "Plant Entity is spawned and the block below", "is turned into Grass (Unless otherwise", "noted). Your Plant is now ready to defend", "you and your home! Hooray!" }; string(str[0], xl + 65, b0 + 15); string(str[1], xl + 80, b0 + 25); y1 = 30; for (int index = 2; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 14: str = new String[] { "Getting Set", "Okay. So now you are ready to build a", "massive Plant army. But wait. What about", "tools? Well we come to you today to", "present: the Trowels! Thats right! Trowels!", "There are 2 Trowels. There is the normal", "Trowel and the Transplant Trowel. You might", "even be able to note what they do!", "Well right off the bat, they will help you", "to dig out dirt blocks (like Shovels/Spades", "do). They are made from IronIngots, and", "therefore have all the properties of a", "normal Iron Shovel." }; string(str[0], xl + 75, b0 + 15); y1 = 20; for (int index = 1; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 15: str = new String[] { "Getting Set", "(continued)", "The Trowel will also do other things. First,", "if you (right) click on a Endowed Grass you", "will turn it back to Grass and get the", "Sunlight back, or Darkened Grass and get", "Moonlight back. If you use ((right) click) a", "Trowel on any Plant, you will instantly", "remove that Plant, gaining no resources in", "return. The Transplant Trowel will act the", "same as the Trowel, but if you (right) click", "on an Plant," }; string(str[0], xl + 75, b0 + 15); string(str[1], xl + 80, b0 + 25); y1 = 30; for (int index = 2; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 16: str = new String[] { "Getting Set", "(continued)", "you will get that Plant's Item back again.", "This way, if you accidentally place a", "plant where you didn't want it, you can", "re-plant that Plant!" }; string(str[0], xl + 75, b0 + 15); string(str[1], xl + 80, b0 + 25); y1 = 30; for (int index = 2; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } break; case 17: str = new String[] { "Additional Things", "Now, aside from the way to get the plants,", "we also have other items and blocks that", "you can have fun with!", "Pod Projectiles", "So you know how those plants shoot pea", "pods, well now you can too! There are Pea", "Pods, Snow Pods, Shroom Pods, and", "Creeper Pods. To shoot these, you must", "(right) click, and it will spawn the", "projectile, using it up." }; string(str[0], xl + 75, b0 + 15); y1 = 15; for (int index = 1; index < 4; index++) { y1 += 10; string(str[index], xl, b0 + y1); } y1 += 10; string(str[4], xl + 20, b0 + y1); for (int index = 5; index < str.length; index++) { y1 += 10; string(str[index], xl, b0 + y1); } } super.drawScreen(i, j, f); } private void string(String str, int x, int y) { this.fontRendererObj.drawString(str, x, y, 0); } }
package filter; import model.*; import org.junit.*; import static java.util.Arrays.asList; import static model.FragmentBuilder.fragmentBuilder; import static model.ProductBuilder.productBuilder; import static model.SegmentBuilder.segmentBuilder; import static model.SegmentRuleBuilder.segmentRuleBuilder; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.MockitoAnnotations.initMocks; import static utils.MapBuilder.mapBuilder; public class SegmentRuleFilterTest { private SegmentRuleFilter segmentRuleFilter; @Before public void setup() { initMocks(this); segmentRuleFilter = new SegmentRuleFilter(); } @Test public void testFilterSegmentRules_MatchedAttribute_TwoMatched() { Product product = productBuilder() .id("product 1") .segmentRuleIds(asList("segment rule id 1")) .build(); SegmentRule segmentRule = segmentRuleBuilder() .id("segment rule id 1") .segmentIds(asList("segment id 1")) .build(); Segment segment = segmentBuilder() .id("segment id 1") .fragmentIds(asList("fragment id 1")) .build(); Fragment fragment = fragmentBuilder() .id("segment rule id 1") .requiredAttributes(mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "another_matched_value") .build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "another_matched_value") .build(), asList(segmentRule), asList(segment), asList(fragment)); assertTrue(result); } @Test public void testFilterSegmentRules_MultipleAttributes_OneMatchedOneUnmatched() { Product product = productBuilder() .id("product 1") .segmentRuleIds(asList("segment rule id 1")) .build(); SegmentRule segmentRule = segmentRuleBuilder() .id("segment rule id 1") .segmentIds(asList("segment id 1")) .build(); Segment segment = segmentBuilder() .id("segment id 1") .fragmentIds(asList("fragment id 1")) .build(); Fragment fragment = fragmentBuilder() .id("segment rule id 1") .requiredAttributes( mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "this_value_will_not_be_matched") .build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "some_unmatched_value") .build(), asList(segmentRule), asList(segment), asList(fragment)); assertFalse(result); } @Test public void testFilterSegmentRules_MultipleFragments_TwoMatched() { Product product = productBuilder() .id("product 1") .segmentRuleIds(asList("segment rule id 1")) .build(); SegmentRule segmentRule = segmentRuleBuilder() .id("segment rule id 1") .segmentIds(asList("segment id 1")) .build(); Segment segment = segmentBuilder() .id("segment id 1") .fragmentIds(asList("matched fragment", "another matched fragment")) .build(); Fragment matchedFragment = fragmentBuilder() .id("matched fragment") .requiredAttributes(mapBuilder().put("key_one", "some_matched_value").build()) .build(); Fragment anotherMatchedFragment = fragmentBuilder() .id("another matched fragment") .requiredAttributes(mapBuilder().put("key_two", "another_matched_value").build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "another_matched_value") .build(), asList(segmentRule), asList(segment), asList(matchedFragment, anotherMatchedFragment)); assertTrue(result); } @Test public void testFilterSegmentRules_MultipleFragments_OneMatchedOneUnmatched() { Product product = productBuilder() .id("product 1") .segmentRuleIds(asList("segment rule id 1")) .build(); SegmentRule segmentRule = segmentRuleBuilder() .id("segment rule id 1") .segmentIds(asList("segment id 1")) .build(); Segment segment = segmentBuilder() .id("segment id 1") .fragmentIds(asList("matched fragment", "unmatched fragment")) .build(); Fragment matchedFragment = fragmentBuilder() .id("matched fragment") .requiredAttributes(mapBuilder().put("key_one", "some_matched_value").build()) .build(); Fragment unmatchedFragment = fragmentBuilder() .id("unmatched fragment") .requiredAttributes(mapBuilder().put("key_two", "this_value_will_not_be_matched").build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "some_unmatched_value") .build(), asList(segmentRule), asList(segment), asList(matchedFragment, unmatchedFragment)); assertFalse(result); } @Test public void testFilterSegmentRules_MultipleSegments_TwoMatched() { Product product = productBuilder().id("product 1").segmentRuleIds(asList("segment rule id 1")).build(); SegmentRule segmentRule = segmentRuleBuilder() .id("segment rule id 1") .segmentIds(asList("matched segment", "another matched segment")) .build(); Segment matchedSegment = segmentBuilder() .id("matched segment") .fragmentIds(asList("matched fragment")) .build(); Segment anotherMatchedSegment = segmentBuilder() .id("another matched segment") .fragmentIds(asList("another matched fragment")) .build(); Fragment matchedFragment = fragmentBuilder() .id("matched fragment") .requiredAttributes(mapBuilder().put("key_one", "some_matched_value").build()) .build(); Fragment anotherMatchedFragment = fragmentBuilder() .id("another matched fragment") .requiredAttributes(mapBuilder().put("key_two", "another_matched_value").build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "another_matched_value") .build(), asList(segmentRule), asList(matchedSegment, anotherMatchedSegment), asList(matchedFragment, anotherMatchedFragment)); assertTrue(result); } @Test public void testFilterSegmentRules_MultipleSegments_OneMatchedOneUnmatched() { Product product = productBuilder().id("product 1").segmentRuleIds(asList("segment rule id 1")).build(); SegmentRule segmentRule = segmentRuleBuilder() .id("segment rule id 1") .segmentIds(asList("matched segment", "another matched segment")) .build(); Segment matchedSegment = segmentBuilder() .id("matched segment") .fragmentIds(asList("matched fragment")) .build(); Segment unmatchedSegment = segmentBuilder() .id("unmatched segment") .fragmentIds(asList("unmatched fragment")) .build(); Fragment matchedFragment = fragmentBuilder() .id("matched fragment") .requiredAttributes(mapBuilder().put("key_one", "some_matched_value").build()) .build(); Fragment unmatchedFragment = fragmentBuilder() .id("unmatched fragment") .requiredAttributes(mapBuilder().put("key_two", "this_value_will_not_be_matched").build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "unmatched_value") .build(), asList(segmentRule), asList(matchedSegment, unmatchedSegment), asList(matchedFragment, unmatchedFragment)); assertFalse(result); } @Test public void testFilterSegmentRules_MultipleSegmentRules_TwoMatched() { Product product = productBuilder() .id("product 1") .segmentRuleIds(asList("matched segment rule", "another matched segment rule")) .build(); SegmentRule matchedSegmentRule = segmentRuleBuilder() .id("matched segment rule") .segmentIds(asList("matched segment")) .build(); SegmentRule anotherMatchedSegmentRule = segmentRuleBuilder() .id("another matched segment rule") .segmentIds(asList("another matched segment")) .build(); Segment matchedSegment = segmentBuilder() .id("matched segment") .fragmentIds(asList("matched fragment")) .build(); Segment anotherMatchedSegment = segmentBuilder() .id("another matched segment") .fragmentIds(asList("another matched fragment")) .build(); Fragment matchedFragment = fragmentBuilder() .id("matched fragment") .requiredAttributes(mapBuilder().put("key_one", "some_matched_value").build()) .build(); Fragment anotherMatchedFragment = fragmentBuilder() .id("another matched fragment") .requiredAttributes(mapBuilder().put("key_two", "another_matched_value").build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "another_matched_value") .build(), asList(matchedSegmentRule, anotherMatchedSegmentRule), asList(matchedSegment, anotherMatchedSegment), asList(matchedFragment, anotherMatchedFragment)); assertTrue(result); } @Test public void testFilterSegmentRules_MultipleSegmentRules_OneMatchedOneUnmatched() { Product product = productBuilder() .id("product 1") .segmentRuleIds(asList("matched segment rule", "unmatched segment rule")) .build(); SegmentRule matchedSegmentRule = segmentRuleBuilder() .id("matched segment rule") .segmentIds(asList("matched segment")) .build(); SegmentRule unmatchedSegmentRule = segmentRuleBuilder() .id("unmatched segment rule") .segmentIds(asList("unmatched segment")) .build(); Segment matchedSegment = segmentBuilder() .id("matched segment") .fragmentIds(asList("matched fragment")) .build(); Segment unmatchedSegment = segmentBuilder() .id("unmatched segment") .fragmentIds(asList("unmatched fragment")) .build(); Fragment matchedFragment = fragmentBuilder() .id("matched fragment") .requiredAttributes(mapBuilder().put("key_one", "some_matched_value").build()) .build(); Fragment unmatchedFragment = fragmentBuilder() .id("another matched fragment") .requiredAttributes(mapBuilder().put("key_two", "this_value_will_not_be_matched").build()) .build(); boolean result = segmentRuleFilter.filterSegmentRules( product, mapBuilder() .put("key_one", "some_matched_value") .put("key_two", "unmatched_value") .build(), asList(matchedSegmentRule, unmatchedSegmentRule), asList(matchedSegment, unmatchedSegment), asList(matchedFragment, unmatchedFragment)); assertFalse(result); } }
package main.java.com.bag.database; import main.java.com.bag.exceptions.OutDatedDataException; import main.java.com.bag.database.interfaces.IDatabaseAccess; import main.java.com.bag.util.*; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import org.jetbrains.annotations.NotNull; import org.neo4j.cluster.ClusterSettings; import org.neo4j.graphdb.*; import org.neo4j.graphdb.factory.GraphDatabaseBuilder; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory; import org.neo4j.kernel.ha.HaSettings; import org.neo4j.kernel.impl.core.NodeProxy; import org.neo4j.kernel.impl.core.RelationshipProxy; import java.io.File; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.stream.Collectors; import static main.java.com.bag.util.Constants.TAG_PRE; import static main.java.com.bag.util.Constants.TAG_VERSION; /** * Class created to handle access to the neo4j database. */ public class Neo4jDatabaseAccess implements IDatabaseAccess { /** * Base path location of the Neo4j database. */ private static final String BASE_PATH = System.getProperty("user.home") + "/Neo4jDB"; /** * String used to match key value pairs. */ private static final String KEY_VALUE_PAIR = "%s: {%s}"; /** * String used to match keys. */ private static final String MATCH = "MATCH "; /** * If the DB runs in multi-version mode. */ private final boolean multiVersion; /** * The graphDB object. */ private GraphDatabaseService graphDb; /** * Id of the database. (If multiple running on the same machine. */ private final int id; /** * If we're running a direct access client, has Neo4j's database address */ private final String haAddresses; /** * Public constructor. * * @param id, id of the server. */ public Neo4jDatabaseAccess(final int id, final String haAddresses, final boolean multiVersion) { this.id = id; this.haAddresses = haAddresses; this.multiVersion = multiVersion; } @Override public void start() { final File dbPath = new File(BASE_PATH + id); Log.getLogger().warn("Starting neo4j database service on " + id); if (haAddresses == null) { graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(dbPath).newGraphDatabase(); registerShutdownHook(graphDb); try (Transaction tx = graphDb.beginTx()) { graphDb.execute("CREATE INDEX ON :Node(idx)"); tx.success(); } } else { final GraphDatabaseBuilder builder = new HighlyAvailableGraphDatabaseFactory().newEmbeddedDatabaseBuilder(dbPath); final String[] addresses = haAddresses.split(";"); final List<String> initialHosts = new ArrayList<>(); final List<String> servers = new ArrayList<>(); for (int i = 0; i < addresses.length; i++) { initialHosts.add(String.format("%s:500%d", addresses[i], (i + 1))); servers.add(String.format("%s:600%d", addresses[i], (i + 1))); } builder.setConfig(ClusterSettings.server_id, Integer.toString(id + 1)); builder.setConfig(ClusterSettings.initial_hosts, String.join(",", initialHosts)); builder.setConfig(HaSettings.ha_server, servers.get(0)); builder.setConfig(ClusterSettings.cluster_server, initialHosts.get(id)); graphDb = builder.newGraphDatabase(); Log.getLogger().warn("HA neo4j database started " + id); if (id > 0) { new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { Log.getLogger().warn("Ping..."); } }, 0, 60000); } } } @Override public void terminate() { Log.getLogger().info("Shutting down Neo4j manually"); graphDb.shutdown(); } /** * Creates a transaction which will get a list of nodes. * * @param identifier the nodes which should be retrieved. * @return the result nodes as a List of NodeStorages.. */ @NotNull public List<Object> readObject(@NotNull final Object identifier, final long snapshotId) throws OutDatedDataException { NodeStorage nodeStorage = null; RelationshipStorage relationshipStorage = null; if (identifier instanceof NodeStorage) { nodeStorage = (NodeStorage) identifier; } else if (identifier instanceof RelationshipStorage) { relationshipStorage = (RelationshipStorage) identifier; } else { Log.getLogger().warn("Can't read data on object: " + identifier.getClass().toString()); return Collections.emptyList(); } if (graphDb == null) { start(); } //We only support 1 label each node/vertex because of compatibility with our graph dbs. final ArrayList<Object> returnStorage = new ArrayList<>(); try (Transaction tx = graphDb.beginTx()) { final StringBuilder builder = new StringBuilder(MATCH); final Map<String, Object> properties; if (nodeStorage == null) { Log.getLogger().info(Long.toString(snapshotId)); builder.append(buildRelationshipString(relationshipStorage)); builder.append(" RETURN r"); Log.getLogger().info(builder.toString()); //Contains params of relationshipStorage. properties = transFormToPropertyMap(relationshipStorage.getProperties(), ""); //Adds also params of start and end node. properties.putAll(transFormToPropertyMap(relationshipStorage.getStartNode().getProperties(), "1")); properties.putAll(transFormToPropertyMap(relationshipStorage.getEndNode().getProperties(), "2")); } else { Log.getLogger().info(Long.toString(snapshotId)); builder.append(buildNodeString(nodeStorage, "")); builder.append(" RETURN n"); Log.getLogger().info(builder.toString()); //Converts the keys to upper case to fit the params we send to neo4j. properties = transFormToPropertyMap(nodeStorage.getProperties(), ""); } Log.getLogger().info("To database: " + builder.toString()); final Result result = graphDb.execute(builder.toString(), properties); while (result.hasNext()) { final Map<String, Object> value = result.next(); for (final Map.Entry<String, Object> entry : value.entrySet()) { if (entry.getValue() instanceof NodeProxy) { final NodeProxy n = (NodeProxy) entry.getValue(); NodeStorage temp = new NodeStorage(n.getLabels().iterator().next().name(), n.getAllProperties()); if (temp.getProperties().containsKey(Constants.TAG_SNAPSHOT_ID)) { final Object sId = temp.getProperties().get(Constants.TAG_SNAPSHOT_ID); if (multiVersion) { temp = OutDatedDataException.getCorrectNodeStorage(sId, snapshotId, temp); } else { OutDatedDataException.checkSnapshotId(sId, snapshotId); } temp.removeProperty(Constants.TAG_SNAPSHOT_ID); } temp.removeProperty(Constants.TAG_HASH); if (multiVersion) { // If the version int is < 0, it means it is outdated and we don't need it. final Object propPre = temp.getProperty(TAG_PRE); if(propPre instanceof NodeProxy) { temp.removeProperty(TAG_PRE); } final Object propV = temp.getProperty(TAG_VERSION); if(propV instanceof Integer) { if((Integer) propV < 0) { continue; } temp.removeProperty(TAG_VERSION); } } returnStorage.add(temp); } else if (entry.getValue() instanceof RelationshipProxy) { final RelationshipProxy r = (RelationshipProxy) entry.getValue(); final NodeStorage start = new NodeStorage(r.getStartNode().getLabels().iterator().next().name(), r.getStartNode().getAllProperties()); final NodeStorage end = new NodeStorage(r.getEndNode().getLabels().iterator().next().name(), r.getEndNode().getAllProperties()); RelationshipStorage temp = new RelationshipStorage(r.getType().name(), r.getAllProperties(), start, end); if (temp.getProperties().containsKey(Constants.TAG_SNAPSHOT_ID)) { final Object sId = temp.getProperties().get(Constants.TAG_SNAPSHOT_ID); if (multiVersion) { temp = OutDatedDataException.getCorrectRSStorage(sId, snapshotId, temp); } else { OutDatedDataException.checkSnapshotId(sId, snapshotId); } temp.removeProperty(Constants.TAG_SNAPSHOT_ID); } temp.removeProperty(Constants.TAG_HASH); if (multiVersion) { // If the version int is < 0, it means it is outdated and we don't need it. final Object propPre = temp.getProperty(TAG_PRE); if(propPre instanceof RelationshipProxy) { temp.removeProperty(TAG_PRE); } final Object propV = temp.getProperty(TAG_VERSION); if(propV instanceof Integer) { if((Integer) propV < 0) { continue; } temp.removeProperty(TAG_VERSION); } } returnStorage.add(temp); } } } tx.success(); } return returnStorage; } @Override public boolean shouldFollow(final int sequence) { return sequence != 9; } /** * Transforms a map of properties to a map of params for neo4j. * * @param map the map to transform. * @param id the id to add. * @return the transformed map. */ private Map<String, Object> transFormToPropertyMap(final Map<String, Object> map, final String id) { return map.entrySet().stream() .collect(Collectors.toMap( e -> e.getKey().toUpperCase() + id, Map.Entry::getValue)); } /** * Creates a complete Neo4j cypher String for a certain relationshipStorage * * @param relationshipStorage the relationshipStorage to transform. * @return a string which may be sent with cypher to neo4j. */ private String buildRelationshipString(final RelationshipStorage relationshipStorage) { return buildNodeString(relationshipStorage.getStartNode(), "1") + buildPureRelationshipString(relationshipStorage) + buildNodeString(relationshipStorage.getEndNode(), "2"); } /** * Creates a Neo4j cypher String for a certain relationshipStorage * * @param relationshipStorage the relationshipStorage to transform. * @return a string which may be sent with cypher to neo4j. */ private String buildPureRelationshipString(final RelationshipStorage relationshipStorage) { final StringBuilder builder = new StringBuilder(); builder.append("-[r"); if (!relationshipStorage.getId().isEmpty()) { builder.append(String.format(":%s", relationshipStorage.getId())); } if (!relationshipStorage.getProperties().isEmpty()) { builder.append(" {"); final Iterator<Map.Entry<String, Object>> iterator = relationshipStorage.getProperties().entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, Object> currentProperty = iterator.next(); builder.append(String.format(KEY_VALUE_PAIR, currentProperty.getKey(), currentProperty.getKey().toUpperCase())); if (iterator.hasNext()) { builder.append(" , "); } } builder.append("}"); } builder.append("]->"); return builder.toString(); } /** * Creates a Neo4j cypher String for a certain nodeStorage. * * @param nodeStorage the nodeStorage to transform. * @param n optional identifier in the query. * @return a string which may be sent with cypher to neo4j. */ private String buildNodeString(final NodeStorage nodeStorage, final String n) { final StringBuilder builder = new StringBuilder("(n").append(n); if (!nodeStorage.getId().isEmpty()) { builder.append(String.format(":%s", nodeStorage.getId())); } if (!nodeStorage.getProperties().isEmpty()) { builder.append(" {"); final Iterator<Map.Entry<String, Object>> iterator = nodeStorage.getProperties().entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, Object> currentProperty = iterator.next(); builder.append(String.format(KEY_VALUE_PAIR, currentProperty.getKey(), currentProperty.getKey().toUpperCase() + n)); if (iterator.hasNext()) { builder.append(" , "); } } builder.append("}"); } builder.append(")"); return builder.toString(); } @Override public boolean compareNode(final NodeStorage nodeStorage) { if (graphDb == null) { start(); } final String builder = MATCH + buildNodeString(nodeStorage, "") + " RETURN n"; final Map<String, Object> properties = transFormToPropertyMap(nodeStorage.getProperties(), ""); final Result result = graphDb.execute(builder, properties); //Assuming we only get one node in return. if (result.hasNext()) { final Map<String, Object> value = result.next(); for (final Map.Entry<String, Object> entry : value.entrySet()) { if (entry.getValue() instanceof NodeProxy) { final NodeProxy n = (NodeProxy) entry.getValue(); try { return HashCreator.sha1FromNode(nodeStorage).equals(n.getProperty(Constants.TAG_HASH)); } catch (final NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't execute SHA1 for node", e); } break; } } } //If can't find the node its different probably. return false; } @Override public boolean applyUpdate(final NodeStorage key, final NodeStorage value, final long snapshotId) { try { graphDb.beginTx(); final Map<String, Object> tempProperties = transFormToPropertyMap(key.getProperties(), ""); final Result result = graphDb.execute(MATCH + buildNodeString(key, "") + " RETURN n", tempProperties); while (result.hasNext()) { final Map<String, Object> resultValue = result.next(); for (final Map.Entry<String, Object> entry : resultValue.entrySet()) { if (entry.getValue() instanceof NodeProxy) { final NodeProxy proxy = (NodeProxy) entry.getValue(); if(multiVersion) { final Object obj = proxy.getProperty(TAG_VERSION); proxy.setProperty(TAG_PRE, proxy); proxy.setProperty(TAG_VERSION, obj instanceof Integer ? (Integer) obj + 1 : 1); } for (final Map.Entry<String, Object> properties : value.getProperties().entrySet()) { proxy.setProperty(properties.getKey(), properties.getValue()); } proxy.setProperty(Constants.TAG_HASH, HashCreator.sha1FromNode(new NodeStorage(proxy.getLabels().iterator().next().name(), proxy.getAllProperties()))); proxy.setProperty(Constants.TAG_SNAPSHOT_ID, snapshotId); } } } } catch (final Exception e) { Log.getLogger().warn("Couldn't execute update node transaction in server: " + id, e); return false; } Log.getLogger().info("Executed update node transaction in server: " + id); return true; } @Override public boolean applyCreate(final NodeStorage storage, final long snapshotId) { try (Transaction tx = graphDb.beginTx()) { final Label label = storage::getId; final Node myNode = graphDb.createNode(label); for (final Map.Entry<String, Object> entry : storage.getProperties().entrySet()) { myNode.setProperty(entry.getKey(), entry.getValue()); } myNode.setProperty(Constants.TAG_HASH, HashCreator.sha1FromNode(storage)); myNode.setProperty(Constants.TAG_SNAPSHOT_ID, snapshotId); if (multiVersion) { myNode.setProperty(TAG_VERSION, null); myNode.setProperty(TAG_PRE, null); } tx.success(); } catch (final Exception e) { Log.getLogger().warn("Couldn't execute create node transaction in server: " + id, e); return false; } Log.getLogger().info("Executed create node transaction in server: " + id); return true; } @Override public boolean applyDelete(final NodeStorage storage, final long snapshotId) { try { if(multiVersion) { final NodeStorage value = new NodeStorage(storage); value.addProperty(TAG_VERSION, -1); return applyUpdate(storage, value, snapshotId); } else { final Map<String, Object> properties = transFormToPropertyMap(storage.getProperties(), ""); final String cypher = MATCH + buildNodeString(storage, "") + " DETACH DELETE n"; graphDb.execute(cypher, properties); } } catch (final Exception e) { Log.getLogger().warn("Couldn't execute delete node transaction in server: " + id, e); return false; } Log.getLogger().info("Executed delete node transaction in server: " + id); return true; } @Override public boolean applyUpdate(final RelationshipStorage key, final RelationshipStorage value, final long snapshotId) { try { //Transform relationship params. final Map<String, Object> propertyMap = transFormToPropertyMap(key.getProperties(), ""); //Adds also params of start and end node. propertyMap.putAll(transFormToPropertyMap(key.getStartNode().getProperties(), "1")); propertyMap.putAll(transFormToPropertyMap(key.getEndNode().getProperties(), "2")); final Result result = graphDb.execute(MATCH + buildRelationshipString(key) + " RETURN r", propertyMap); while (result.hasNext()) { final Map<String, Object> relValue = result.next(); for (final Map.Entry<String, Object> entry : relValue.entrySet()) { if (entry.getValue() instanceof RelationshipProxy) { final RelationshipProxy proxy = (RelationshipProxy) entry.getValue(); if(multiVersion) { final Object obj = proxy.getProperty(TAG_VERSION); proxy.setProperty(TAG_PRE, proxy); proxy.setProperty(TAG_VERSION, obj instanceof Integer ? (Integer) obj + 1 : 1); } for (final Map.Entry<String, Object> properties : value.getProperties().entrySet()) { proxy.setProperty(properties.getKey(), properties.getValue()); } final NodeStorage start = new NodeStorage(proxy.getStartNode().getLabels().iterator().next().name(), proxy.getStartNode().getAllProperties()); final NodeStorage end = new NodeStorage(proxy.getEndNode().getLabels().iterator().next().name(), proxy.getEndNode().getAllProperties()); proxy.setProperty(Constants.TAG_HASH, HashCreator.sha1FromRelationship(new RelationshipStorage(proxy.getType().name(), proxy.getAllProperties(), start, end))); proxy.setProperty(Constants.TAG_SNAPSHOT_ID, snapshotId); } } } } catch (final NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't execute update relationship transaction in server: " + id, e); return false; } Log.getLogger().info("Executed update relationship transaction in server: " + id); return true; } @Override public boolean applyCreate(final RelationshipStorage storage, final long snapshotId) { try { final RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode()); tempStorage.addProperty(Constants.TAG_HASH, HashCreator.sha1FromRelationship(storage)); tempStorage.addProperty(Constants.TAG_SNAPSHOT_ID, snapshotId); final String builder = MATCH + buildNodeString(tempStorage.getStartNode(), "1") + ", " + buildNodeString(tempStorage.getEndNode(), "2") + " CREATE (n1)" + buildPureRelationshipString(tempStorage) + "(n2)"; if (multiVersion) { tempStorage.addProperty(TAG_VERSION,null); tempStorage.addProperty(TAG_PRE,null); } //Transform relationship params. final Map<String, Object> properties = transFormToPropertyMap(tempStorage.getProperties(), ""); //Adds also params of start and end node. properties.putAll(transFormToPropertyMap(tempStorage.getStartNode().getProperties(), "1")); properties.putAll(transFormToPropertyMap(tempStorage.getEndNode().getProperties(), "2")); graphDb.execute(builder, properties); } catch (final Exception e) { Log.getLogger().warn("Couldn't execute create relationship transaction in server: " + id, e); return false; } Log.getLogger().info("Executed create relationship transaction in server: " + id); return true; } @Override public boolean applyDelete(final RelationshipStorage storage, final long snapshotId) { try { if(multiVersion) { final RelationshipStorage value = new RelationshipStorage(storage); value.addProperty(TAG_VERSION, -1); return applyUpdate(storage, value, snapshotId); } else { //Delete relationship final String cypher = MATCH + buildRelationshipString(storage) + " DELETE r"; //Transform relationship params. final Map<String, Object> properties = transFormToPropertyMap(storage.getProperties(), ""); //Adds also params of start and end node. properties.putAll(transFormToPropertyMap(storage.getStartNode().getProperties(), "1")); properties.putAll(transFormToPropertyMap(storage.getEndNode().getProperties(), "2")); graphDb.execute(cypher, properties); } } catch (final Exception e) { Log.getLogger().warn("Couldn't execute delete relationship transaction in server: " + id, e); return false; } Log.getLogger().info("Executed delete relationship transaction in server: " + id); return true; } @Override public boolean compareRelationship(final RelationshipStorage relationshipStorage) { final String builder = MATCH + buildRelationshipString(relationshipStorage) + " RETURN r"; //Contains params of relationshipStorage. final Map<String, Object> properties = transFormToPropertyMap(relationshipStorage.getProperties(), ""); //Adds also params of start and end node. properties.putAll(transFormToPropertyMap(relationshipStorage.getStartNode().getProperties(), "1")); properties.putAll(transFormToPropertyMap(relationshipStorage.getEndNode().getProperties(), "2")); final Result result = graphDb.execute(builder, properties); //Assuming we only get one node in return. if (result.hasNext()) { final Map<String, Object> value = result.next(); for (final Map.Entry<String, Object> entry : value.entrySet()) { if (entry.getValue() instanceof NodeProxy) { final NodeProxy n = (NodeProxy) entry.getValue(); try { return HashCreator.sha1FromRelationship(relationshipStorage).equals(n.getProperty(Constants.TAG_HASH)); } catch (final NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't execute SHA1 for relationship", e); } break; } } } return false; } /** * Registers a shutdown hook for the Neo4j instance so that it * shuts down nicely when the VM exits (even if you "Ctrl-C" the * running application). * * @param graphDb the graphDB to register the shutDownHook to. */ private static void registerShutdownHook(final GraphDatabaseService graphDb) { Runtime.getRuntime().addShutdownHook(new Thread(() -> { Log.getLogger().info("Shutting down Neo4j."); graphDb.shutdown(); })); } }
package mcjty.rftools.blocks.builder; import com.mojang.authlib.GameProfile; import mcjty.lib.container.*; import mcjty.lib.entity.GenericEnergyReceiverTileEntity; import mcjty.lib.network.Argument; import mcjty.lib.network.Arguments; import mcjty.lib.network.PacketRequestIntegerFromServer; import mcjty.lib.varia.*; import mcjty.rftools.ClientCommandHandler; import mcjty.rftools.RFTools; import mcjty.rftools.blocks.teleporter.TeleportationTools; import mcjty.rftools.hud.IHudSupport; import mcjty.rftools.items.builder.ShapeCardItem; import mcjty.rftools.items.builder.ShapeCardType; import mcjty.rftools.items.storage.StorageFilterCache; import mcjty.rftools.items.storage.StorageFilterItem; import mcjty.rftools.network.PacketGetHudLog; import mcjty.rftools.network.RFToolsMessages; import mcjty.rftools.proxy.CommonProxy; import mcjty.rftools.shapes.Shape; import mcjty.rftools.varia.RFToolsTools; import mcjty.theoneprobe.api.IProbeHitData; import mcjty.theoneprobe.api.IProbeInfo; import mcjty.theoneprobe.api.ProbeMode; import mcjty.typed.Type; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.BlockShulkerBox; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.item.*; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityShulkerBox; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.IPlantable; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.FakePlayerFactory; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.fluids.BlockFluidBase; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.fml.common.Optional; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.util.*; public class BuilderTileEntity extends GenericEnergyReceiverTileEntity implements DefaultSidedInventory, ITickable, IHudSupport { public static final String COMPONENT_NAME = "builder"; public static final String CMD_SETMODE = "setMode"; public static final String CMD_SETANCHOR = "setAnchor"; public static final String CMD_SETROTATE = "setRotate"; public static final String CMD_SETSILENT = "setSilent"; public static final String CMD_SETSUPPORT = "setSupport"; public static final String CMD_SETENTITIES = "setEntities"; public static final String CMD_SETWAIT = "setWait"; public static final String CMD_SETHILIGHT = "setHilight"; public static final String CMD_SETLOOP = "setLoop"; public static final String CMD_GETLEVEL = "getLevel"; public static final String CMD_SETRSMODE = "setRsMode"; public static final String CMD_RESTART = "restart"; public static final String CLIENTCMD_GETLEVEL = "getLevel"; public static final int SLOT_TAB = 0; public static final int SLOT_FILTER = 1; public static final ContainerFactory CONTAINER_FACTORY = new ContainerFactory(new ResourceLocation(RFTools.MODID, "gui/builder.gui")); // @Override // protected void setup() { // addSlotBox(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, // new ItemStack(BuilderSetup.spaceChamberCardItem), // new ItemStack(BuilderSetup.shapeCardItem)), // ContainerFactory.CONTAINER_CONTAINER, SLOT_TAB, 100, 10, 1, 18, 1, 18); // addSlot(new SlotDefinition(SlotType.SLOT_SPECIFICITEM, StorageFilterItem.class), ContainerFactory.CONTAINER_CONTAINER, SLOT_FILTER, 84, 46); // layoutPlayerInventorySlots(10, 70); public static final ModuleSupport MODULE_SUPPORT = new ModuleSupport(SLOT_TAB) { @Override public boolean isModule(ItemStack itemStack) { return (itemStack.getItem() == BuilderSetup.shapeCardItem || itemStack.getItem() == BuilderSetup.spaceChamberCardItem); } }; private InventoryHelper inventoryHelper = new InventoryHelper(this, CONTAINER_FACTORY, 2); public static final int MODE_COPY = 0; public static final int MODE_MOVE = 1; public static final int MODE_SWAP = 2; public static final int MODE_BACK = 3; public static final int MODE_COLLECT = 4; public static final String[] MODES = new String[]{"Copy", "Move", "Swap", "Back", "Collect"}; public static final String ROTATE_0 = "0"; public static final String ROTATE_90 = "90"; public static final String ROTATE_180 = "180"; public static final String ROTATE_270 = "270"; public static final int ANCHOR_SW = 0; public static final int ANCHOR_SE = 1; public static final int ANCHOR_NW = 2; public static final int ANCHOR_NE = 3; private String lastError = null; private int mode = MODE_COPY; private int rotate = 0; private int anchor = ANCHOR_SW; private boolean silent = false; private boolean supportMode = false; private boolean entityMode = false; private boolean loopMode = false; private boolean waitMode = true; private boolean hilightMode = false; // For usage in the gui private static int currentLevel = 0; // Client-side private int scanLocCnt = 0; private static Map<BlockPos, Pair<Long, BlockPos>> scanLocClient = new HashMap<>(); private int collectCounter = BuilderConfiguration.collectTimer; private int collectXP = 0; private boolean boxValid = false; private BlockPos minBox = null; private BlockPos maxBox = null; private BlockPos scan = null; private int projDx; private int projDy; private int projDz; private long lastHudTime = 0; private List<String> clientHudLog = new ArrayList<>(); private ShapeCardType cardType = ShapeCardType.CARD_UNKNOWN; private StorageFilterCache filterCache = null; // For chunkloading with the quarry. private ForgeChunkManager.Ticket ticket = null; // The currently forced chunk. private ChunkPos forcedChunk = null; // Cached set of blocks that we need to build in shaped mode private Map<BlockPos, IBlockState> cachedBlocks = null; private ChunkPos cachedChunk = null; // For which chunk are the cachedBlocks valid // Cached set of blocks that we want to void with the quarry. private Set<Block> cachedVoidableBlocks = null; // Drops from a block that we broke but couldn't fit in an inventory private List<ItemStack> overflowItems = null; private static FakePlayer harvester = null; public BuilderTileEntity() { super(BuilderConfiguration.BUILDER_MAXENERGY, BuilderConfiguration.BUILDER_RECEIVEPERTICK); setRSMode(RedstoneMode.REDSTONE_ONREQUIRED); } @Override protected boolean needsRedstoneMode() { return true; } @Override protected boolean needsCustomInvWrapper() { return true; } public static FakePlayer getHarvester() { if (harvester == null) { harvester = FakePlayerFactory.get(DimensionManager.getWorld(0), new GameProfile(new UUID(111, 333), "rftools_builder")); } return harvester; } @Override public EnumFacing getBlockOrientation() { IBlockState state = world.getBlockState(pos); if (state.getBlock() == BuilderSetup.builderBlock) { return OrientationTools.getOrientationHoriz(state); } else { return null; } } @Override public boolean isBlockAboveAir() { return getWorld().isAirBlock(pos.up()); } @Override public List<String> getClientLog() { return clientHudLog; } public List<String> getHudLog() { List<String> list = new ArrayList<>(); list.add(TextFormatting.BLUE + "Mode:"); if (isShapeCard()) { getCardType().addHudLog(list, inventoryHelper); } else { list.add(" Space card: " + new String[]{"copy", "move", "swap", "back", "collect"}[mode]); } if (scan != null) { list.add(TextFormatting.BLUE + "Progress:"); list.add(" Y level: " + scan.getY()); int minChunkX = minBox.getX() >> 4; int minChunkZ = minBox.getZ() >> 4; int maxChunkX = maxBox.getX() >> 4; int maxChunkZ = maxBox.getZ() >> 4; int curX = scan.getX() >> 4; int curZ = scan.getZ() >> 4; int totChunks = (maxChunkX - minChunkX + 1) * (maxChunkZ - minChunkZ + 1); int curChunk = (curZ - minChunkZ) * (maxChunkX - minChunkX) + curX - minChunkX; list.add(" Chunk: " + curChunk + " of " + totChunks); } if (lastError != null && !lastError.isEmpty()) { String[] errors = StringUtils.split(lastError, "\n"); for (String error : errors) { list.add(TextFormatting.RED + error); } } return list; } @Override public BlockPos getBlockPos() { return getPos(); } @Override public long getLastUpdateTime() { return lastHudTime; } @Override public void setLastUpdateTime(long t) { lastHudTime = t; } private boolean isShapeCard() { ItemStack itemStack = inventoryHelper.getStackInSlot(SLOT_TAB); if (itemStack.isEmpty()) { return false; } return itemStack.getItem() == BuilderSetup.shapeCardItem; } private NBTTagCompound hasCard() { ItemStack itemStack = inventoryHelper.getStackInSlot(SLOT_TAB); if (itemStack.isEmpty()) { return null; } return itemStack.getTagCompound(); } private void makeSupportBlocksShaped() { ItemStack shapeCard = inventoryHelper.getStackInSlot(SLOT_TAB); BlockPos dimension = ShapeCardItem.getClampedDimension(shapeCard, BuilderConfiguration.maxBuilderDimension); BlockPos offset = ShapeCardItem.getClampedOffset(shapeCard, BuilderConfiguration.maxBuilderOffset); Shape shape = ShapeCardItem.getShape(shapeCard); Map<BlockPos, IBlockState> blocks = new HashMap<>(); ShapeCardItem.composeFormula(shapeCard, shape.getFormulaFactory().get(), getWorld(), getPos(), dimension, offset, blocks, BuilderConfiguration.maxBuilderDimension * 256 * BuilderConfiguration.maxBuilderDimension, false, false, null); for (Map.Entry<BlockPos, IBlockState> entry : blocks.entrySet()) { BlockPos p = entry.getKey(); if (getWorld().isAirBlock(p)) { getWorld().setBlockState(p, BuilderSetup.supportBlock.getDefaultState().withProperty(SupportBlock.STATUS, SupportBlock.STATUS_OK), 3); } } } private void makeSupportBlocks() { if (isShapeCard()) { makeSupportBlocksShaped(); return; } SpaceChamberRepository.SpaceChamberChannel chamberChannel = calculateBox(); if (chamberChannel != null) { int dimension = chamberChannel.getDimension(); World world = DimensionManager.getWorld(dimension); if (world == null) { return; } BlockPos.MutableBlockPos src = new BlockPos.MutableBlockPos(); BlockPos.MutableBlockPos dest = new BlockPos.MutableBlockPos(); for (int x = minBox.getX(); x <= maxBox.getX(); x++) { for (int y = minBox.getY(); y <= maxBox.getY(); y++) { for (int z = minBox.getZ(); z <= maxBox.getZ(); z++) { src.setPos(x, y, z); sourceToDest(src, dest); IBlockState srcState = world.getBlockState(src); Block srcBlock = srcState.getBlock(); IBlockState dstState = world.getBlockState(dest); Block dstBlock = dstState.getBlock(); int error = SupportBlock.STATUS_OK; if (mode != MODE_COPY) { TileEntity srcTileEntity = world.getTileEntity(src); TileEntity dstTileEntity = getWorld().getTileEntity(dest); int error1 = isMovable(world, src, srcBlock, srcTileEntity); int error2 = isMovable(getWorld(), dest, dstBlock, dstTileEntity); error = Math.max(error1, error2); } if (isEmpty(srcState, srcBlock) && !isEmpty(dstState, dstBlock)) { getWorld().setBlockState(src, BuilderSetup.supportBlock.getDefaultState().withProperty(SupportBlock.STATUS, error), 3); } if (isEmpty(dstState, dstBlock) && !isEmpty(srcState, srcBlock)) { getWorld().setBlockState(dest, BuilderSetup.supportBlock.getDefaultState().withProperty(SupportBlock.STATUS, error), 3); } } } } } } private void clearSupportBlocksShaped() { ItemStack shapeCard = inventoryHelper.getStackInSlot(SLOT_TAB); BlockPos dimension = ShapeCardItem.getClampedDimension(shapeCard, BuilderConfiguration.maxBuilderDimension); BlockPos offset = ShapeCardItem.getClampedOffset(shapeCard, BuilderConfiguration.maxBuilderOffset); Shape shape = ShapeCardItem.getShape(shapeCard); Map<BlockPos, IBlockState> blocks = new HashMap<>(); ShapeCardItem.composeFormula(shapeCard, shape.getFormulaFactory().get(), getWorld(), getPos(), dimension, offset, blocks, BuilderConfiguration.maxSpaceChamberDimension * BuilderConfiguration.maxSpaceChamberDimension * BuilderConfiguration.maxSpaceChamberDimension, false, false, null); for (Map.Entry<BlockPos, IBlockState> entry : blocks.entrySet()) { BlockPos block = entry.getKey(); if (getWorld().getBlockState(block).getBlock() == BuilderSetup.supportBlock) { getWorld().setBlockToAir(block); } } } public void clearSupportBlocks() { if (getWorld().isRemote) { // Don't do anything on the client. return; } if (isShapeCard()) { clearSupportBlocksShaped(); return; } SpaceChamberRepository.SpaceChamberChannel chamberChannel = calculateBox(); if (chamberChannel != null) { int dimension = chamberChannel.getDimension(); World world = DimensionManager.getWorld(dimension); BlockPos.MutableBlockPos src = new BlockPos.MutableBlockPos(); BlockPos.MutableBlockPos dest = new BlockPos.MutableBlockPos(); for (int x = minBox.getX(); x <= maxBox.getX(); x++) { for (int y = minBox.getY(); y <= maxBox.getY(); y++) { for (int z = minBox.getZ(); z <= maxBox.getZ(); z++) { src.setPos(x, y, z); if (world != null) { Block srcBlock = world.getBlockState(src).getBlock(); if (srcBlock == BuilderSetup.supportBlock) { world.setBlockToAir(src); } } sourceToDest(src, dest); Block dstBlock = getWorld().getBlockState(dest).getBlock(); if (dstBlock == BuilderSetup.supportBlock) { getWorld().setBlockToAir(dest); } } } } } } public boolean isHilightMode() { return hilightMode; } public void setHilightMode(boolean hilightMode) { this.hilightMode = hilightMode; } public boolean isWaitMode() { return waitMode; } public void setWaitMode(boolean waitMode) { this.waitMode = waitMode; markDirtyClient(); } private boolean waitOrSkip(String error) { if (waitMode) { lastError = error; } return waitMode; } private boolean skip() { lastError = null; return false; } public boolean suspend(int rfNeeded, BlockPos srcPos, IBlockState srcState, IBlockState pickState) { lastError = null; return true; } private boolean suspend(String error) { lastError = error; return true; } public boolean hasLoopMode() { return loopMode; } public void setLoopMode(boolean loopMode) { this.loopMode = loopMode; markDirtyClient(); } public boolean hasEntityMode() { return entityMode; } public void setEntityMode(boolean entityMode) { this.entityMode = entityMode; markDirtyClient(); } public boolean hasSupportMode() { return supportMode; } public void setSupportMode(boolean supportMode) { this.supportMode = supportMode; if (supportMode) { makeSupportBlocks(); } else { clearSupportBlocks(); } markDirtyClient(); } public boolean isSilent() { return silent; } public void setSilent(boolean silent) { this.silent = silent; markDirtyClient(); } public int getMode() { return mode; } public void setMode(int mode) { if (mode != this.mode) { this.mode = mode; restartScan(); markDirtyClient(); } } public void resetBox() { boxValid = false; } public int getAnchor() { return anchor; } public void setAnchor(int anchor) { if (supportMode) { clearSupportBlocks(); } boxValid = false; this.anchor = anchor; if (isShapeCard()) { // If there is a shape card we modify it for the new settings. ItemStack shapeCard = inventoryHelper.getStackInSlot(SLOT_TAB); BlockPos dimension = ShapeCardItem.getDimension(shapeCard); BlockPos minBox = positionBox(dimension); int dx = dimension.getX(); int dy = dimension.getY(); int dz = dimension.getZ(); BlockPos offset = new BlockPos(minBox.getX() + (int) Math.ceil(dx / 2), minBox.getY() + (int) Math.ceil(dy / 2), minBox.getZ() + (int) Math.ceil(dz / 2)); ShapeCardItem.setOffset(shapeCard, offset.getX(), offset.getY(), offset.getZ()); } if (supportMode) { makeSupportBlocks(); } markDirtyClient(); } // Give a dimension, return a min coordinate of the box right in front of the builder private BlockPos positionBox(BlockPos dimension) { IBlockState state = getWorld().getBlockState(getPos()); EnumFacing direction = state.getValue(BaseBlock.FACING_HORIZ); int spanX = dimension.getX(); int spanY = dimension.getY(); int spanZ = dimension.getZ(); int x = 0; int y; int z = 0; y = -((anchor == ANCHOR_NE || anchor == ANCHOR_NW) ? spanY - 1 : 0); switch (direction) { case SOUTH: x = -((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? spanX - 1 : 0); z = -spanZ; break; case NORTH: x = 1 - spanX + ((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? spanX - 1 : 0); z = 1; break; case WEST: x = 1; z = -((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? spanZ - 1 : 0); break; case EAST: x = -spanX; z = -((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? 0 : spanZ - 1); break; case DOWN: case UP: default: break; } return new BlockPos(x, y, z); } public int getRotate() { return rotate; } public void setRotate(int rotate) { if (supportMode) { clearSupportBlocks(); } boxValid = false; this.rotate = rotate; if (supportMode) { makeSupportBlocks(); } markDirtyClient(); } @Override public void setPowerInput(int powered) { boolean o = isMachineEnabled(); super.setPowerInput(powered); boolean n = isMachineEnabled(); if (o != n) { if (loopMode || (n && scan == null)) { restartScan(); } } } private void createProjection(SpaceChamberRepository.SpaceChamberChannel chamberChannel) { BlockPos minC = rotate(chamberChannel.getMinCorner()); BlockPos maxC = rotate(chamberChannel.getMaxCorner()); BlockPos minCorner = new BlockPos(Math.min(minC.getX(), maxC.getX()), Math.min(minC.getY(), maxC.getY()), Math.min(minC.getZ(), maxC.getZ())); BlockPos maxCorner = new BlockPos(Math.max(minC.getX(), maxC.getX()), Math.max(minC.getY(), maxC.getY()), Math.max(minC.getZ(), maxC.getZ())); IBlockState state = getWorld().getBlockState(getPos()); EnumFacing direction = state.getValue(BaseBlock.FACING_HORIZ); int xCoord = getPos().getX(); int yCoord = getPos().getY(); int zCoord = getPos().getZ(); int spanX = maxCorner.getX() - minCorner.getX(); int spanY = maxCorner.getY() - minCorner.getY(); int spanZ = maxCorner.getZ() - minCorner.getZ(); switch (direction) { case SOUTH: projDx = xCoord + EnumFacing.NORTH.getDirectionVec().getX() - minCorner.getX() - ((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? spanX : 0); projDz = zCoord + EnumFacing.NORTH.getDirectionVec().getZ() - minCorner.getZ() - spanZ; break; case NORTH: projDx = xCoord + EnumFacing.SOUTH.getDirectionVec().getX() - minCorner.getX() - spanX + ((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? spanX : 0); projDz = zCoord + EnumFacing.SOUTH.getDirectionVec().getZ() - minCorner.getZ(); break; case WEST: projDx = xCoord + EnumFacing.EAST.getDirectionVec().getX() - minCorner.getX(); projDz = zCoord + EnumFacing.EAST.getDirectionVec().getZ() - minCorner.getZ() - ((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? spanZ : 0); break; case EAST: projDx = xCoord + EnumFacing.WEST.getDirectionVec().getX() - minCorner.getX() - spanX; projDz = zCoord + EnumFacing.WEST.getDirectionVec().getZ() - minCorner.getZ() - spanZ + ((anchor == ANCHOR_NE || anchor == ANCHOR_SE) ? spanZ : 0); break; case DOWN: case UP: default: break; } projDy = yCoord - minCorner.getY() - ((anchor == ANCHOR_NE || anchor == ANCHOR_NW) ? spanY : 0); } private void calculateBox(NBTTagCompound cardCompound) { int channel = cardCompound.getInteger("channel"); SpaceChamberRepository repository = SpaceChamberRepository.getChannels(getWorld()); SpaceChamberRepository.SpaceChamberChannel chamberChannel = repository.getChannel(channel); BlockPos minCorner = chamberChannel.getMinCorner(); BlockPos maxCorner = chamberChannel.getMaxCorner(); if (minCorner == null || maxCorner == null) { return; } if (boxValid) { // Double check if the box is indeed still valid. if (minCorner.equals(minBox) && maxCorner.equals(maxBox)) { return; } } boxValid = true; cardType = ShapeCardType.CARD_SPACE; createProjection(chamberChannel); minBox = minCorner; maxBox = maxCorner; restartScan(); } private void checkStateServerShaped() { float factor = getInfusedFactor(); for (int i = 0; i < BuilderConfiguration.quarryBaseSpeed + (factor * BuilderConfiguration.quarryInfusionSpeedFactor); i++) { if (scan != null) { handleBlockShaped(); } } } @Override public InventoryHelper getInventoryHelper() { return inventoryHelper; } @Override public void update() { if (!getWorld().isRemote) { checkStateServer(); } } private void checkStateServer() { if (overflowItems != null && insertItems(overflowItems)) { overflowItems = null; } if (!isMachineEnabled() && loopMode) { return; } if (scan == null) { return; } if (isHilightMode()) { updateHilight(); } if (isShapeCard()) { if (!isMachineEnabled()) { chunkUnload(); return; } checkStateServerShaped(); return; } SpaceChamberRepository.SpaceChamberChannel chamberChannel = calculateBox(); if (chamberChannel == null) { scan = null; markDirty(); return; } int dimension = chamberChannel.getDimension(); World world = DimensionManager.getWorld(dimension); if (world == null) { // The other location must be loaded. return; } if (mode == MODE_COLLECT) { collectItems(world); } else { float factor = getInfusedFactor(); for (int i = 0; i < 2 + (factor * 40); i++) { if (scan != null) { handleBlock(world); } } } } public List<ItemStack> getOverflowItems() { return overflowItems; } private void updateHilight() { scanLocCnt if (scanLocCnt <= 0) { scanLocCnt = 5; int x = scan.getX(); int y = scan.getY(); int z = scan.getZ(); double sqradius = 30 * 30; for (EntityPlayerMP player : getWorld().getMinecraftServer().getPlayerList().getPlayers()) { if (player.dimension == getWorld().provider.getDimension()) { double d0 = x - player.posX; double d1 = y - player.posY; double d2 = z - player.posZ; if (d0 * d0 + d1 * d1 + d2 * d2 < sqradius) { RFToolsMessages.sendToClient(player, ClientCommandHandler.CMD_POSITION_TO_CLIENT, Arguments.builder().value(getPos()).value(scan)); } } } } } private void collectItems(World world) { // Collect item mode collectCounter if (collectCounter > 0) { return; } collectCounter = BuilderConfiguration.collectTimer; if (!loopMode) { scan = null; } int rf = getEnergyStored(); float area = (maxBox.getX() - minBox.getX() + 1) * (maxBox.getY() - minBox.getY() + 1) * (maxBox.getZ() - minBox.getZ() + 1); float infusedFactor = (4.0f - getInfusedFactor()) / 4.0f; int rfNeeded = (int) (BuilderConfiguration.collectRFPerTickPerArea * area * infusedFactor) * BuilderConfiguration.collectTimer; if (rfNeeded > rf) { // Not enough energy. return; } consumeEnergy(rfNeeded); AxisAlignedBB bb = new AxisAlignedBB(minBox.getX() - .8, minBox.getY() - .8, minBox.getZ() - .8, maxBox.getX() + .8, maxBox.getY() + .8, maxBox.getZ() + .8); List<Entity> items = world.getEntitiesWithinAABB(Entity.class, bb); for (Entity entity : items) { if (entity instanceof EntityItem) { if (collectItem(world, infusedFactor, (EntityItem) entity)) { return; } } else if (entity instanceof EntityXPOrb) { if (collectXP(world, infusedFactor, (EntityXPOrb) entity)) { return; } } } } private boolean collectXP(World world, float infusedFactor, EntityXPOrb orb) { int rf; int rfNeeded; int xp = orb.getXpValue(); rf = getEnergyStored(); rfNeeded = (int) (BuilderConfiguration.collectRFPerXP * infusedFactor * xp); if (rfNeeded > rf) { // Not enough energy. return true; } collectXP += xp; int bottles = collectXP / 7; if (bottles > 0) { if (insertItem(new ItemStack(Items.EXPERIENCE_BOTTLE, bottles)).isEmpty()) { collectXP = collectXP % 7; world.removeEntity(orb); consumeEnergy(rfNeeded); } else { collectXP = 0; } } return false; } private boolean collectItem(World world, float infusedFactor, EntityItem item) { int rf; int rfNeeded; ItemStack stack = item.getItem(); rf = getEnergyStored(); rfNeeded = (int) (BuilderConfiguration.collectRFPerItem * infusedFactor) * stack.getCount(); if (rfNeeded > rf) { // Not enough energy. return true; } consumeEnergy(rfNeeded); world.removeEntity(item); stack = insertItem(stack); if (!stack.isEmpty()) { BlockPos position = item.getPosition(); EntityItem entityItem = new EntityItem(getWorld(), position.getX(), position.getY(), position.getZ(), stack); getWorld().spawnEntity(entityItem); } return false; } private void calculateBoxShaped() { ItemStack shapeCard = inventoryHelper.getStackInSlot(SLOT_TAB); if (shapeCard.isEmpty()) { return; } BlockPos dimension = ShapeCardItem.getClampedDimension(shapeCard, BuilderConfiguration.maxBuilderDimension); BlockPos offset = ShapeCardItem.getClampedOffset(shapeCard, BuilderConfiguration.maxBuilderOffset); BlockPos minCorner = ShapeCardItem.getMinCorner(getPos(), dimension, offset); BlockPos maxCorner = ShapeCardItem.getMaxCorner(getPos(), dimension, offset); if (minCorner.getY() < 0) { minCorner = new BlockPos(minCorner.getX(), 0, minCorner.getZ()); } else if (minCorner.getY() > 255) { minCorner = new BlockPos(minCorner.getX(), 255, minCorner.getZ()); } if (maxCorner.getY() < 0) { maxCorner = new BlockPos(maxCorner.getX(), 0, maxCorner.getZ()); } else if (maxCorner.getY() > 255) { maxCorner = new BlockPos(maxCorner.getX(), 255, maxCorner.getZ()); } if (boxValid) { // Double check if the box is indeed still valid. if (minCorner.equals(minBox) && maxCorner.equals(maxBox)) { return; } } boxValid = true; cardType = ShapeCardType.fromDamage(shapeCard.getItemDamage()); cachedBlocks = null; cachedChunk = null; cachedVoidableBlocks = null; minBox = minCorner; maxBox = maxCorner; restartScan(); } private SpaceChamberRepository.SpaceChamberChannel calculateBox() { NBTTagCompound tc = hasCard(); if (tc == null) { return null; } int channel = tc.getInteger("channel"); if (channel == -1) { return null; } SpaceChamberRepository repository = SpaceChamberRepository.getChannels(getWorld()); SpaceChamberRepository.SpaceChamberChannel chamberChannel = repository.getChannel(channel); if (chamberChannel == null) { return null; } calculateBox(tc); if (!boxValid) { return null; } return chamberChannel; } private Map<BlockPos, IBlockState> getCachedBlocks(ChunkPos chunk) { if ((chunk != null && !chunk.equals(cachedChunk)) || (chunk == null && cachedChunk != null)) { cachedBlocks = null; } if (cachedBlocks == null) { cachedBlocks = new HashMap<>(); ItemStack shapeCard = inventoryHelper.getStackInSlot(SLOT_TAB); Shape shape = ShapeCardItem.getShape(shapeCard); boolean solid = ShapeCardItem.isSolid(shapeCard); BlockPos dimension = ShapeCardItem.getClampedDimension(shapeCard, BuilderConfiguration.maxBuilderDimension); BlockPos offset = ShapeCardItem.getClampedOffset(shapeCard, BuilderConfiguration.maxBuilderOffset); boolean forquarry = !ShapeCardItem.isNormalShapeCard(shapeCard); ShapeCardItem.composeFormula(shapeCard, shape.getFormulaFactory().get(), getWorld(), getPos(), dimension, offset, cachedBlocks, BuilderConfiguration.maxSpaceChamberDimension * BuilderConfiguration.maxSpaceChamberDimension * BuilderConfiguration.maxSpaceChamberDimension, solid, forquarry, chunk); cachedChunk = chunk; } return cachedBlocks; } private void handleBlockShaped() { for (int i = 0; i < 100; i++) { if (scan == null) { return; } Map<BlockPos, IBlockState> blocks = getCachedBlocks(new ChunkPos(scan.getX() >> 4, scan.getZ() >> 4)); if (blocks.containsKey(scan)) { IBlockState state = blocks.get(scan); if (!handleSingleBlock(state)) { nextLocation(); } return; } else { nextLocation(); } } } private ShapeCardType getCardType() { if (cardType == ShapeCardType.CARD_UNKNOWN) { ItemStack card = inventoryHelper.getStackInSlot(SLOT_TAB); if (!card.isEmpty()) { cardType = ShapeCardType.fromDamage(card.getItemDamage()); } } return cardType; } // Return true if we have to wait at this spot. private boolean handleSingleBlock(IBlockState pickState) { BlockPos srcPos = scan; int sx = scan.getX(); int sy = scan.getY(); int sz = scan.getZ(); if (!chunkLoad(sx, sz)) { // The chunk is not available and we could not chunkload it. We have to wait. return suspend("Chunk not available!"); } int rfNeeded = getCardType().getRfNeeded(); IBlockState state = null; if (getCardType() != ShapeCardType.CARD_SHAPE && getCardType() != ShapeCardType.CARD_PUMP_LIQUID) { state = getWorld().getBlockState(srcPos); Block block = state.getBlock(); if (!isEmpty(state, block)) { float hardness; if (isFluidBlock(block)) { hardness = 1.0f; } else { if (getCachedVoidableBlocks().contains(block)) { rfNeeded = (int) (BuilderConfiguration.builderRfPerQuarry * BuilderConfiguration.voidShapeCardFactor); } hardness = block.getBlockHardness(state, getWorld(), srcPos); } rfNeeded *= (int) ((hardness + 1) * 2); } } rfNeeded = (int) (rfNeeded * (3.0f - getInfusedFactor()) / 3.0f); if (rfNeeded > getEnergyStored()) { // Not enough energy. return suspend("Not enough power!"); } return getCardType().handleSingleBlock(this, rfNeeded, srcPos, state, pickState); } public boolean buildBlock(int rfNeeded, BlockPos srcPos, IBlockState srcState, IBlockState pickState) { if (isEmptyOrReplacable(getWorld(), srcPos)) { TakeableItem item = createTakeableItem(getWorld(), srcPos, pickState); ItemStack stack = item.peek(); if (stack.isEmpty()) { return waitOrSkip("Cannot find block!\nor missing inventory\non top or below"); // We could not find a block. Wait } FakePlayer fakePlayer = getHarvester(); IBlockState newState = BlockTools.placeStackAt(fakePlayer, stack, getWorld(), srcPos, pickState); if (!ItemStack.areItemStacksEqual(stack, item.peek())) { // Did we actually use up whatever we were holding? if(!stack.isEmpty()) { // Are we holding something else that we should put back? stack = item.takeAndReplace(stack); // First try to put our new item where we got what we placed if(!stack.isEmpty()) { // If that didn't work, then try to put it anywhere it will fit stack = insertItem(stack); if(!stack.isEmpty()) { // If that still didn't work, then just drop whatever we're holding getWorld().spawnEntity(new EntityItem(getWorld(), getPos().getX(), getPos().getY(), getPos().getZ(), stack)); } } } else { item.take(); // If we aren't holding anything, then just consume what we placed } } if (!silent) { SoundTools.playSound(getWorld(), newState.getBlock().getSoundType(newState, getWorld(), srcPos, fakePlayer).getPlaceSound(), srcPos.getX(), srcPos.getY(), srcPos.getZ(), 1.0f, 1.0f); } consumeEnergy(rfNeeded); } return skip(); } private Set<Block> getCachedVoidableBlocks() { if (cachedVoidableBlocks == null) { ItemStack card = inventoryHelper.getStackInSlot(SLOT_TAB); if (!card.isEmpty() && card.getItem() == BuilderSetup.shapeCardItem) { cachedVoidableBlocks = ShapeCardItem.getVoidedBlocks(card); } else { cachedVoidableBlocks = Collections.emptySet(); } } return cachedVoidableBlocks; } private void clearOrDirtBlock(int rfNeeded, BlockPos spos, IBlockState srcState, boolean clear) { if (srcState.getBlock() instanceof BlockShulkerBox) { TileEntity te = world.getTileEntity(spos); if(te instanceof TileEntityShulkerBox) { ((TileEntityShulkerBox)te).clear(); // We already collected a drop before we called this. Clear to make sure setBlockState doesn't spawn another. } } if (clear) { getWorld().setBlockToAir(spos); } else { getWorld().setBlockState(spos, getReplacementBlock(), 2); // No block update! } consumeEnergy(rfNeeded); if (!silent) { SoundTools.playSound(getWorld(), srcState.getBlock().getSoundType(srcState, getWorld(), spos, null).getBreakSound(), spos.getX(), spos.getY(), spos.getZ(), 1.0f, 1.0f); } } private IBlockState getReplacementBlock() { return BuilderConfiguration.getQuarryReplace(); } public boolean silkQuarryBlock(int rfNeeded, BlockPos srcPos, IBlockState srcState, IBlockState pickState) { return commonQuarryBlock(true, rfNeeded, srcPos, srcState); } private void getFilterCache() { if (filterCache == null) { filterCache = StorageFilterItem.getCache(inventoryHelper.getStackInSlot(SLOT_FILTER)); } } public static boolean allowedToBreak(IBlockState state, World world, BlockPos pos, EntityPlayer entityPlayer) { if (!state.getBlock().canEntityDestroy(state, world, pos, entityPlayer)) { return false; } BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(world, pos, state, entityPlayer); MinecraftForge.EVENT_BUS.post(event); return !event.isCanceled(); } public boolean quarryBlock(int rfNeeded, BlockPos srcPos, IBlockState srcState, IBlockState pickState) { return commonQuarryBlock(false, rfNeeded, srcPos, srcState); } private boolean commonQuarryBlock(boolean silk, int rfNeeded, BlockPos srcPos, IBlockState srcState) { Block block = srcState.getBlock(); int xCoord = getPos().getX(); int yCoord = getPos().getY(); int zCoord = getPos().getZ(); int sx = srcPos.getX(); int sy = srcPos.getY(); int sz = srcPos.getZ(); if (sx >= xCoord - 1 && sx <= xCoord + 1 && sy >= yCoord - 1 && sy <= yCoord + 1 && sz >= zCoord - 1 && sz <= zCoord + 1) { // Skip a 3x3x3 block around the builder. return skip(); } if (isEmpty(srcState, block)) { return skip(); } if (block.getBlockHardness(srcState, getWorld(), srcPos) >= 0) { boolean clear = getCardType().isClearing(); if ((!clear) && srcState == getReplacementBlock()) { // We can skip dirt if we are not clearing. return skip(); } if ((!BuilderConfiguration.quarryTileEntities) && getWorld().getTileEntity(srcPos) != null) { // Skip tile entities return skip(); } FakePlayer fakePlayer = getHarvester(); if (allowedToBreak(srcState, getWorld(), srcPos, fakePlayer)) { ItemStack filter = getStackInSlot(SLOT_FILTER); if (!filter.isEmpty()) { getFilterCache(); if (filterCache != null) { boolean match = filterCache.match(block.getItem(getWorld(), srcPos, srcState)); if (!match) { consumeEnergy(Math.min(rfNeeded, BuilderConfiguration.builderRfPerSkipped)); return skip(); // Skip this } } } if (!getCachedVoidableBlocks().contains(block)) { if (overflowItems != null) { // Don't harvest any new blocks if we're still overflowing with the drops from a previous block return waitOrSkip("Not enough room!\nor no usable storage\non top or below!"); } List<ItemStack> drops; if(silk && block.canSilkHarvest(getWorld(), srcPos, srcState, fakePlayer)) { ItemStack drop; try { drop = (ItemStack) CommonProxy.Block_getSilkTouch.invoke(block, srcState); } catch (IllegalAccessException|InvocationTargetException e) { throw new RuntimeException(e); } drops = new ArrayList<>(); if (!drop.isEmpty()) { drops.add(drop); } net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(drops, getWorld(), srcPos, srcState, 0, 1.0f, true, fakePlayer); } else { int fortune = getCardType().isFortune() ? 3 : 0; if (block instanceof BlockShulkerBox) { // Shulker boxes drop in setBlockState, rather than anywhere sensible. Work around this. drops = new ArrayList<>(); TileEntity te = getWorld().getTileEntity(srcPos); if (te instanceof TileEntityShulkerBox) { TileEntityShulkerBox teShulkerBox = (TileEntityShulkerBox)te; ItemStack stack = new ItemStack(Item.getItemFromBlock(block)); teShulkerBox.saveToNbt(stack.getOrCreateSubCompound("BlockEntityTag")); if (teShulkerBox.hasCustomName()) { stack.setStackDisplayName(teShulkerBox.getName()); } drops.add(stack); } } else { drops = block.getDrops(getWorld(), srcPos, srcState, fortune); } net.minecraftforge.event.ForgeEventFactory.fireBlockHarvesting(drops, getWorld(), srcPos, srcState, fortune, 1.0f, false, fakePlayer); } if (checkValidItems(block, drops) && !insertItems(drops)) { overflowItems = drops; clearOrDirtBlock(rfNeeded, srcPos, srcState, clear); return waitOrSkip("Not enough room!\nor no usable storage\non top or below!"); // Not enough room. Wait } } clearOrDirtBlock(rfNeeded, srcPos, srcState, clear); } } return silk ? skip() : false; } private static boolean isFluidBlock(Block block) { return block instanceof BlockLiquid || block instanceof BlockFluidBase; } private static int getFluidLevel(IBlockState srcState) { if (srcState.getBlock() instanceof BlockLiquid) { return srcState.getValue(BlockLiquid.LEVEL); } if (srcState.getBlock() instanceof BlockFluidBase) { return srcState.getValue(BlockFluidBase.LEVEL); } return -1; } public boolean placeLiquidBlock(int rfNeeded, BlockPos srcPos, IBlockState srcState, IBlockState pickState) { if (isEmptyOrReplacable(getWorld(), srcPos)) { FluidStack stack = consumeLiquid(getWorld(), srcPos); if (stack == null) { return waitOrSkip("Cannot find liquid!\nor no usable tank\nabove or below"); // We could not find a block. Wait } Fluid fluid = stack.getFluid(); if (fluid.doesVaporize(stack) && getWorld().provider.doesWaterVaporize()) { fluid.vaporize(null, getWorld(), srcPos, stack); } else { // We assume here the liquid is placable. Block block = fluid.getBlock(); FakePlayer fakePlayer = getHarvester(); getWorld().setBlockState(srcPos, block.getDefaultState(), 11); if (!silent) { SoundTools.playSound(getWorld(), block.getSoundType(block.getDefaultState(), getWorld(), srcPos, fakePlayer).getPlaceSound(), srcPos.getX(), srcPos.getY(), srcPos.getZ(), 1.0f, 1.0f); } } consumeEnergy(rfNeeded); } return skip(); } public boolean pumpBlock(int rfNeeded, BlockPos srcPos, IBlockState srcState, IBlockState pickState) { Block block = srcState.getBlock(); Fluid fluid = FluidRegistry.lookupFluidForBlock(block); if (fluid == null) { return skip(); } if (!isFluidBlock(block)) { return skip(); } if (getFluidLevel(srcState) != 0) { return skip(); } if (block.getBlockHardness(srcState, getWorld(), srcPos) >= 0) { FakePlayer fakePlayer = getHarvester(); if (allowedToBreak(srcState, getWorld(), srcPos, fakePlayer)) { if (checkAndInsertFluids(fluid)) { consumeEnergy(rfNeeded); boolean clear = getCardType().isClearing(); if (clear) { getWorld().setBlockToAir(srcPos); } else { getWorld().setBlockState(srcPos, getReplacementBlock(), 2); // No block update! } if (!silent) { SoundTools.playSound(getWorld(), block.getSoundType(srcState, getWorld(), srcPos, fakePlayer).getBreakSound(), srcPos.getX(), srcPos.getY(), srcPos.getZ(), 1.0f, 1.0f); } return skip(); } return waitOrSkip("No room for liquid\nor no usable tank\nabove or below!"); // No room in tanks or not a valid tank: wait } } return skip(); } public boolean voidBlock(int rfNeeded, BlockPos srcPos, IBlockState srcState, IBlockState pickState) { Block block = srcState.getBlock(); int xCoord = getPos().getX(); int yCoord = getPos().getY(); int zCoord = getPos().getZ(); int sx = srcPos.getX(); int sy = srcPos.getY(); int sz = srcPos.getZ(); if (sx >= xCoord - 1 && sx <= xCoord + 1 && sy >= yCoord - 1 && sy <= yCoord + 1 && sz >= zCoord - 1 && sz <= zCoord + 1) { // Skip a 3x3x3 block around the builder. return skip(); } FakePlayer fakePlayer = getHarvester(); if (allowedToBreak(srcState, getWorld(), srcPos, fakePlayer)) { if (block.getBlockHardness(srcState, getWorld(), srcPos) >= 0) { ItemStack filter = getStackInSlot(SLOT_FILTER); if (!filter.isEmpty()) { getFilterCache(); if (filterCache != null) { boolean match = filterCache.match(block.getItem(getWorld(), srcPos, srcState)); if (!match) { consumeEnergy(Math.min(rfNeeded, BuilderConfiguration.builderRfPerSkipped)); return skip(); // Skip this } } } if (!silent) { SoundTools.playSound(getWorld(), block.getSoundType(srcState, getWorld(), srcPos, fakePlayer).getBreakSound(), sx, sy, sz, 1.0f, 1.0f); } getWorld().setBlockToAir(srcPos); consumeEnergy(rfNeeded); } } return skip(); } private void handleBlock(World world) { BlockPos srcPos = scan; BlockPos destPos = sourceToDest(scan); int x = scan.getX(); int y = scan.getY(); int z = scan.getZ(); int destX = destPos.getX(); int destY = destPos.getY(); int destZ = destPos.getZ(); switch (mode) { case MODE_COPY: copyBlock(world, srcPos, getWorld(), destPos); break; case MODE_MOVE: if (entityMode) { moveEntities(world, x, y, z, getWorld(), destX, destY, destZ); } moveBlock(world, srcPos, getWorld(), destPos, rotate); break; case MODE_BACK: if (entityMode) { moveEntities(getWorld(), destX, destY, destZ, world, x, y, z); } moveBlock(getWorld(), destPos, world, srcPos, oppositeRotate()); break; case MODE_SWAP: if (entityMode) { swapEntities(world, x, y, z, getWorld(), destX, destY, destZ); } swapBlock(world, srcPos, getWorld(), destPos); break; } nextLocation(); } private static Random random = new Random(); // Also works if block is null and just picks the first available block. private TakeableItem findBlockTakeableItem(IItemHandler inventory, World srcWorld, BlockPos srcPos, IBlockState state) { if (state == null) { // We are not looking for a specific block. Pick a random one out of the chest. List<Integer> slots = new ArrayList<>(); for (int i = 0; i < inventory.getSlots(); i++) { if (isPlacable(inventory.getStackInSlot(i))) { slots.add(i); } } if (!slots.isEmpty()) { return new TakeableItem(inventory, slots.get(random.nextInt(slots.size()))); } } else { Block block = state.getBlock(); ItemStack srcItem = block.getItem(srcWorld, srcPos, state); if (isPlacable(srcItem)) { for (int i = 0; i < inventory.getSlots(); i++) { ItemStack stack = inventory.getStackInSlot(i); if (!stack.isEmpty() && stack.isItemEqual(srcItem)) { return new TakeableItem(inventory, i); } } } } return TakeableItem.EMPTY; } private boolean isPlacable(ItemStack stack) { if (stack.isEmpty()) { return false; } Item item = stack.getItem(); return item instanceof ItemBlock || item instanceof ItemSkull || item instanceof ItemBlockSpecial || item instanceof IPlantable || item instanceof ItemRedstone; } // Also works if block is null and just picks the first available block. private TakeableItem findBlockTakeableItem(IInventory inventory, World srcWorld, BlockPos srcPos, IBlockState state) { if (state == null) { // We are not looking for a specific block. Pick a random one out of the chest. List<Integer> slots = new ArrayList<>(); for (int i = 0; i < inventory.getSizeInventory(); i++) { if (isPlacable(inventory.getStackInSlot(i))) { slots.add(i); } } if (!slots.isEmpty()) { return new TakeableItem(inventory, slots.get(random.nextInt(slots.size()))); } } else { Block block = state.getBlock(); ItemStack srcItem = block.getItem(srcWorld, srcPos, state); if(isPlacable(srcItem)) { for (int i = 0; i < inventory.getSizeInventory(); i++) { ItemStack stack = inventory.getStackInSlot(i); if (!stack.isEmpty() && stack.isItemEqual(srcItem)) { return new TakeableItem(inventory, i); } } } } return TakeableItem.EMPTY; } // To protect against mods doing bad things we have to check // the items that we try to insert. private boolean checkValidItems(Block block, List<ItemStack> items) { for (ItemStack stack : items) { if ((!stack.isEmpty()) && stack.getItem() == null) { Logging.logError("Builder tried to quarry " + block.getRegistryName().toString() + " and it returned null item!"); Broadcaster.broadcast(getWorld(), pos.getX(), pos.getY(), pos.getZ(), "Builder tried to quarry " + block.getRegistryName().toString() + " and it returned null item!\nPlease report to mod author!", 10); return false; // We don't wait for this. Just skip the item } } return true; } private boolean checkAndInsertFluids(Fluid fluid) { if (checkFluidTank(fluid, getPos().up(), EnumFacing.DOWN)) { return true; } if (checkFluidTank(fluid, getPos().down(), EnumFacing.UP)) { return true; } return false; } private boolean checkFluidTank(Fluid fluid, BlockPos up, EnumFacing side) { TileEntity te = getWorld().getTileEntity(up); if (te != null && te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side)) { IFluidHandler handler = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side); FluidStack fluidStack = new FluidStack(fluid, 1000); int amount = handler.fill(fluidStack, false); if (amount == 1000) { handler.fill(fluidStack, true); return true; } } return false; } private boolean insertItems(List<ItemStack> items) { TileEntity te = getWorld().getTileEntity(getPos().up()); boolean ok = InventoryHelper.insertItemsAtomic(items, te, EnumFacing.DOWN); if (!ok) { te = getWorld().getTileEntity(getPos().down()); ok = InventoryHelper.insertItemsAtomic(items, te, EnumFacing.UP); } return ok; } // Return what could not be inserted private ItemStack insertItem(ItemStack s) { s = InventoryHelper.insertItem(getWorld(), getPos(), EnumFacing.UP, s); if (!s.isEmpty()) { s = InventoryHelper.insertItem(getWorld(), getPos(), EnumFacing.DOWN, s); } return s; } private static class TakeableItem { private final IItemHandler itemHandler; private final IInventory inventory; private final int slot; private final ItemStack peekStack; public static final TakeableItem EMPTY = new TakeableItem(); private TakeableItem() { this.itemHandler = null; this.inventory = null; this.slot = -1; this.peekStack = ItemStack.EMPTY; } public TakeableItem(IItemHandler itemHandler, int slot) { Validate.inclusiveBetween(0, itemHandler.getSlots() - 1, slot); this.itemHandler = itemHandler; this.inventory = null; this.slot = slot; this.peekStack = itemHandler.extractItem(slot, 1, true); } public TakeableItem(IInventory inventory, int slot) { Validate.inclusiveBetween(0, inventory.getSizeInventory() - 1, slot); this.itemHandler = null; this.inventory = inventory; this.slot = slot; this.peekStack = inventory.getStackInSlot(slot).copy(); this.peekStack.setCount(1); } public ItemStack peek() { return peekStack.copy(); } public void take() { if(itemHandler != null) { itemHandler.extractItem(slot, 1, false); } else if(slot != -1) { inventory.decrStackSize(slot, 1); } } public ItemStack takeAndReplace(ItemStack replacement) { if(itemHandler != null) { itemHandler.extractItem(slot, 1, false); return itemHandler.insertItem(slot, replacement, false); } else if(slot != -1) { inventory.decrStackSize(slot, 1); if(inventory.isItemValidForSlot(slot, replacement) && inventory.getStackInSlot(slot).isEmpty()) { inventory.setInventorySlotContents(slot, replacement); return ItemStack.EMPTY; } } return replacement; } } /** * Create a way to let you consume a block out of an inventory. Returns a blockstate * from that inventory or else null if nothing could be found. * If the given blockstate parameter is null then a random block will be * returned. Otherwise the returned block has to match. */ private TakeableItem createTakeableItem(EnumFacing direction, World srcWorld, BlockPos srcPos, IBlockState state) { TileEntity te = getWorld().getTileEntity(getPos().offset(direction)); if (te != null) { if (te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, direction.getOpposite())) { IItemHandler capability = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, direction.getOpposite()); return findBlockTakeableItem(capability, srcWorld, srcPos, state); } else if (te instanceof IInventory) { return findBlockTakeableItem((IInventory) te, srcWorld, srcPos, state); } } return TakeableItem.EMPTY; } private FluidStack consumeLiquid(World srcWorld, BlockPos srcPos) { FluidStack b = consumeLiquid(EnumFacing.UP, srcWorld, srcPos); if (b == null) { b = consumeLiquid(EnumFacing.DOWN, srcWorld, srcPos); } return b; } private FluidStack consumeLiquid(EnumFacing direction, World srcWorld, BlockPos srcPos) { TileEntity te = getWorld().getTileEntity(getPos().offset(direction)); if (te != null) { if (te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, direction.getOpposite())) { IFluidHandler capability = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, direction.getOpposite()); return findAndConsumeLiquid(capability, srcWorld, srcPos); } if (te.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null)) { IFluidHandler capability = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null); return findAndConsumeLiquid(capability, srcWorld, srcPos); } } return null; } private FluidStack findAndConsumeLiquid(IFluidHandler tank, World srcWorld, BlockPos srcPos) { for (IFluidTankProperties properties : tank.getTankProperties()) { FluidStack contents = properties.getContents(); if (contents != null) { if (contents.getFluid() != null) { if (contents.amount >= 1000) { FluidStack drained = tank.drain(new FluidStack(contents.getFluid(), 1000, contents.tag), true); // System.out.println("drained = " + drained); return drained; } } } } return null; } private TakeableItem createTakeableItem(World srcWorld, BlockPos srcPos, IBlockState state) { TakeableItem b = createTakeableItem(EnumFacing.UP, srcWorld, srcPos, state); if (b.peek().isEmpty()) { b = createTakeableItem(EnumFacing.DOWN, srcWorld, srcPos, state); } return b; } public static BuilderSetup.BlockInformation getBlockInformation(World world, BlockPos pos, Block block, TileEntity tileEntity) { IBlockState state = world.getBlockState(pos); if (isEmpty(state, block)) { return BuilderSetup.BlockInformation.FREE; } FakePlayer fakePlayer = getHarvester(); if (!allowedToBreak(state, world, pos, fakePlayer)) { return BuilderSetup.BlockInformation.INVALID; } BuilderSetup.BlockInformation blockInformation = BuilderSetup.getBlockInformation(block); if (tileEntity != null) { switch (BuilderConfiguration.teMode) { case MOVE_FORBIDDEN: return BuilderSetup.BlockInformation.INVALID; case MOVE_WHITELIST: if (blockInformation == null || blockInformation.getBlockLevel() == SupportBlock.STATUS_ERROR) { return BuilderSetup.BlockInformation.INVALID; } break; case MOVE_BLACKLIST: if (blockInformation != null && blockInformation.getBlockLevel() == SupportBlock.STATUS_ERROR) { return BuilderSetup.BlockInformation.INVALID; } break; case MOVE_ALLOWED: break; } } if (blockInformation != null) { return blockInformation; } return BuilderSetup.BlockInformation.OK; } private int isMovable(World world, BlockPos pos, Block block, TileEntity tileEntity) { return getBlockInformation(world, pos, block, tileEntity).getBlockLevel(); } public static boolean isEmptyOrReplacable(World world, BlockPos pos) { IBlockState state = world.getBlockState(pos); Block block = state.getBlock(); if (block.isReplaceable(world, pos)) { return true; } return isEmpty(state, block); } // True if this block can just be overwritten (i.e. are or support block) public static boolean isEmpty(IBlockState state, Block block) { if (block == null) { return true; } if (block.getMaterial(state) == Material.AIR) { return true; } if (block == BuilderSetup.supportBlock) { return true; } return false; } private void clearBlock(World world, BlockPos pos) { if (supportMode) { world.setBlockState(pos, BuilderSetup.supportBlock.getDefaultState(), 3); } else { world.setBlockToAir(pos); } } private int oppositeRotate() { switch (rotate) { case 1: return 3; case 3: return 1; } return rotate; } private void copyBlock(World srcWorld, BlockPos srcPos, World destWorld, BlockPos destPos) { int rf = getEnergyStored(); int rfNeeded = (int) (BuilderConfiguration.builderRfPerOperation * getDimensionCostFactor(srcWorld, destWorld) * (4.0f - getInfusedFactor()) / 4.0f); if (rfNeeded > rf) { // Not enough energy. return; } if (isEmptyOrReplacable(destWorld, destPos)) { if (srcWorld.isAirBlock(srcPos)) { return; } IBlockState srcState = srcWorld.getBlockState(srcPos); TakeableItem takeableItem = createTakeableItem(srcWorld, srcPos, srcState); ItemStack consumedStack = takeableItem.peek(); if (consumedStack.isEmpty()) { return; } FakePlayer fakePlayer = getHarvester(); IBlockState newState = BlockTools.placeStackAt(fakePlayer, consumedStack, destWorld, destPos, srcState); destWorld.setBlockState(destPos, newState, 3); // placeBlockAt can reset the orientation. Restore it here if (!ItemStack.areItemStacksEqual(consumedStack, takeableItem.peek())) { // Did we actually use up whatever we were holding? if(!consumedStack.isEmpty()) { // Are we holding something else that we should put back? consumedStack = takeableItem.takeAndReplace(consumedStack); // First try to put our new item where we got what we placed if(!consumedStack.isEmpty()) { // If that didn't work, then try to put it anywhere it will fit consumedStack = insertItem(consumedStack); if(!consumedStack.isEmpty()) { // If that still didn't work, then just drop whatever we're holding getWorld().spawnEntity(new EntityItem(getWorld(), getPos().getX(), getPos().getY(), getPos().getZ(), consumedStack)); } } } else { takeableItem.take(); // If we aren't holding anything, then just consume what we placed } } if (!silent) { SoundTools.playSound(destWorld, newState.getBlock().getSoundType(newState, destWorld, destPos, fakePlayer).getPlaceSound(), destPos.getX(), destPos.getY(), destPos.getZ(), 1.0f, 1.0f); } consumeEnergy(rfNeeded); } } private double getDimensionCostFactor(World world, World destWorld) { return destWorld.provider.getDimension() == world.provider.getDimension() ? 1.0 : BuilderConfiguration.dimensionCostFactor; } private boolean consumeEntityEnergy(int rfNeeded, int rfNeededPlayer, Entity entity) { int rf = getEnergyStored(); int rfn; if (entity instanceof EntityPlayer) { rfn = rfNeededPlayer; } else { rfn = rfNeeded; } if (rfn > rf) { // Not enough energy. return true; } else { consumeEnergy(rfn); } return false; } private void moveEntities(World world, int x, int y, int z, World destWorld, int destX, int destY, int destZ) { int rfNeeded = (int) (BuilderConfiguration.builderRfPerEntity * getDimensionCostFactor(world, destWorld) * (4.0f - getInfusedFactor()) / 4.0f); int rfNeededPlayer = (int) (BuilderConfiguration.builderRfPerPlayer * getDimensionCostFactor(world, destWorld) * (4.0f - getInfusedFactor()) / 4.0f); // Check for entities. List<Entity> entities = world.getEntitiesWithinAABBExcludingEntity(null, new AxisAlignedBB(x - .1, y - .1, z - .1, x + 1.1, y + 1.1, z + 1.1)); for (Entity entity : entities) { if (consumeEntityEnergy(rfNeeded, rfNeededPlayer, entity)) { return; } double newX = destX + (entity.posX - x); double newY = destY + (entity.posY - y); double newZ = destZ + (entity.posZ - z); teleportEntity(world, destWorld, entity, newX, newY, newZ); } } private void swapEntities(World world, int x, int y, int z, World destWorld, int destX, int destY, int destZ) { int rfNeeded = (int) (BuilderConfiguration.builderRfPerEntity * getDimensionCostFactor(world, destWorld) * (4.0f - getInfusedFactor()) / 4.0f); int rfNeededPlayer = (int) (BuilderConfiguration.builderRfPerPlayer * getDimensionCostFactor(world, destWorld) * (4.0f - getInfusedFactor()) / 4.0f); // Check for entities. List<Entity> entitiesSrc = world.getEntitiesWithinAABBExcludingEntity(null, new AxisAlignedBB(x, y, z, x + 1, y + 1, z + 1)); List<Entity> entitiesDst = destWorld.getEntitiesWithinAABBExcludingEntity(null, new AxisAlignedBB(destX, destY, destZ, destX + 1, destY + 1, destZ + 1)); for (Entity entity : entitiesSrc) { if (isEntityInBlock(x, y, z, entity)) { if (consumeEntityEnergy(rfNeeded, rfNeededPlayer, entity)) { return; } double newX = destX + (entity.posX - x); double newY = destY + (entity.posY - y); double newZ = destZ + (entity.posZ - z); teleportEntity(world, destWorld, entity, newX, newY, newZ); } } for (Entity entity : entitiesDst) { if (isEntityInBlock(destX, destY, destZ, entity)) { if (consumeEntityEnergy(rfNeeded, rfNeededPlayer, entity)) { return; } double newX = x + (entity.posX - destX); double newY = y + (entity.posY - destY); double newZ = z + (entity.posZ - destZ); teleportEntity(destWorld, world, entity, newX, newY, newZ); } } } private void teleportEntity(World world, World destWorld, Entity entity, double newX, double newY, double newZ) { if (!TeleportationTools.allowTeleport(entity, world.provider.getDimension(), entity.getPosition(), destWorld.provider.getDimension(), new BlockPos(newX, newY, newZ))) { return; } mcjty.lib.varia.TeleportationTools.teleportEntity(entity, destWorld, newX, newY, newZ, null); } private boolean isEntityInBlock(int x, int y, int z, Entity entity) { if (entity.posX >= x && entity.posX < x + 1 && entity.posY >= y && entity.posY < y + 1 && entity.posZ >= z && entity.posZ < z + 1) { return true; } return false; } private void moveBlock(World srcWorld, BlockPos srcPos, World destWorld, BlockPos destPos, int rotMode) { IBlockState oldDestState = destWorld.getBlockState(destPos); Block oldDestBlock = oldDestState.getBlock(); if (isEmpty(oldDestState, oldDestBlock)) { IBlockState srcState = srcWorld.getBlockState(srcPos); Block srcBlock = srcState.getBlock(); if (isEmpty(srcState, srcBlock)) { return; } TileEntity srcTileEntity = srcWorld.getTileEntity(srcPos); BuilderSetup.BlockInformation srcInformation = getBlockInformation(srcWorld, srcPos, srcBlock, srcTileEntity); if (srcInformation.getBlockLevel() == SupportBlock.STATUS_ERROR) { return; } int rf = getEnergyStored(); int rfNeeded = (int) (BuilderConfiguration.builderRfPerOperation * getDimensionCostFactor(srcWorld, destWorld) * srcInformation.getCostFactor() * (4.0f - getInfusedFactor()) / 4.0f); if (rfNeeded > rf) { // Not enough energy. return; } else { consumeEnergy(rfNeeded); } NBTTagCompound tc = null; if (srcTileEntity != null) { tc = new NBTTagCompound(); srcTileEntity.writeToNBT(tc); srcWorld.removeTileEntity(srcPos); } clearBlock(srcWorld, srcPos); destWorld.setBlockState(destPos, srcState, 3); if (srcTileEntity != null && tc != null) { setTileEntityNBT(destWorld, tc, destPos, srcState); } if (!silent) { SoundTools.playSound(srcWorld, srcBlock.getSoundType(srcState, srcWorld, srcPos, null).getBreakSound(), srcPos.getX(), srcPos.getY(), srcPos.getZ(), 1.0f, 1.0f); SoundTools.playSound(destWorld, srcBlock.getSoundType(srcState, destWorld, destPos, null).getPlaceSound(), destPos.getX(), destPos.getY(), destPos.getZ(), 1.0f, 1.0f); } } } private void setTileEntityNBT(World destWorld, NBTTagCompound tc, BlockPos destpos, IBlockState newDestState) { tc.setInteger("x", destpos.getX()); tc.setInteger("y", destpos.getY()); tc.setInteger("z", destpos.getZ()); TileEntity tileEntity = TileEntity.create(destWorld, tc); if (tileEntity != null) { destWorld.getChunkFromBlockCoords(destpos).addTileEntity(tileEntity); tileEntity.markDirty(); destWorld.notifyBlockUpdate(destpos, newDestState, newDestState, 3); } } private void swapBlock(World srcWorld, BlockPos srcPos, World destWorld, BlockPos dstPos) { IBlockState oldSrcState = srcWorld.getBlockState(srcPos); Block srcBlock = oldSrcState.getBlock(); TileEntity srcTileEntity = srcWorld.getTileEntity(srcPos); IBlockState oldDstState = destWorld.getBlockState(dstPos); Block dstBlock = oldDstState.getBlock(); TileEntity dstTileEntity = destWorld.getTileEntity(dstPos); if (isEmpty(oldSrcState, srcBlock) && isEmpty(oldDstState, dstBlock)) { return; } BuilderSetup.BlockInformation srcInformation = getBlockInformation(srcWorld, srcPos, srcBlock, srcTileEntity); if (srcInformation.getBlockLevel() == SupportBlock.STATUS_ERROR) { return; } BuilderSetup.BlockInformation dstInformation = getBlockInformation(destWorld, dstPos, dstBlock, dstTileEntity); if (dstInformation.getBlockLevel() == SupportBlock.STATUS_ERROR) { return; } int rf = getEnergyStored(); int rfNeeded = (int) (BuilderConfiguration.builderRfPerOperation * getDimensionCostFactor(srcWorld, destWorld) * srcInformation.getCostFactor() * (4.0f - getInfusedFactor()) / 4.0f); rfNeeded += (int) (BuilderConfiguration.builderRfPerOperation * getDimensionCostFactor(srcWorld, destWorld) * dstInformation.getCostFactor() * (4.0f - getInfusedFactor()) / 4.0f); if (rfNeeded > rf) { // Not enough energy. return; } else { consumeEnergy(rfNeeded); } srcWorld.removeTileEntity(srcPos); srcWorld.setBlockToAir(srcPos); destWorld.removeTileEntity(dstPos); destWorld.setBlockToAir(dstPos); IBlockState newDstState = oldSrcState; destWorld.setBlockState(dstPos, newDstState, 3); // destWorld.setBlockMetadataWithNotify(destX, destY, destZ, srcMeta, 3); if (srcTileEntity != null) { srcTileEntity.validate(); destWorld.setTileEntity(dstPos, srcTileEntity); srcTileEntity.markDirty(); destWorld.notifyBlockUpdate(dstPos, newDstState, newDstState, 3); } IBlockState newSrcState = oldDstState; srcWorld.setBlockState(srcPos, newSrcState, 3); // world.setBlockMetadataWithNotify(x, y, z, dstMeta, 3); if (dstTileEntity != null) { dstTileEntity.validate(); srcWorld.setTileEntity(srcPos, dstTileEntity); dstTileEntity.markDirty(); srcWorld.notifyBlockUpdate(srcPos, newSrcState, newSrcState, 3); } if (!silent) { if (!isEmpty(oldSrcState, srcBlock)) { SoundTools.playSound(srcWorld, srcBlock.getSoundType(oldSrcState, srcWorld, srcPos, null).getBreakSound(), srcPos.getX(), srcPos.getY(), srcPos.getZ(), 1.0f, 1.0f); SoundTools.playSound(destWorld, srcBlock.getSoundType(oldSrcState, destWorld, dstPos, null).getPlaceSound(), dstPos.getX(), dstPos.getY(), dstPos.getZ(), 1.0f, 1.0f); } if (!isEmpty(oldDstState, dstBlock)) { SoundTools.playSound(destWorld, dstBlock.getSoundType(oldDstState, destWorld, dstPos, null).getBreakSound(), dstPos.getX(), dstPos.getY(), dstPos.getZ(), 1.0f, 1.0f); SoundTools.playSound(srcWorld, dstBlock.getSoundType(oldDstState, srcWorld, srcPos, null).getPlaceSound(), srcPos.getX(), srcPos.getY(), srcPos.getZ(), 1.0f, 1.0f); } } } private BlockPos sourceToDest(BlockPos source) { return rotate(source).add(projDx, projDy, projDz); } private BlockPos rotate(BlockPos c) { switch (rotate) { case 0: return c; case 1: return new BlockPos(-c.getZ(), c.getY(), c.getX()); case 2: return new BlockPos(-c.getX(), c.getY(), -c.getZ()); case 3: return new BlockPos(c.getZ(), c.getY(), -c.getX()); } return c; } private void sourceToDest(BlockPos source, BlockPos.MutableBlockPos dest) { rotate(source, dest); dest.setPos(dest.getX() + projDx, dest.getY() + projDy, dest.getZ() + projDz); } private void rotate(BlockPos c, BlockPos.MutableBlockPos dest) { switch (rotate) { case 0: dest.setPos(c); break; case 1: dest.setPos(-c.getZ(), c.getY(), c.getX()); break; case 2: dest.setPos(-c.getX(), c.getY(), -c.getZ()); break; case 3: dest.setPos(c.getZ(), c.getY(), -c.getX()); break; } } private void restartScan() { lastError = null; chunkUnload(); if (loopMode || (isMachineEnabled() && scan == null)) { if (getCardType() == ShapeCardType.CARD_SPACE) { calculateBox(); scan = minBox; } else if (getCardType() != ShapeCardType.CARD_UNKNOWN) { calculateBoxShaped(); // We start at the top for a quarry or shape building scan = new BlockPos(minBox.getX(), maxBox.getY(), minBox.getZ()); } cachedBlocks = null; cachedChunk = null; cachedVoidableBlocks = null; } else { scan = null; } } @Override public void invalidate() { super.invalidate(); chunkUnload(); } private void chunkUnload() { if (forcedChunk != null && ticket != null) { ForgeChunkManager.unforceChunk(ticket, forcedChunk); forcedChunk = null; } } private boolean chunkLoad(int x, int z) { int cx = x >> 4; int cz = z >> 4; if (RFToolsTools.chunkLoaded(getWorld(), new BlockPos(x, 0, z))) { return true; } if (BuilderConfiguration.quarryChunkloads) { if (ticket == null) { ticket = ForgeChunkManager.requestTicket(RFTools.instance, getWorld(), ForgeChunkManager.Type.NORMAL); if (ticket == null) { // Chunk is not loaded and we can't get a ticket. return false; } } ChunkPos pair = new ChunkPos(cx, cz); if (pair.equals(forcedChunk)) { return true; } if (forcedChunk != null) { ForgeChunkManager.unforceChunk(ticket, forcedChunk); } forcedChunk = pair; ForgeChunkManager.forceChunk(ticket, forcedChunk); return true; } // Chunk is not loaded and we don't do chunk loading so we cannot proceed. return false; } public static void setScanLocationClient(BlockPos tePos, BlockPos scanPos) { scanLocClient.put(tePos, Pair.of(System.currentTimeMillis(), scanPos)); } public static Map<BlockPos, Pair<Long, BlockPos>> getScanLocClient() { if (scanLocClient.isEmpty()) { return scanLocClient; } Map<BlockPos, Pair<Long, BlockPos>> scans = new HashMap<>(); long time = System.currentTimeMillis(); for (Map.Entry<BlockPos, Pair<Long, BlockPos>> entry : scanLocClient.entrySet()) { if (entry.getValue().getKey()+10000 > time) { scans.put(entry.getKey(), entry.getValue()); } } scanLocClient = scans; return scanLocClient; } private void nextLocation() { if (scan != null) { int x = scan.getX(); int y = scan.getY(); int z = scan.getZ(); if (getCardType() == ShapeCardType.CARD_SPACE) { nextLocationNormal(x, y, z); } else { nextLocationQuarry(x, y, z); } } } private void nextLocationQuarry(int x, int y, int z) { if (x >= maxBox.getX() || ((x + 1) % 16 == 0)) { if (z >= maxBox.getZ() || ((z + 1) % 16 == 0)) { if (y <= minBox.getY()) { if (x < maxBox.getX()) { x++; z = (z >> 4) << 4; y = maxBox.getY(); scan = new BlockPos(x, y, z); } else if (z < maxBox.getZ()) { x = minBox.getX(); z++; y = maxBox.getY(); scan = new BlockPos(x, y, z); } else { restartScan(); } } else { scan = new BlockPos((x >> 4) << 4, y - 1, (z >> 4) << 4); } } else { scan = new BlockPos((x >> 4) << 4, y, z + 1); } } else { scan = new BlockPos(x + 1, y, z); } } private void nextLocationNormal(int x, int y, int z) { if (x >= maxBox.getX()) { if (z >= maxBox.getZ()) { if (y >= maxBox.getY()) { if (mode != MODE_SWAP || isShapeCard()) { restartScan(); } else { // We don't restart in swap mode. scan = null; } } else { scan = new BlockPos(minBox.getX(), y + 1, minBox.getZ()); } } else { scan = new BlockPos(minBox.getX(), y, z + 1); } } else { scan = new BlockPos(x + 1, y, z); } } @Override public int[] getSlotsForFace(EnumFacing side) { return CONTAINER_FACTORY.getAccessibleSlots(); } @Override public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) { return CONTAINER_FACTORY.isInputSlot(index); } @Override public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) { return CONTAINER_FACTORY.isOutputSlot(index); } @Override public ItemStack decrStackSize(int index, int amount) { if (index == SLOT_TAB && !inventoryHelper.getStackInSlot(index).isEmpty() && amount > 0) { // Restart if we go from having a stack to not having stack or the other way around. refreshSettings(); } if (index == SLOT_FILTER) { filterCache = null; } return inventoryHelper.decrStackSize(index, amount); } @Override public void setInventorySlotContents(int index, ItemStack stack) { if (index == SLOT_TAB && ((stack.isEmpty() && !inventoryHelper.getStackInSlot(index).isEmpty()) || (!stack.isEmpty() && inventoryHelper.getStackInSlot(index).isEmpty()))) { // Restart if we go from having a stack to not having stack or the other way around. refreshSettings(); } if (index == SLOT_FILTER) { filterCache = null; } inventoryHelper.setInventorySlotContents(getInventoryStackLimit(), index, stack); } private void refreshSettings() { clearSupportBlocks(); cachedBlocks = null; cachedChunk = null; cachedVoidableBlocks = null; boxValid = false; scan = null; cardType = ShapeCardType.CARD_UNKNOWN; } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isEmpty() { return false; } @Override public boolean isUsableByPlayer(EntityPlayer player) { return canPlayerAccess(player); } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { return stack.getItem() == BuilderSetup.spaceChamberCardItem || stack.getItem() == BuilderSetup.shapeCardItem; } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); if(tagCompound.hasKey("overflowItems")) { NBTTagList overflowItemsNbt = tagCompound.getTagList("overflowItems", Constants.NBT.TAG_COMPOUND); overflowItems = new ArrayList<>(overflowItemsNbt.tagCount()); for(NBTBase overflowNbt : overflowItemsNbt) { overflowItems.add(new ItemStack((NBTTagCompound)overflowNbt)); } } } @Override public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); if(overflowItems != null) { NBTTagList overflowItemsNbt = new NBTTagList(); for(ItemStack overflow : overflowItems) { overflowItemsNbt.appendTag(overflow.writeToNBT(new NBTTagCompound())); } tagCompound.setTag("overflowItems", overflowItemsNbt); } return tagCompound; } @Override public void readRestorableFromNBT(NBTTagCompound tagCompound) { super.readRestorableFromNBT(tagCompound); // Workaround to get the redstone mode for old builders to default to 'on' if (!tagCompound.hasKey("rsMode")) { rsMode = RedstoneMode.REDSTONE_ONREQUIRED; } readBufferFromNBT(tagCompound, inventoryHelper); if (tagCompound.hasKey("lastError")) { lastError = tagCompound.getString("lastError"); } else { lastError = null; } mode = tagCompound.getInteger("mode"); anchor = tagCompound.getInteger("anchor"); rotate = tagCompound.getInteger("rotate"); silent = tagCompound.getBoolean("silent"); supportMode = tagCompound.getBoolean("support"); entityMode = tagCompound.getBoolean("entityMode"); loopMode = tagCompound.getBoolean("loopMode"); if (tagCompound.hasKey("waitMode")) { waitMode = tagCompound.getBoolean("waitMode"); } else { waitMode = true; } hilightMode = tagCompound.getBoolean("hilightMode"); scan = BlockPosTools.readFromNBT(tagCompound, "scan"); minBox = BlockPosTools.readFromNBT(tagCompound, "minBox"); maxBox = BlockPosTools.readFromNBT(tagCompound, "maxBox"); } @Override public void writeRestorableToNBT(NBTTagCompound tagCompound) { super.writeRestorableToNBT(tagCompound); writeBufferToNBT(tagCompound, inventoryHelper); if (lastError != null) { tagCompound.setString("lastError", lastError); } tagCompound.setInteger("mode", mode); tagCompound.setInteger("anchor", anchor); tagCompound.setInteger("rotate", rotate); tagCompound.setBoolean("silent", silent); tagCompound.setBoolean("support", supportMode); tagCompound.setBoolean("entityMode", entityMode); tagCompound.setBoolean("loopMode", loopMode); tagCompound.setBoolean("waitMode", waitMode); tagCompound.setBoolean("hilightMode", hilightMode); BlockPosTools.writeToNBT(tagCompound, "scan", scan); BlockPosTools.writeToNBT(tagCompound, "minBox", minBox); BlockPosTools.writeToNBT(tagCompound, "maxBox", maxBox); } // Request the current scan level. public void requestCurrentLevel() { RFToolsMessages.INSTANCE.sendToServer(new PacketRequestIntegerFromServer(RFTools.MODID, getPos(), CMD_GETLEVEL, CLIENTCMD_GETLEVEL)); } public static int getCurrentLevelClientSide() { return currentLevel; } public int getCurrentLevel() { return scan == null ? -1 : scan.getY(); } @Override public boolean execute(EntityPlayerMP playerMP, String command, Map<String, Argument> args) { boolean rc = super.execute(playerMP, command, args); if (rc) { return true; } if (CMD_SETRSMODE.equals(command)) { String m = args.get("rs").getString(); setRSMode(RedstoneMode.getMode(m)); return true; } else if (CMD_RESTART.equals(command)) { restartScan(); return true; } else if (CMD_SETMODE.equals(command)) { setMode(args.get("mode").getInteger()); return true; } else if (CMD_SETANCHOR.equals(command)) { setAnchor(args.get("anchor").getInteger()); return true; } else if (CMD_SETROTATE.equals(command)) { setRotate(args.get("rotate").getInteger()); return true; } else if (CMD_SETSILENT.equals(command)) { setSilent(args.get("silent").getBoolean()); return true; } else if (CMD_SETSUPPORT.equals(command)) { setSupportMode(args.get("support").getBoolean()); return true; } else if (CMD_SETENTITIES.equals(command)) { setEntityMode(args.get("entities").getBoolean()); return true; } else if (CMD_SETLOOP.equals(command)) { setLoopMode(args.get("loop").getBoolean()); return true; } else if (CMD_SETWAIT.equals(command)) { setWaitMode(args.get("wait").getBoolean()); return true; } else if (CMD_SETHILIGHT.equals(command)) { setHilightMode(args.get("hilight").getBoolean()); return true; } return false; } @Nonnull @Override public <T> List<T> executeWithResultList(String command, Map<String, Argument> args, Type<T> type) { List<T> rc = super.executeWithResultList(command, args, type); if (!rc.isEmpty()) { return rc; } if (PacketGetHudLog.CMD_GETHUDLOG.equals(command)) { return type.convert(getHudLog()); } return rc; } @Override public <T> boolean execute(String command, List<T> list, Type<T> type) { boolean rc = super.execute(command, list, type); if (rc) { return true; } if (PacketGetHudLog.CLIENTCMD_GETHUDLOG.equals(command)) { clientHudLog = Type.STRING.convert(list); return true; } return false; } @Override public Integer executeWithResultInteger(String command, Map<String, Argument> args) { Integer rc = super.executeWithResultInteger(command, args); if (rc != null) { return rc; } if (CMD_GETLEVEL.equals(command)) { return scan == null ? -1 : scan.getY(); } return null; } @Override public boolean execute(String command, Integer result) { boolean rc = super.execute(command, result); if (rc) { return true; } if (CLIENTCMD_GETLEVEL.equals(command)) { currentLevel = result; return true; } return false; } @Override public void onBlockBreak(World workd, BlockPos pos, IBlockState state) { if (hasSupportMode()) { clearSupportBlocks(); } } @SuppressWarnings("NullableProblems") @SideOnly(Side.CLIENT) @Override public AxisAlignedBB getRenderBoundingBox() { return new AxisAlignedBB(pos, pos.add(1, 2, 1)); } @Optional.Method(modid = "theoneprobe") @Override public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { super.addProbeInfo(mode, probeInfo, player, world, blockState, data); int scan = getCurrentLevel(); probeInfo.text(TextFormatting.GREEN + "Current level: " + (scan == -1 ? "not scanning" : scan)); } private static long lastTime = 0; @SideOnly(Side.CLIENT) @Override @Optional.Method(modid = "waila") public void addWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { super.addWailaBody(itemStack, currenttip, accessor, config); if (System.currentTimeMillis() - lastTime > 250) { lastTime = System.currentTimeMillis(); requestCurrentLevel(); } int scan = BuilderTileEntity.getCurrentLevelClientSide(); currenttip.add(TextFormatting.GREEN + "Current level: " + (scan == -1 ? "not scanning" : scan)); } @Override public void rotateBlock(EnumFacing axis) { super.rotateBlock(axis); if (!world.isRemote) { if (hasSupportMode()) { clearSupportBlocks(); resetBox(); } } } @Override public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState metadata, int fortune) { super.getDrops(drops, world, pos, metadata, fortune); List<ItemStack> overflowItems = getOverflowItems(); if(overflowItems != null) { drops.addAll(overflowItems); } } }
package net.pixelcop.sewer; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Properties; import net.pixelcop.sewer.node.AbstractNodeTest; import net.pixelcop.sewer.node.NodeConfig; import net.pixelcop.sewer.node.TestableNode; import net.pixelcop.sewer.sink.buffer.DisruptorSink; import net.pixelcop.sewer.source.debug.ThreadedEventGeneratorSource; import net.pixelcop.sewer.util.HdfsUtil; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.junit.Test; import org.junit.runner.JUnitCore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Benchmark extends AbstractNodeTest { class Result { double duration; double count; double opsPerSec; String source; String sink; String notes; @Override public String toString() { NumberFormat f = DecimalFormat.getIntegerInstance(); if (duration > 0) { return sink + "\t" + f.format(count) + "\t" + f.format(opsPerSec) + "\t\t" + notes; } return sink + "\t" + notes; } } private static final long TEST_WARMUP = 10000; private static final long TEST_DURATION = 30000; protected static final Logger LOG = LoggerFactory.getLogger(Benchmark.class); protected static final List<String> waitStrategies = new ArrayList<String>(); static { waitStrategies.add(DisruptorSink.WAIT_BLOCKING); waitStrategies.add(DisruptorSink.WAIT_BUSYSPIN); waitStrategies.add(DisruptorSink.WAIT_SLEEPING); waitStrategies.add(DisruptorSink.WAIT_TIMEOUT); waitStrategies.add(DisruptorSink.WAIT_YIELDING); } private String compressor = null; public static void main(String[] args) { JUnitCore.main(Benchmark.class.getName()); } @Test public void testPerf() throws InterruptedException, IOException { Properties props = new Properties(); props.setProperty(DisruptorSink.CONF_THREADS, "1"); props.setProperty(DisruptorSink.CONF_TIMEOUT_MS, "1"); String source = "tgen(256)"; List<Result> results = new ArrayList<Result>(); // null tests runAllTests(props, source, "null", results); // i/o tests List<Class<? extends CompressionCodec>> codecs = CompressionCodecFactory.getCodecClasses(loadTestConfig(false, "")); for (Class<? extends CompressionCodec> codec : codecs) { props.put(HdfsUtil.CONFIG_COMPRESSION, codec.getName()); compressor = codec.getSimpleName(); runAllTests(props, source, "seqfile('/tmp/sewer-bench')", results); } compressor = null; // print results NumberFormat f = DecimalFormat.getIntegerInstance(); System.err.println("\n\n\n\n\n\n"); System.err.println("sink\tmsgs\tops/sec\t\tnotes"); for (Result result : results) { System.err.println(result); } System.err.println("\n\n\n\n\n\n"); } private void runAllTests(Properties props, String source, String dest, List<Result> results) throws InterruptedException, IOException { // basic tests results.add(runTest(source, dest)); results.add(runTest(source, "buffer > " + dest)); // disruptor > null runDisruptorTests(props, source, "disruptor > " + dest, results); // meter before results.add(runTest(source, "meter > " + dest)); results.add(runTest(source, "meter > buffer > " + dest)); runDisruptorTests(props, source, "meter > disruptor > " + dest, results); // meter after results.add(runTest(source, "buffer > meter > " + dest)); runDisruptorTests(props, source, "disruptor > meter > " + dest, results); // meter before & after results.add(runTest(source, "meter > buffer > meter > " + dest)); runDisruptorTests(props, source, "meter > disruptor > meter > " + dest, results); } private void runDisruptorTests(Properties props, String source, String sink, List<Result> results) throws InterruptedException, IOException { for (String strat : waitStrategies) { props.setProperty(DisruptorSink.CONF_WAIT_STRATEGY, strat); results.add(runTest(source, sink, props, strat)); } } private Result runTest(String source, String sink) throws InterruptedException, IOException { return runTest(source, sink, null, ""); } private Result runTest(String source, String sink, Properties props, String notes) throws InterruptedException, IOException { // add compressor to notes if (compressor != null) { if (notes == null || notes.isEmpty()) { notes = "\t" + compressor; } else { notes = notes + "\t" + compressor; } } Result r = new Result(); r.source = source; r.sink = sink; r.notes = notes; System.out.println("running test: " + r); NodeConfig conf = loadTestConfig(false, ""); if (props != null) { conf.addResource(props); } TestableNode node = createNode(source, sink, null, conf); // start node, opens source node.start(); LOG.info("warming up..."); Thread.sleep(TEST_WARMUP); double startTime = System.nanoTime(); ((ThreadedEventGeneratorSource) node.getSource()).resetCounters(); Thread.sleep(TEST_DURATION); node.await(); node.cleanup(); r.count = ((ThreadedEventGeneratorSource) node.getSource()).getTotalCount(); r.duration = System.nanoTime() - startTime; r.opsPerSec = (1000L * 1000L * 1000L * r.count) / r.duration; System.gc(); // why not return r; } }
package mcjty.rftools.blocks.storage; import mcjty.container.GenericGuiContainer; import mcjty.gui.Window; import mcjty.gui.events.ButtonEvent; import mcjty.gui.events.ChoiceEvent; import mcjty.gui.events.TextEvent; import mcjty.gui.layout.HorizontalAlignment; import mcjty.gui.layout.HorizontalLayout; import mcjty.gui.layout.PositionalLayout; import mcjty.gui.widgets.*; import mcjty.gui.widgets.Button; import mcjty.gui.widgets.Label; import mcjty.gui.widgets.Panel; import mcjty.gui.widgets.TextField; import mcjty.rftools.RFTools; import mcjty.rftools.blocks.storage.modules.DefaultTypeModule; import mcjty.rftools.blocks.storage.modules.TypeModule; import mcjty.rftools.blocks.storage.sorters.ItemSorter; import mcjty.rftools.items.storage.StorageModuleItem; import mcjty.rftools.network.Argument; import mcjty.rftools.network.PacketHandler; import mcjty.rftools.network.PacketUpdateNBTItem; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.inventory.*; import net.minecraft.inventory.Container; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.lwjgl.input.Keyboard; import java.awt.*; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class GuiModularStorage extends GenericGuiContainer<ModularStorageTileEntity> { public static final int STORAGE_WIDTH = 256; public static final int STORAGE_HEIGHT0 = 236; public static final int STORAGE_HEIGHT1 = 320; public static final int STORAGE_HEIGHT2 = 490; public static final String VIEW_LIST = "list"; public static final String VIEW_COLUMNS = "columns"; public static final String VIEW_ICONS = "icons"; private TypeModule typeModule; private static final ResourceLocation iconLocationTop = new ResourceLocation(RFTools.MODID, "textures/gui/modularstorageTop.png"); private static final ResourceLocation iconLocation = new ResourceLocation(RFTools.MODID, "textures/gui/modularstorage.png"); private static final ResourceLocation guiElements = new ResourceLocation(RFTools.MODID, "textures/gui/guielements.png"); private WidgetList itemList; private Slider slider; private TextField filter; private ImageChoiceLabel viewMode; private ImageChoiceLabel sortMode; private ImageChoiceLabel groupMode; private Label amountLabel; private Button cycleButton; private Button compactButton; public GuiModularStorage(ModularStorageTileEntity modularStorageTileEntity, ModularStorageContainer container) { this(modularStorageTileEntity, (Container) container); } public GuiModularStorage(RemoteStorageItemContainer container) { this(null, container); } public GuiModularStorage(ModularStorageItemContainer container) { this(null, container); } public GuiModularStorage(ModularStorageTileEntity modularStorageTileEntity, Container container) { super(modularStorageTileEntity, container); xSize = STORAGE_WIDTH; int width = Minecraft.getMinecraft().displayWidth; int height = Minecraft.getMinecraft().displayHeight; ScaledResolution scaledresolution = new ScaledResolution(Minecraft.getMinecraft(), width, height); width = scaledresolution.getScaledWidth(); height = scaledresolution.getScaledHeight(); if (height > 510) { ySize = STORAGE_HEIGHT2; } else if (height > 340) { ySize = STORAGE_HEIGHT1; } else { ySize = STORAGE_HEIGHT0; } for (Object o : container.inventorySlots) { Slot slot = (Slot) o; slot.yDisplayPosition += ySize - STORAGE_HEIGHT0; } } @Override public void initGui() { super.initGui(); itemList = new WidgetList(mc, this).setLayoutHint(new PositionalLayout.PositionalHint(5, 3, 235, ySize-89)).setNoSelectionMode(true).setUserObject(new Integer(-1)). setFilledBackground(ModularStorageConfiguration.itemListBackground).setLeftMargin(0).setRowheight(-1); slider = new Slider(mc, this).setLayoutHint(new PositionalLayout.PositionalHint(241, 3, 11, ySize-89)).setDesiredWidth(11).setVertical().setScrollable(itemList); filter = new TextField(mc, this).setLayoutHint(new PositionalLayout.PositionalHint(8, ySize-79, 80, 12)).setTooltips("Name based filter for items").addTextEvent(new TextEvent() { @Override public void textChanged(Widget parent, String newText) { updateSettings(); } }); viewMode = new ImageChoiceLabel(mc, this).setLayoutHint(new PositionalLayout.PositionalHint(8, ySize-66, 16, 16)).setTooltips("Control how items are shown", "in the view").addChoiceEvent(new ChoiceEvent() { @Override public void choiceChanged(Widget parent, String newChoice) { updateSettings(); } }); viewMode.addChoice(VIEW_LIST, "Items are shown in a list view", guiElements, 9 * 16, 16); viewMode.addChoice(VIEW_COLUMNS, "Items are shown in columns", guiElements, 10 * 16, 16); viewMode.addChoice(VIEW_ICONS, "Items are shown with icons", guiElements, 11 * 16, 16); updateTypeModule(); sortMode = new ImageChoiceLabel(mc, this).setLayoutHint(new PositionalLayout.PositionalHint(28, ySize-66, 16, 16)).setTooltips("Control how items are sorted", "in the view").addChoiceEvent(new ChoiceEvent() { @Override public void choiceChanged(Widget parent, String newChoice) { updateSettings(); } }); for (ItemSorter sorter : typeModule.getSorters()) { sortMode.addChoice(sorter.getName(), sorter.getTooltip(), guiElements, sorter.getU(), sorter.getV()); } groupMode = new ImageChoiceLabel(mc, this).setLayoutHint(new PositionalLayout.PositionalHint(48, ySize-66, 16, 16)).setTooltips("If enabled it will show groups", "based on sorting criterium").addChoiceEvent(new ChoiceEvent() { @Override public void choiceChanged(Widget parent, String newChoice) { updateSettings(); } }); groupMode.addChoice("Off", "Don't show groups", guiElements, 13 * 16, 0); groupMode.addChoice("On", "Show groups", guiElements, 14 * 16, 0); amountLabel = new Label(mc, this); amountLabel.setHorizontalAlignment(HorizontalAlignment.ALIGH_LEFT); amountLabel.setLayoutHint(new PositionalLayout.PositionalHint(22, ySize-48, 66, 12)); amountLabel.setTooltips("Amount of stacks / maximum amount"); amountLabel.setText("? / ?"); compactButton = new Button(mc, this).setLayoutHint(new PositionalLayout.PositionalHint(8, ySize-48, 12, 12)).setText("z").setTooltips("Compact equal stacks").addButtonEvent(new ButtonEvent() { @Override public void buttonClicked(Widget parent) { compact(); } }); cycleButton = new Button(mc, this).setText("C").setTooltips("Cycle to the next storage module").setLayoutHint(new PositionalLayout.PositionalHint(66, ySize-66, 16, 16)). addButtonEvent(new ButtonEvent() { @Override public void buttonClicked(Widget parent) { cycleStorage(); } }); if (tileEntity != null) { filter.setText(tileEntity.getFilter()); setViewMode(tileEntity.getViewMode()); setSortMode(tileEntity.getSortMode()); groupMode.setCurrentChoice(tileEntity.isGroupMode() ? 1 : 0); } else { NBTTagCompound tagCompound = Minecraft.getMinecraft().thePlayer.getHeldItem().getTagCompound(); filter.setText(tagCompound.getString("filter")); setViewMode(tagCompound.getString("viewMode")); setSortMode(tagCompound.getString("sortMode")); groupMode.setCurrentChoice(tagCompound.getBoolean("groupMode") ? 1 : 0); } Panel toplevel = new Panel(mc, this).setLayout(new PositionalLayout()).addChild(itemList).addChild(slider).addChild(filter). addChild(viewMode).addChild(sortMode).addChild(groupMode).addChild(amountLabel).addChild(compactButton).addChild(cycleButton); toplevel.setBackgrounds(iconLocationTop, iconLocation); toplevel.setBackgroundLayout(false, ySize-STORAGE_HEIGHT0+2); if (tileEntity == null) { // We must hide two slots. ImageLabel hideLabel = new ImageLabel(mc, this); hideLabel.setLayoutHint(new PositionalLayout.PositionalHint(4, ySize-23, 62, 21)); hideLabel.setImage(guiElements, 32, 32); toplevel.addChild(hideLabel); } toplevel.setBounds(new Rectangle(guiLeft, guiTop, xSize, ySize)); window = new Window(this, toplevel); } private void setSortMode(String sortMode) { int idx; idx = this.sortMode.findChoice(sortMode); if (idx == -1) { this.sortMode.setCurrentChoice(0); } else { this.sortMode.setCurrentChoice(idx); } } private void setViewMode(String viewMode) { int idx = this.viewMode.findChoice(viewMode); if (idx == -1) { this.viewMode.setCurrentChoice(VIEW_LIST); } else { this.viewMode.setCurrentChoice(idx); } } private void cycleStorage() { if (tileEntity != null) { sendServerCommand(ModularStorageTileEntity.CMD_CYCLE); } else { PacketHandler.INSTANCE.sendToServer(new PacketCycleStorage()); } } private void compact() { if (tileEntity != null) { sendServerCommand(ModularStorageTileEntity.CMD_COMPACT); } else { PacketHandler.INSTANCE.sendToServer(new PacketCompact()); } } private void updateSettings() { if (tileEntity != null) { sendServerCommand(ModularStorageTileEntity.CMD_SETTINGS, new Argument("sortMode", sortMode.getCurrentChoice()), new Argument("viewMode", viewMode.getCurrentChoice()), new Argument("filter", filter.getText()), new Argument("groupMode", groupMode.getCurrentChoiceIndex() == 1)); } else { PacketHandler.INSTANCE.sendToServer(new PacketUpdateNBTItem( new Argument("sortMode", sortMode.getCurrentChoice()), new Argument("viewMode", viewMode.getCurrentChoice()), new Argument("filter", filter.getText()), new Argument("groupMode", groupMode.getCurrentChoiceIndex() == 1))); } } private Slot findEmptySlot() { for (Object slotObject : inventorySlots.inventorySlots) { Slot slot = (Slot) slotObject; // Skip the first two slots if we are on a modular storage block. if (tileEntity != null && slot.getSlotIndex() < ModularStorageContainer.SLOT_STORAGE) { continue; } if ((!slot.getHasStack()) || slot.getStack().stackSize == 0) { return slot; } } return null; } @Override public Slot getSlotAtPosition(int x, int y) { Widget widget = window.getToplevel().getWidgetAtPosition(x, y); if (widget != null) { Object userObject = widget.getUserObject(); if (userObject instanceof Integer) { Integer slotIndex = (Integer) userObject; if (slotIndex != -1) { return inventorySlots.getSlot(slotIndex); } else { return findEmptySlot(); } } } return super.getSlotAtPosition(x, y); } private void dumpClasses(String name, Object o) { RFTools.log(name + ":" + o.getClass().getCanonicalName()); Class<?>[] classes = o.getClass().getClasses(); for (Class<?> a : classes) { RFTools.log(" " + a.getCanonicalName()); } RFTools.log(" Super:" + o.getClass().getGenericSuperclass()); for (Type type : o.getClass().getGenericInterfaces()) { RFTools.log(" type:" + type.getClass().getCanonicalName()); } } @Override protected void mouseClicked(int x, int y, int button) { if (Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL)) { Slot slot = getSlotAtPosition(x, y); if (slot != null && slot.getHasStack()) { ItemStack stack = slot.getStack(); Item item = stack.getItem(); if (item instanceof ItemBlock) { Block block = ((ItemBlock) item).field_150939_a; dumpClasses("Block", block); } else { dumpClasses("Item", item); } } } super.mouseClicked(x, y, button); } private void updateList() { itemList.removeChildren(); if (tileEntity != null && !inventorySlots.getSlot(ModularStorageContainer.SLOT_STORAGE_MODULE).getHasStack()) { amountLabel.setText("(no storage)"); compactButton.setEnabled(false); cycleButton.setEnabled(false); return; } cycleButton.setEnabled(tileEntity == null || isRemote()); String filterText = filter.getText().toLowerCase().trim(); String view = viewMode.getCurrentChoice(); int numcolumns; int labelWidth; int spacing; if (VIEW_LIST.equals(view)) { numcolumns = 1; labelWidth = 210; spacing = 5; } else if (VIEW_COLUMNS.equals(view)) { numcolumns = 2; labelWidth = 86; spacing = 5; } else { numcolumns = 12; labelWidth = 0; spacing = 3; } int max; List<Pair<ItemStack,Integer>> items = new ArrayList<Pair<ItemStack, Integer>>(); if (tileEntity != null) { for (int i = 2; i < tileEntity.getSizeInventory(); i++) { ItemStack stack = tileEntity.getStackInSlot(i); if (stack != null && stack.stackSize > 0) { String displayName = stack.getDisplayName(); if (filterText.isEmpty() || displayName.toLowerCase().contains(filterText)) { items.add(Pair.of(stack, i)); } } } max = tileEntity.getSizeInventory() - 2; } else { // Also works for ModularStorageItemContainer for (int i = 0; i < RemoteStorageItemContainer.MAXSIZE_STORAGE ; i++) { Slot slot = inventorySlots.getSlot(i); ItemStack stack = slot.getStack(); if (stack != null && stack.stackSize > 0) { String displayName = stack.getDisplayName(); if (filterText.isEmpty() || displayName.toLowerCase().contains(filterText)) { items.add(Pair.of(stack, i)); } } } max = mc.thePlayer.getHeldItem().getTagCompound().getInteger("maxSize"); } amountLabel.setText(items.size() + " / " + max); compactButton.setEnabled(max > 0); int sort = getCurrentSortMode(); boolean dogroups = groupMode.getCurrentChoiceIndex() == 1; ItemSorter itemSorter = typeModule.getSorters().get(sort); Collections.sort(items, itemSorter.getComparator()); Pair<Panel,Integer> currentPos = MutablePair.of(null, 0); Pair<ItemStack, Integer> prevItem = null; for (Pair<ItemStack, Integer> item : items) { currentPos = addItemToList(item.getKey(), itemList, currentPos, numcolumns, labelWidth, spacing, item.getValue(), dogroups && (prevItem == null || !itemSorter.isSameGroup(prevItem, item)), itemSorter.getGroupName(item)); prevItem = item; } } private boolean isRemote() { return inventorySlots.getSlot(ModularStorageContainer.SLOT_STORAGE_MODULE).getStack().getItemDamage() == StorageModuleItem.STORAGE_REMOTE; } private int getCurrentSortMode() { updateTypeModule(); String sortName = sortMode.getCurrentChoice(); sortMode.clear(); for (ItemSorter sorter : typeModule.getSorters()) { sortMode.addChoice(sorter.getName(), sorter.getTooltip(), guiElements, sorter.getU(), sorter.getV()); } int sort = sortMode.findChoice(sortName); if (sort == -1) { sort = 0; } sortMode.setCurrentChoice(sort); return sort; } private void updateTypeModule() { if (tileEntity != null) { ItemStack typeStack = tileEntity.getStackInSlot(ModularStorageContainer.SLOT_TYPE_MODULE); if (typeStack == null || typeStack.stackSize == 0 || !(typeStack.getItem() instanceof TypeModule)) { typeModule = new DefaultTypeModule(); } else { typeModule = (TypeModule) typeStack.getItem(); } } else { typeModule = new DefaultTypeModule(); } } private Pair<Panel,Integer> addItemToList(ItemStack stack, WidgetList itemList, Pair<Panel,Integer> currentPos, int numcolumns, int labelWidth, int spacing, int slot, boolean newgroup, String groupName) { Panel panel = currentPos.getKey(); if (panel == null || currentPos.getValue() >= numcolumns || (newgroup && groupName != null)) { if (newgroup && groupName != null) { itemList.addChild(new Label(mc, this).setText(groupName).setColor(ModularStorageConfiguration.groupForeground). setHorizontalAlignment(HorizontalAlignment.ALIGH_LEFT).setFilledBackground(ModularStorageConfiguration.groupBackground).setDesiredHeight(10)); } panel = new Panel(mc, this).setLayout(new HorizontalLayout().setSpacing(spacing)).setDesiredHeight(12).setUserObject(new Integer(-1)).setDesiredHeight(16); currentPos = MutablePair.of(panel, 0); itemList.addChild(panel); } BlockRender blockRender = new BlockRender(mc, this).setRenderItem(stack).setUserObject(new Integer(slot)).setOffsetX(-1).setOffsetY(-1); panel.addChild(blockRender); if (labelWidth > 0) { String displayName; if (labelWidth > 100) { displayName = typeModule.getLongLabel(stack); } else { displayName = typeModule.getShortLabel(stack); } AbstractWidget label = new Label(mc, this).setText(displayName).setHorizontalAlignment(HorizontalAlignment.ALIGH_LEFT).setDesiredWidth(labelWidth).setUserObject(new Integer(-1)); panel.addChild(label); } currentPos.setValue(currentPos.getValue() + 1); return currentPos; } @Override protected void drawGuiContainerBackgroundLayer(float v, int i, int i2) { updateList(); window.draw(); } }
package me.itszooti.geojson.gson; import java.lang.reflect.Type; import me.itszooti.geojson.GeoGeometry; import me.itszooti.geojson.GeoLineString; import me.itszooti.geojson.GeoMultiLineString; import me.itszooti.geojson.GeoMultiPoint; import me.itszooti.geojson.GeoPoint; import me.itszooti.geojson.GeoPolygon; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class GeoGeometrySerializer implements JsonSerializer<GeoGeometry> { @Override public JsonElement serialize(GeoGeometry geom, Type type, JsonSerializationContext context) { // always an object with type JsonObject obj = new JsonObject(); obj.addProperty("type", geom.getClass().getSimpleName().substring(3)); // check type if (geom instanceof GeoPoint) { GeoPoint point = (GeoPoint)geom; obj.add("coordinates", context.serialize(point.getPosition())); } else if (geom instanceof GeoLineString) { GeoLineString lineString = (GeoLineString)geom; obj.add("coordinates", context.serialize(lineString.getPositions())); } else if (geom instanceof GeoPolygon) { GeoPolygon polygon = (GeoPolygon)geom; JsonArray coords = new JsonArray(); coords.add(context.serialize(polygon.getExterior())); for (int i = 0; i < polygon.getNumInteriors(); i++) { coords.add(context.serialize(polygon.getInterior(i))); } obj.add("coordinates", coords); } else if (geom instanceof GeoMultiPoint) { GeoMultiPoint multiPoint = (GeoMultiPoint)geom; JsonArray coords = new JsonArray(); for (int i = 0; i < multiPoint.getNumPoints(); i++) { coords.add(context.serialize(multiPoint.getPoint(i).getPosition())); } obj.add("coordinates", coords); } else if (geom instanceof GeoMultiLineString) { GeoMultiLineString multiLineString = (GeoMultiLineString)geom; JsonArray coords = new JsonArray(); for (int i = 0; i < multiLineString.getNumLineStrings(); i++) { coords.add(context.serialize(multiLineString.getLineString(i).getPositions())); } obj.add("coordinates", coords); } return obj; } }
package me.kenzierocks.plugins; import com.google.common.base.Preconditions; import com.google.common.collect.FluentIterable; import com.google.inject.Inject; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.trait.BlockTrait; import org.spongepowered.api.data.DataTransactionResult.Type; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.mutable.item.BlockItemData; import org.spongepowered.api.entity.ArmorEquipable; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GamePreInitializationEvent; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.text.Texts; import org.spongepowered.api.util.command.CommandException; import org.spongepowered.api.util.command.CommandResult; import org.spongepowered.api.util.command.CommandSource; import org.spongepowered.api.util.command.args.CommandContext; import org.spongepowered.api.util.command.spec.CommandExecutor; import org.spongepowered.api.util.command.spec.CommandSpec; import java.util.Collection; import java.util.Optional; import java.util.Random; /** * Usage: Hold item in hand, use command {@code (/blockitemcycle)} to randomize * first property. */ @Plugin(id = TestSpongeBlockItemData.PLUGIN_ID, name = TestSpongeBlockItemData.PLUGIN_NAME, version = TestSpongeBlockItemData.PLUGIN_VERSION) public class TestSpongeBlockItemData { private static final class BlockItemDataCommand implements CommandExecutor { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (src instanceof ArmorEquipable) { Optional<ItemStack> item = ((ArmorEquipable) src).getItemInHand(); if (item.isPresent()) { Optional<BlockState> manipulatorOpt = item.get().get(BlockItemData.class).get().get(Keys.ITEM_BLOCKSTATE); Optional<BlockState> stateOpt = item.get().get(Keys.ITEM_BLOCKSTATE); Preconditions.checkState(manipulatorOpt.equals(stateOpt)); if (!stateOpt.isPresent()) { src.sendMessage(Texts.of("Missing state!")); return CommandResult.empty(); } BlockState state = stateOpt.get().copy(); src.sendMessage(Texts.of(state.getTraitMap())); } else { src.sendMessage(Texts.of("LOL FAIL, no item in hand.")); } } else { src.sendMessage(Texts.of("LOL FAIL, no hands!")); } return CommandResult.empty(); } } public static final class BlockItemCycleCommand implements CommandExecutor { private static final Random RANDOM = new Random(); @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (src instanceof ArmorEquipable) { Optional<ItemStack> item = ((ArmorEquipable) src).getItemInHand(); if (item.isPresent()) { ItemStack stack = item.get(); Optional<BlockState> stateOpt = stack.get(Keys.ITEM_BLOCKSTATE); if (!stateOpt.isPresent()) { src.sendMessage(Texts.of("Missing state!")); return CommandResult.empty(); } BlockState state = stateOpt.get().copy(); BlockTrait<?> trait = randomFromIterator(state.getTraits()).get(); Optional<?> val = randomFromIterator(trait.getPossibleValues()); if (val.isPresent()) { state = state.withTrait(trait, val.get()).get(); if (stack.offer(Keys.ITEM_BLOCKSTATE, state).getType() == Type.SUCCESS) { src.sendMessage(Texts.of("SUCCESS BY KEYS, state=", state.toString(), "stuff=", val.get())); } else { src.sendMessage(Texts.of("LOL FAIL, tried to randomize property on " + stack)); } BlockItemData manipulator = item.get().get(BlockItemData.class).get(); manipulator.set(Keys.ITEM_BLOCKSTATE, state); if (stack.offer(manipulator).getType() == Type.SUCCESS) { src.sendMessage(Texts.of("SUCCESS BY MANIPULATOR, state=", state.toString(), "stuff=", val.get())); } else { src.sendMessage(Texts.of("LOL FAIL, tried to randomize property on " + stack)); } ((ArmorEquipable) src).setItemInHand(stack); return CommandResult.success(); } else { src.sendMessage(Texts.of("LOL FAIL, no trait to randomize!")); } } else { src.sendMessage(Texts.of("LOL FAIL, no item in hand.")); } } else { src.sendMessage(Texts.of("LOL FAIL, no hands!")); } return CommandResult.empty(); } private <T> Optional<T> randomFromIterator(Collection<T> possibleValues) { return Optional.ofNullable(FluentIterable.from(possibleValues).skip(RANDOM.nextInt(possibleValues.size())).first().orNull()); } } public static final String PLUGIN_ID = "testblockitemdata", PLUGIN_NAME = "Test BlockItemData", PLUGIN_VERSION = "1.0"; @Inject private Logger logger; @Inject private Game game; @Listener public void onGamePreInitilization(GamePreInitializationEvent event) { this.logger.info("Commencing initialization..."); CommandSpec cycleCommand = CommandSpec.builder() .description(Texts.of("Cycle your items! Colors!")) .executor(new BlockItemCycleCommand()) .build(); game.getCommandDispatcher().register(this, cycleCommand, "blockitemcycle"); CommandSpec dumpCommand = CommandSpec.builder() .description(Texts.of("Print data.")) .executor(new BlockItemDataCommand()) .build(); game.getCommandDispatcher().register(this, dumpCommand, "blockitemdata"); } }
package net.sf.jabref.importer.fileformat; import java.io.BufferedReader; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.io.StringReader; import java.util.*; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sf.jabref.*; import net.sf.jabref.bibtex.EntryTypes; import net.sf.jabref.logic.CustomEntryTypesManager; import net.sf.jabref.gui.GUIGlobals; import net.sf.jabref.model.database.KeyCollisionException; import net.sf.jabref.importer.ParserResult; import net.sf.jabref.model.entry.IdGenerator; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.util.strings.StringUtil; import net.sf.jabref.model.database.BibtexDatabase; import net.sf.jabref.model.entry.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Class for importing BibTeX-files. * <p> * Use: * <p> * BibtexParser parser = new BibtexParser(reader); * <p> * ParserResult result = parser.parse(); * <p> * or * <p> * ParserResult result = BibtexParser.parse(reader); * <p> * Can be used stand-alone. */ public class BibtexParser { private static final Log LOGGER = LogFactory.getLog(BibtexParser.class); private PushbackReader pushbackReader; private BibtexDatabase database; private HashMap<String, EntryType> entryTypes; private boolean eof; private int line = 1; private final FieldContentParser fieldContentParser = new FieldContentParser(); private ParserResult parserResult; private static final Integer LOOKAHEAD = 64; private final boolean autoDoubleBraces; private Deque<Character> pureTextFromFile = new LinkedList<>(); private BibtexEntry lastParsedEntry; public BibtexParser(Reader in) { Objects.requireNonNull(in); if (Globals.prefs == null) { Globals.prefs = JabRefPreferences.getInstance(); } autoDoubleBraces = Globals.prefs.getBoolean(JabRefPreferences.AUTO_DOUBLE_BRACES); pushbackReader = new PushbackReader(in, BibtexParser.LOOKAHEAD); } /** * Shortcut usage to create a Parser and read the input. * * @param in the Reader to read from * @throws IOException */ public static ParserResult parse(Reader in) throws IOException { BibtexParser parser = new BibtexParser(in); return parser.parse(); } /** * Parses BibtexEntries from the given string and returns the collection of all entries found. * * @param bibtexString * @return Returns null if an error occurred, returns an empty collection if no entries where found. */ public static Collection<BibtexEntry> fromString(String bibtexString) { StringReader reader = new StringReader(bibtexString); BibtexParser parser = new BibtexParser(reader); try { return parser.parse().getDatabase().getEntries(); } catch (Exception e) { return null; } } /** * Parses BibtexEntries from the given string and returns one entry found (or null if none found) * <p> * It is undetermined which entry is returned, so use this in case you know there is only one entry in the string. * * @param bibtexString * @return The bibtexentry or null if non was found or an error occurred. */ public static BibtexEntry singleFromString(String bibtexString) { Collection<BibtexEntry> entries = BibtexParser.fromString(bibtexString); if ((entries == null) || entries.isEmpty()) { return null; } return entries.iterator().next(); } /** * Check whether the source is in the correct format for this importer. */ public static boolean isRecognizedFormat(Reader reader) throws IOException { // Our strategy is to look for the "@<type> {" line. BufferedReader in = new BufferedReader(reader); Pattern formatPattern = Pattern.compile("@[a-zA-Z]*\\s*\\{"); String bibtexString; while ((bibtexString = in.readLine()) != null) { if (formatPattern.matcher(bibtexString).find()) { return true; } } return false; } /** * Will parse the BibTex-Data found when reading from reader. * <p> * The reader will be consumed. * <p> * Multiple calls to parse() return the same results * * @return ParserResult * @throws IOException */ public ParserResult parse() throws IOException { // If we already parsed this, just return it. if (parserResult != null) { return parserResult; } // Bibtex related contents. initializeParserResult(); HashMap<String, String> meta = new HashMap<>(); // First see if we can find the version number of the JabRef version that // wrote the file: String versionNumber = readJabRefVersionNumber(); if (versionNumber != null) { parserResult.setJabrefVersion(versionNumber); setMajorMinorVersions(); } skipWhitespace(); try { while (!eof) { boolean found = consumeUncritically('@'); if (!found) { break; } skipWhitespace(); String entryType = parseTextToken(); EntryType type = EntryTypes.getType(entryType); boolean isEntry = type != null; // The entry type name was not recognized. This can mean // that it is a string, preamble, or comment. If so, // parse and set accordingly. If not, assume it is an entry // with an unknown type. if (!isEntry) { if ("preamble".equals(entryType.toLowerCase())) { database.setPreamble(parsePreamble()); } else if ("string".equals(entryType.toLowerCase())) { BibtexString bibtexString = parseString(); bibtexString.setParsedSerialization(dumpTextReadSoFarToString()); try { database.addString(bibtexString); } catch (KeyCollisionException ex) { parserResult.addWarning(Localization.lang("Duplicate string name") + ": " + bibtexString.getName()); } } else if ("comment".equals(entryType.toLowerCase())) { StringBuffer buffer = parseBracketedTextExactly(); /** * * Metadata are used to store Bibkeeper-specific * information in .bib files. * * Metadata are stored in bibtex files in the format * * @comment{jabref-meta: type:data0;data1;data2;...} * * Each comment that starts with the META_FLAG is stored * in the meta HashMap, with type as key. Unluckily, the * old META_FLAG bibkeeper-meta: was used in JabRef 1.0 * and 1.1, so we need to support it as well. At least * for a while. We'll always save with the new one. */ String comment = buffer.toString().replaceAll("[\\x0d\\x0a]", ""); if (comment.substring(0, Math.min(comment.length(), GUIGlobals.META_FLAG.length())).equals( GUIGlobals.META_FLAG) || comment.substring(0, Math.min(comment.length(), GUIGlobals.META_FLAG_OLD.length())) .equals(GUIGlobals.META_FLAG_OLD)) { String rest; if (comment.substring(0, GUIGlobals.META_FLAG.length()).equals( GUIGlobals.META_FLAG)) { rest = comment.substring(GUIGlobals.META_FLAG.length()); } else { rest = comment.substring(GUIGlobals.META_FLAG_OLD.length()); } int pos = rest.indexOf(':'); if (pos > 0) { meta.put(rest.substring(0, pos), rest.substring(pos + 1)); // We remove all line breaks in the metadata - these // will have been inserted // to prevent too long lines when the file was // saved, and are not part of the data. } } else if (comment.substring(0, Math.min(comment.length(), CustomEntryType.ENTRYTYPE_FLAG.length())).equals( CustomEntryType.ENTRYTYPE_FLAG)) { // A custom entry type can also be stored in a // "@comment" CustomEntryType typ = CustomEntryTypesManager.parseEntryType(comment); entryTypes.put(typ.getName(), typ); } else { // FIXME: user comments are simply dropped // at least, we log that we ignored the comment LOGGER.info("Dropped comment from database: " + comment); } } else { // The entry type was not recognized. This may mean that // it is a custom entry type whose definition will // appear // at the bottom of the file. So we use an // UnknownEntryType // to remember the type name by. type = new UnknownEntryType(EntryUtil.capitalizeFirst(entryType)); isEntry = true; } } // True if not comment, preamble or string. if (isEntry) { /** * Morten Alver 13 Aug 2006: Trying to make the parser more * robust. If an exception is thrown when parsing an entry, * drop the entry and try to resume parsing. Add a warning * for the user. */ try { BibtexEntry entry = parseEntry(type); boolean duplicateKey = database.insertEntry(entry); entry.setParsedSerialization(dumpTextReadSoFarToString()); lastParsedEntry = entry; if (duplicateKey) { parserResult.addDuplicateKey(entry.getCiteKey()); } else if ((entry.getCiteKey() == null) || "".equals(entry.getCiteKey())) { parserResult .addWarning(Localization.lang("Empty BibTeX key") + ": " + entry.getAuthorTitleYear(40) + " (" + Localization.lang("grouping may not work for this entry") + ")"); } } catch (IOException ex) { LOGGER.warn("Could not parse entry", ex); parserResult.addWarning(Localization.lang("Error occurred when parsing entry") + ": '" + ex.getMessage() + "'. " + Localization.lang("Skipped entry.")); } } skipWhitespace(); } // Before returning the database, update entries with unknown type // based on parsed type definitions, if possible. checkEntryTypes(parserResult); // Instantiate meta data: parserResult.setMetaData(new MetaData(meta, database)); if (lastParsedEntry != null) { // read remaining content of file and add it to the parsed serialization of the last entry lastParsedEntry.setParsedSerialization(lastParsedEntry.getParsedSerialization() + dumpTextReadSoFarToString()); } return parserResult; } catch (KeyCollisionException kce) { // kce.printStackTrace(); throw new IOException("Duplicate ID in bibtex file: " + kce); } } private void initializeParserResult() { database = new BibtexDatabase(); entryTypes = new HashMap<>(); // To store custem entry types parsed. parserResult = new ParserResult(database, null, entryTypes); } /** * Puts all text that has been read from the reader, including newlines, etc., since the last call of this method into a string. * Removes the JabRef file header, if it is found * * @return the text read so far */ private String dumpTextReadSoFarToString() { StringBuilder entry = new StringBuilder(); while (!pureTextFromFile.isEmpty()) { entry.append(pureTextFromFile.pollFirst()); } String result = entry.toString(); int indexOfAt = entry.indexOf("@"); // if there is no entry found, simply return the content (necessary to parse text remaining after the last entry) if (indexOfAt == -1) { return purgeEOFCharacters(entry); } else { //skip all text except newlines and whitespaces before first @. This is necessary to remove the file header int runningIndex = indexOfAt - 1; while (runningIndex >= 0) { if (!Character.isWhitespace(result.charAt(runningIndex))) { break; } runningIndex } // only keep newlines if there is an entry before if (runningIndex > 0 && !"}".equals(result.charAt(runningIndex - 1))) { result = result.substring(indexOfAt); } else { result = result.substring(runningIndex + 1); } return result; } } /** * Removes all eof characters from a StringBuilder and returns a new String with the resulting content * * @return a String without eof characters */ private String purgeEOFCharacters(StringBuilder input) { StringBuilder remainingText = new StringBuilder(); for (Character character : input.toString().toCharArray()) { if (!(isEOFCharacter(character))) { remainingText.append(character); } } return remainingText.toString(); } private void skipWhitespace() throws IOException { int character; while (true) { character = read(); if (isEOFCharacter(character)) { eof = true; return; } if (Character.isWhitespace((char) character)) { continue; } else { // found non-whitespace char unread(character); break; } } } private boolean isEOFCharacter(int character) { return (character == -1) || (character == 65535); } private String skipAndRecordWhitespace(int character) throws IOException { StringBuilder stringBuilder = new StringBuilder(); if (character != ' ') { stringBuilder.append((char) character); } while (true) { int nextCharacter = read(); if (isEOFCharacter(nextCharacter)) { eof = true; return stringBuilder.toString(); } if (Character.isWhitespace((char) nextCharacter)) { if (nextCharacter != ' ') { stringBuilder.append((char) nextCharacter); } continue; } else { // found non-whitespace char unread(nextCharacter); break; } } return stringBuilder.toString(); } private int peek() throws IOException { int character = read(); unread(character); return character; } private int read() throws IOException { int character = pushbackReader.read(); pureTextFromFile.offerLast(Character.valueOf((char) character)); if (character == '\n') { line++; } return character; } private void unread(int character) throws IOException { if (character == '\n') { line } pushbackReader.unread(character); pureTextFromFile.pollLast(); } private BibtexString parseString() throws IOException { skipWhitespace(); consume('{', '('); // while (read() != '}'); skipWhitespace(); // Util.pr("Parsing string name"); String name = parseTextToken(); // Util.pr("Parsed string name"); skipWhitespace(); // Util.pr("Now the contents"); consume('='); String content = parseFieldContent(name); // Util.pr("Now I'm going to consume a }"); consume('}', ')'); // Util.pr("Finished string parsing."); String id = IdGenerator.next(); return new BibtexString(id, name, content); } private String parsePreamble() throws IOException { return parseBracketedText().toString(); } private BibtexEntry parseEntry(EntryType entryType) throws IOException { String id = IdGenerator.next(); BibtexEntry result = new BibtexEntry(id, entryType); skipWhitespace(); consume('{', '('); int character = peek(); if ((character != '\n') && (character != '\r')) { skipWhitespace(); } String key = parseKey(); if ("".equals(key)) { key = null; } result.setField(BibtexEntry.KEY_FIELD, key); skipWhitespace(); while (true) { character = peek(); if ((character == '}') || (character == ')')) { break; } if (character == ',') { consume(','); } skipWhitespace(); character = peek(); if ((character == '}') || (character == ')')) { break; } parseField(result); } consume('}', ')'); return result; } private void parseField(BibtexEntry entry) throws IOException { String key = parseTextToken().toLowerCase(); // Util.pr("Field: _"+key+"_"); skipWhitespace(); consume('='); String content = parseFieldContent(key); // Now, if the field in question is set up to be fitted automatically // with braces around // capitals, we should remove those now when reading the field: if (Globals.prefs.putBracesAroundCapitals(key)) { content = StringUtil.removeBracesAroundCapitals(content); } if (!content.isEmpty()) { if (entry.getField(key) == null) { entry.setField(key, content); } else { // The following hack enables the parser to deal with multiple // author or // editor lines, stringing them together instead of getting just // one of them. // Multiple author or editor lines are not allowed by the bibtex // format, but // at least one online database exports bibtex like that, making // it inconvenient // for users if JabRef didn't accept it. if ("author".equals(key) || "editor".equals(key)) { entry.setField(key, entry.getField(key) + " and " + content); } } } } private String parseFieldContent(String key) throws IOException { skipWhitespace(); StringBuilder value = new StringBuilder(); int character; while (((character = peek()) != ',') && (character != '}') && (character != ')')) { if (eof) { throw new RuntimeException("Error in line " + line + ": EOF in mid-string"); } if (character == '"') { StringBuffer text = parseQuotedFieldExactly(); value.append(fieldContentParser.format(text, key)); /* * * The following code doesn't handle {"} correctly: // value is * a string consume('"'); * * while (!((peek() == '"') && (j != '\\'))) { j = read(); if * (_eof || (j == -1) || (j == 65535)) { throw new * RuntimeException("Error in line "+line+ ": EOF in * mid-string"); } * * value.append((char) j); } * * consume('"'); */ } else if (character == '{') { // Value is a string enclosed in brackets. There can be pairs // of brackets inside of a field, so we need to count the // brackets to know when the string is finished. StringBuffer text = parseBracketedTextExactly(); value.append(fieldContentParser.format(text, key)); } else if (Character.isDigit((char) character)) { // value is a number String number = parseTextToken(); value.append(number); } else if (character == ' consume(' } else { String textToken = parseTextToken(); if (textToken.isEmpty()) { throw new IOException("Error in line " + line + " or above: " + "Empty text token.\nThis could be caused " + "by a missing comma between two fields."); } value.append("#").append(textToken).append("#"); } skipWhitespace(); } // Check if we are to strip extra pairs of braces before returning: if (autoDoubleBraces) { // Do it: while ((value.length() > 1) && (value.charAt(0) == '{') && (value.charAt(value.length() - 1) == '}')) { value.deleteCharAt(value.length() - 1); value.deleteCharAt(0); } // Problem: if the field content is "{DNA} blahblah {EPA}", one pair // too much will be removed. // Check if this is the case, and re-add as many pairs as needed. while (hasNegativeBraceCount(value.toString())) { value.insert(0, '{'); value.append('}'); } } return value.toString(); } /** * Check if a string at any point has had more ending braces (}) than * opening ones ({). Will e.g. return true for the string "DNA} blahblal * {EPA" * * @param toCheck The string to check. * @return true if at any index the brace count is negative. */ private boolean hasNegativeBraceCount(String toCheck) { int index = 0; int braceCount = 0; while (index < toCheck.length()) { if (toCheck.charAt(index) == '{') { braceCount++; } else if (toCheck.charAt(index) == '}') { braceCount } if (braceCount < 0) { return true; } index++; } return false; } /** * This method is used to parse string labels, field names, entry type and * numbers outside brackets. */ private String parseTextToken() throws IOException { StringBuilder token = new StringBuilder(20); while (true) { int character = read(); // Util.pr(".. "+c); if (character == -1) { eof = true; return token.toString(); } if (Character.isLetterOrDigit((char) character) || (character == ':') || (character == '-') || (character == '_') || (character == '*') || (character == '+') || (character == '.') || (character == '/') || (character == '\'')) { token.append((char) character); } else { unread(character); return token.toString(); } } } /** * Tries to restore the key * * @return rest of key on success, otherwise empty string * @throws IOException on Reader-Error */ private String fixKey() throws IOException { StringBuilder key = new StringBuilder(); int lookaheadUsed = 0; char currentChar; // Find a char which ends key (','&&'\n') or entryfield ('='): do { currentChar = (char) read(); key.append(currentChar); lookaheadUsed++; } while ((currentChar != ',') && (currentChar != '\n') && (currentChar != '=') && (lookaheadUsed < BibtexParser.LOOKAHEAD)); // Consumed a char too much, back into reader and remove from key: unread(currentChar); key.deleteCharAt(key.length() - 1); // Restore if possible: switch (currentChar) { case '=': // Get entryfieldname, push it back and take rest as key key = key.reverse(); boolean matchedAlpha = false; for (int i = 0; i < key.length(); i++) { currentChar = key.charAt(i); /// Skip spaces: if (!matchedAlpha && (currentChar == ' ')) { continue; } matchedAlpha = true; // Begin of entryfieldname (e.g. author) -> push back: unread(currentChar); if ((currentChar == ' ') || (currentChar == '\n')) { /* * found whitespaces, entryfieldname completed -> key in * keybuffer, skip whitespaces */ StringBuilder newKey = new StringBuilder(); for (int j = i; j < key.length(); j++) { currentChar = key.charAt(j); if (!Character.isWhitespace(currentChar)) { newKey.append(currentChar); } } // Finished, now reverse newKey and remove whitespaces: parserResult.addWarning(Localization.lang("Line %0: Found corrupted BibTeX-key.", String.valueOf(line))); key = newKey.reverse(); } } break; case ',': parserResult.addWarning(Localization.lang("Line %0: Found corrupted BibTeX-key (contains whitespaces).", String.valueOf(line))); case '\n': parserResult.addWarning(Localization.lang("Line %0: Found corrupted BibTeX-key (comma missing).", String.valueOf(line))); break; default: // No more lookahead, give up: unreadBuffer(key); return ""; } return removeWhitespaces(key).toString(); } /** * returns a new <code>StringBuilder</code> which corresponds to <code>toRemove</code> without whitespaces * * @param toRemove * @return */ private StringBuilder removeWhitespaces(StringBuilder toRemove) { StringBuilder result = new StringBuilder(); char current; for (int i = 0; i < toRemove.length(); ++i) { current = toRemove.charAt(i); if (!Character.isWhitespace(current)) { result.append(current); } } return result; } /** * pushes buffer back into input * * @param stringBuilder * @throws IOException can be thrown if buffer is bigger than LOOKAHEAD */ private void unreadBuffer(StringBuilder stringBuilder) throws IOException { for (int i = stringBuilder.length() - 1; i >= 0; --i) { unread(stringBuilder.charAt(i)); } } /** * This method is used to parse the bibtex key for an entry. */ private String parseKey() throws IOException { StringBuilder token = new StringBuilder(20); while (true) { int character = read(); // Util.pr(".. '"+(char)c+"'\t"+c); if (character == -1) { eof = true; return token.toString(); } // Ikke: #{}\uFFFD~\uFFFD // G\uFFFDr: $_*+.-\/?"^ if (!Character.isWhitespace((char) character) && (Character.isLetterOrDigit((char) character) || (character == ':') || ((character != '#') && (character != '{') && (character != '}') && (character != '\uFFFD') && (character != '~') && (character != '\uFFFD') && (character != ',') && (character != '=')))) { token.append((char) character); } else { if (Character.isWhitespace((char) character)) { // We have encountered white space instead of the comma at // the end of // the key. Possibly the comma is missing, so we try to // return what we // have found, as the key and try to restore the rest in fixKey(). return token + fixKey(); } else if (character == ',') { unread(character); return token.toString(); } else if (character == '=') { // If we find a '=' sign, it is either an error, or // the entry lacked a comma signifying the end of the key. return token.toString(); } else { throw new IOException("Error in line " + line + ":" + "Character '" + (char) character + "' is not " + "allowed in bibtex keys."); } } } } private StringBuffer parseBracketedText() throws IOException { StringBuffer value = new StringBuffer(); consume('{'); int brackets = 0; while (!((peek() == '}') && (brackets == 0))) { int character = read(); if (isEOFCharacter(character)) { throw new RuntimeException("Error in line " + line + ": EOF in mid-string"); } else if (character == '{') { brackets++; } else if (character == '}') { brackets } // If we encounter whitespace of any kind, read it as a // simple space, and ignore any others that follow immediately. /* * if (j == '\n') { if (peek() == '\n') value.append('\n'); } else */ if (Character.isWhitespace((char) character)) { String whitespacesReduced = skipAndRecordWhitespace(character); if (!"".equals(whitespacesReduced) && !"\n\t".equals(whitespacesReduced)) { whitespacesReduced = whitespacesReduced.replaceAll("\t", ""); // Remove tabulators. value.append(whitespacesReduced); } else { value.append(' '); } } else { value.append((char) character); } } consume('}'); return value; } private StringBuffer parseBracketedTextExactly() throws IOException { StringBuffer value = new StringBuffer(); consume('{'); int brackets = 0; while (!((peek() == '}') && (brackets == 0))) { int character = read(); if (isEOFCharacter(character)) { throw new RuntimeException("Error in line " + line + ": EOF in mid-string"); } else if (character == '{') { brackets++; } else if (character == '}') { brackets } value.append((char) character); } consume('}'); return value; } private StringBuffer parseQuotedFieldExactly() throws IOException { StringBuffer value = new StringBuffer(); consume('"'); int brackets = 0; while (!((peek() == '"') && (brackets == 0))) { int j = read(); if (isEOFCharacter(j)) { throw new RuntimeException("Error in line " + line + ": EOF in mid-string"); } else if (j == '{') { brackets++; } else if (j == '}') { brackets } value.append((char) j); } consume('"'); return value; } private void consume(char expected) throws IOException { int character = read(); if (character != expected) { throw new RuntimeException("Error in line " + line + ": Expected " + expected + " but received " + (char) character); } } private boolean consumeUncritically(char expected) throws IOException { int character; while (((character = read()) != expected) && (character != -1) && (character != 65535)) { // do nothing } if (isEOFCharacter(character)) { eof = true; } // Return true if we actually found the character we were looking for: return character == expected; } private void consume(char firstOption, char secondOption) throws IOException { // Consumes one of the two, doesn't care which appears. int character = read(); if ((character != firstOption) && (character != secondOption)) { throw new RuntimeException("Error in line " + line + ": Expected " + firstOption + " or " + secondOption + " but received " + character); } } private void checkEntryTypes(ParserResult parserResult) { for (BibtexEntry bibtexEntry : database.getEntries()) { if (bibtexEntry.getType() instanceof UnknownEntryType) { // Look up the unknown type name in our map of parsed types: String name = bibtexEntry.getType().getName(); EntryType type = entryTypes.get(name); if (type != null) { bibtexEntry.setType(type); } else { parserResult.addWarning( Localization.lang("Unknown entry type") + ": " + name + "; key: " + bibtexEntry.getCiteKey() ); } } } } /** * Read the JabRef signature, if any, and find what version number is given. * This method advances the file reader only as far as the end of the first line of * the JabRef signature, or up until the point where the read characters don't match * the signature. This should ensure that the parser can continue from that spot without * resetting the reader, without the risk of losing important contents. * * @return The version number, or null if not found. * @throws IOException */ private String readJabRefVersionNumber() throws IOException { StringBuilder headerText = new StringBuilder(); boolean keepOn = true; int piv = 0; int character; // We start by reading the standard part of the signature, which precedes // the version number: This file was created with JabRef X.y. while (keepOn) { character = peek(); headerText.append((char) character); if ((piv == 0) && (Character.isWhitespace((char) character) || (character == '%'))) { read(); } else if (character == Globals.SIGNATURE.charAt(piv)) { piv++; read(); } else { return null; } // Check if we've reached the end of the signature's standard part: if (piv == Globals.SIGNATURE.length()) { keepOn = false; // Found the standard part. Now read the version number: StringBuilder stringBuilder = new StringBuilder(); while (((character = read()) != '\n') && (character != -1)) { stringBuilder.append((char) character); } String versionNumber = stringBuilder.toString().trim(); // See if it fits the X.y. pattern: if (Pattern.compile("[1-9]+\\.[1-9A-Za-z ]+\\.").matcher(versionNumber).matches()) { // It matched. Remove the last period and return: return versionNumber.substring(0, versionNumber.length() - 1); } else if (Pattern.compile("[1-9]+\\.[1-9]\\.[1-9A-Za-z ]+\\.").matcher(versionNumber).matches()) { // It matched. Remove the last period and return: return versionNumber.substring(0, versionNumber.length() - 1); } } } return null; } /** * After a JabRef version number has been parsed and put into _pr, * parse the version number to determine the JabRef major and minor version * number */ private void setMajorMinorVersions() { String version = parserResult.getJabrefVersion(); Pattern versionPattern = Pattern.compile("([0-9]+)\\.([0-9]+).*"); Matcher matcher = versionPattern.matcher(version); if (matcher.matches()) { if (matcher.groupCount() >= 2) { parserResult.setJabrefMajorVersion(Integer.parseInt(matcher.group(1))); parserResult.setJabrefMinorVersion(Integer.parseInt(matcher.group(2))); } } } }
package org.jdesktop.beans; import java.util.Collection; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComponent; import junit.framework.TestCase; import org.apache.commons.collections.MultiHashMap; import org.apache.commons.collections.MultiMap; import org.jdesktop.swingx.InteractiveTestCase; import org.jdesktop.swingx.JXCollapsiblePane; import org.jdesktop.swingx.JXDatePicker; import org.jdesktop.swingx.JXImagePanel; import org.jdesktop.swingx.JXList; import org.jdesktop.swingx.JXMonthView; import org.jdesktop.swingx.JXMultiSplitPane; import org.jdesktop.swingx.JXMultiThumbSlider; import org.jdesktop.swingx.JXSearchPanel; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.renderer.JRendererCheckBox; import org.jdesktop.swingx.renderer.JRendererLabel; import org.jdesktop.swingx.renderer.JXRendererHyperlink; import org.jdesktop.swingx.renderer.WrappingIconPanel; import org.jdesktop.test.TestUtils; /** * Reflection based test for testing PCE firing. * * @author rah003 */ public class BeanEventsTest extends InteractiveTestCase { static Logger log = Logger.getAnonymousLogger(); public void testAllPainterPCEFiring() throws Exception { log.setLevel(Level.ALL); List<Class<?>> beanClasses = ClassSearchUtils.searchClassPath("org.jdesktop.swingx."); MultiMap excludes = new MultiHashMap(); // shorthand for getModel.setColumnMargin excludes.put(JXTable.class, "columnMargin"); // overwritten method setPreferredScrollableViewportSize from JTable // the super implementation fails to fire event. Attempt to do so in JXTable causes other test failures. Needs to be investigated. excludes.put(JXTable.class, "preferredScrollableViewportSize"); // no op due to method being deprecated excludes.put(JXTable.class, "rowHeightEnabled"); // no op due to sorting conflict excludes.put(JXTreeTable.class, "sortable"); // shorthand for getSortController().setSortOrder excludes.put(JXList.class, "sortOrder"); // no op temporarily disabled due to changes in filtering implementation excludes.put(JXList.class, "filterEnabled"); // no op due to sorting conflict excludes.put(JXTreeTable.class, "filters"); // shorthand for getRenderer.setLargeModel excludes.put(JXTreeTable.class, "largeModel"); // shorthand for getRenderer.setOverwriteRendererIcons excludes.put(JXTreeTable.class, "overwriteRendererIcons"); // shorthand for getRenderer.setRootVisible excludes.put(JXTreeTable.class, "rootVisible"); // shorthand for getRenderer.setToggleClickCount excludes.put(JXTreeTable.class, "toggleClickCount"); // shorthand for getLayout.setDividerSize excludes.put(JXMultiSplitPane.class, "dividerSize"); // shorthand for getLayout.setModel excludes.put(JXMultiSplitPane.class, "model"); // shorthand for getSelectionModel.setSelectionMode excludes.put(JXMonthView.class, "selectionMode"); // shorthand for getSelectionModel.setUpperBound excludes.put(JXMonthView.class, "upperBound"); // shorthand for getSelectionModel.setLowerBound excludes.put(JXMonthView.class, "lowerBound"); // shorthand for getSelectionModel.setSelectionInterval(newDate, newDate); excludes.put(JXMonthView.class, "selectionDate"); // shorthand for getEditor.setFont excludes.put(JXDatePicker.class, "font"); // according to javadoc: api hack for testing excludes.put(JXDatePicker.class, "linkDay"); // incorrect method name ... shoud be addPatternFilter instead excludes.put(JXSearchPanel.class, "patternFilter"); // JRendererLabel doesn't fire events for performance reasons excludes.put(JRendererLabel.class, "toolTipText"); // JRendererLabel doesn't fire events for performance reasons excludes.put(JRendererLabel.class, "painter"); // JRendererCheckBox doesn't fire events for performance reasons excludes.put(JRendererCheckBox.class, "toolTipText"); // JRendererCheckBox doesn't fire events for performance reasons excludes.put(JRendererCheckBox.class, "painter"); // shorthand for getComponent.setPainter() excludes.put(WrappingIconPanel.class, "painter"); // JXRendererHyperlink doesn't fire events for performance reasons excludes.put(JXRendererHyperlink.class, "toolTipText"); // JXRendererHyperlink doesn't fire events for performance reasons excludes.put(JXRendererHyperlink.class, "painter"); // shorthand for getModel.setMinimumValue excludes.put(JXMultiThumbSlider.class, "minimumValue"); // shorthand for getModel.setMaximumValue excludes.put(JXMultiThumbSlider.class, "maximumValue"); // shorthand for getContentPane.setMinimumSize excludes.put(JXCollapsiblePane.class, "minimumSize"); // shorthand for getContentPane.setPreferredSize excludes.put(JXCollapsiblePane.class, "preferredSize"); // shorthand for getContentPane.setBorder excludes.put(JXCollapsiblePane.class, "border"); // this is a tricky one ... potentially a bug somewhere. In case preferredSize is not set yet, call to getPreferredSize() is propagated all the way up to Container, which in turn requests preferred size from the layout manager. On the other hand when preferred size is set, "old" preferred size for the purpose of event is determined (this time in Component) solely from the previous value of private variable preferredSize and therefore null excludes.put(JXImagePanel.class, "preferredSize"); log.fine("Got " + beanClasses.size()); for (Class beanClass : beanClasses) { if (!AbstractBean.class.isAssignableFrom(beanClass) && !JComponent.class.isAssignableFrom(beanClass) || TestCase.class.isAssignableFrom(beanClass)) { log.fine("Skipping " + beanClass); continue; } try { Object inst = beanClass.newInstance(); log.fine("Testing " + beanClass); TestUtils.assertPCEFiring( inst, (Collection<String>) excludes.get(beanClass)); } catch (Exception e) { log.info("ignoring " + beanClass + " because of " + e.getMessage()); } } } }
package net.sf.mzmine.datamodel.impl; import java.text.Format; import java.util.Arrays; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import net.sf.mzmine.datamodel.Feature; import net.sf.mzmine.datamodel.IsotopePattern; import net.sf.mzmine.datamodel.PeakIdentity; import net.sf.mzmine.datamodel.PeakInformation; import net.sf.mzmine.datamodel.PeakListRow; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.Scan; import net.sf.mzmine.main.MZmineCore; import net.sf.mzmine.util.PeakSorter; import net.sf.mzmine.util.SortingDirection; import net.sf.mzmine.util.SortingProperty; /** * Implementation of PeakListRow */ public class SimplePeakListRow implements PeakListRow { // faster than Hashtable private ConcurrentHashMap<RawDataFile, Feature> peaks; private Feature preferredPeak; private List<PeakIdentity> identities; private PeakIdentity preferredIdentity; private String comment; private PeakInformation information; private int myID; private double maxDataPointIntensity = 0; /** * These variables are used for caching the average values, so we don't need to calculate them * again and again */ private double averageRT, averageMZ, averageHeight, averageArea; private int rowCharge; public SimplePeakListRow(int myID) { this.myID = myID; peaks = new ConcurrentHashMap<RawDataFile, Feature>(); identities = new Vector<PeakIdentity>(); information = null; preferredPeak = null; } /** * @see net.sf.mzmine.datamodel.PeakListRow#getID() */ public int getID() { return myID; } /** * Return peaks assigned to this row */ public Feature[] getPeaks() { return peaks.values().toArray(new Feature[0]); } public void removePeak(RawDataFile file) { this.peaks.remove(file); calculateAverageValues(); } /** * Returns opened raw data files with a peak on this row */ public RawDataFile[] getRawDataFiles() { return peaks.keySet().toArray(new RawDataFile[0]); } /** * Returns peak for given raw data file */ public Feature getPeak(RawDataFile rawData) { return peaks.get(rawData); } public void addPeak(RawDataFile rawData, Feature peak) { if (peak == null) throw new IllegalArgumentException("Cannot add null peak to a peak list row"); // ConcurrentHashMap is already synchronized peaks.put(rawData, peak); synchronized (this) { if (peak.getRawDataPointsIntensityRange().upperEndpoint() > maxDataPointIntensity) maxDataPointIntensity = peak.getRawDataPointsIntensityRange().upperEndpoint(); calculateAverageValues(); } } public double getAverageMZ() { return averageMZ; } public double getAverageRT() { return averageRT; } public double getAverageHeight() { return averageHeight; } public double getAverageArea() { return averageArea; } public int getRowCharge() { return rowCharge; } private synchronized void calculateAverageValues() { double rtSum = 0, mzSum = 0, heightSum = 0, areaSum = 0; int charge = 0; HashSet<Integer> chargeArr = new HashSet<Integer>(); Enumeration<Feature> peakEnum = peaks.elements(); while (peakEnum.hasMoreElements()) { Feature p = peakEnum.nextElement(); rtSum += p.getRT(); mzSum += p.getMZ(); heightSum += p.getHeight(); areaSum += p.getArea(); if (p.getCharge() > 0) { chargeArr.add(p.getCharge()); charge = p.getCharge(); } } averageRT = rtSum / peaks.size(); averageMZ = mzSum / peaks.size(); averageHeight = heightSum / peaks.size(); averageArea = areaSum / peaks.size(); if (chargeArr.size() < 2) { rowCharge = charge; } else { rowCharge = 0; } } /** * Returns number of peaks assigned to this row */ public int getNumberOfPeaks() { return peaks.size(); } public String toString() { StringBuffer buf = new StringBuffer(); Format mzFormat = MZmineCore.getConfiguration().getMZFormat(); Format timeFormat = MZmineCore.getConfiguration().getRTFormat(); buf.append("#" + myID + " "); buf.append(mzFormat.format(getAverageMZ())); buf.append(" m/z @"); buf.append(timeFormat.format(getAverageRT())); if (preferredIdentity != null) buf.append(" " + preferredIdentity.getName()); if ((comment != null) && (comment.length() > 0)) buf.append(" (" + comment + ")"); return buf.toString(); } /** * @see net.sf.mzmine.datamodel.PeakListRow#getComment() */ public String getComment() { return comment; } /** * @see net.sf.mzmine.datamodel.PeakListRow#setComment(java.lang.String) */ public void setComment(String comment) { this.comment = comment; } /** * @see net.sf.mzmine.datamodel.PeakListRow#setAverageMZ(java.lang.String) */ public void setAverageMZ(double mz) { this.averageMZ = mz; } /** * @see net.sf.mzmine.datamodel.PeakListRow#setAverageRT(java.lang.String) */ public void setAverageRT(double rt) { this.averageRT = rt; } /** * @see net.sf.mzmine.datamodel.PeakListRow#addCompoundIdentity(net.sf.mzmine.datamodel.PeakIdentity) */ public synchronized void addPeakIdentity(PeakIdentity identity, boolean preferred) { // Verify if exists already an identity with the same name for (PeakIdentity testId : identities) { if (testId.getName().equals(identity.getName())) { return; } } identities.add(identity); if ((preferredIdentity == null) || (preferred)) { setPreferredPeakIdentity(identity); } } /** * @see net.sf.mzmine.datamodel.PeakListRow#addCompoundIdentity(net.sf.mzmine.datamodel.PeakIdentity) */ public synchronized void removePeakIdentity(PeakIdentity identity) { identities.remove(identity); if (preferredIdentity == identity) { if (identities.size() > 0) { PeakIdentity[] identitiesArray = identities.toArray(new PeakIdentity[0]); setPreferredPeakIdentity(identitiesArray[0]); } else preferredIdentity = null; } } /** * @see net.sf.mzmine.datamodel.PeakListRow#getPeakIdentities() */ public PeakIdentity[] getPeakIdentities() { return identities.toArray(new PeakIdentity[0]); } /** * @see net.sf.mzmine.datamodel.PeakListRow#getPreferredPeakIdentity() */ public PeakIdentity getPreferredPeakIdentity() { return preferredIdentity; } /** * @see net.sf.mzmine.datamodel.PeakListRow#setPreferredPeakIdentity(net.sf.mzmine.datamodel.PeakIdentity) */ public void setPreferredPeakIdentity(PeakIdentity identity) { if (identity == null) return; preferredIdentity = identity; if (!identities.contains(identity)) { identities.add(identity); } } @Override public void setPeakInformation(PeakInformation information) { this.information = information; } @Override public PeakInformation getPeakInformation() { return information; } /** * @see net.sf.mzmine.datamodel.PeakListRow#getDataPointMaxIntensity() */ public double getDataPointMaxIntensity() { return maxDataPointIntensity; } public boolean hasPeak(Feature peak) { return peaks.containsValue(peak); } public boolean hasPeak(RawDataFile file) { return peaks.containsKey(file); } /** * Returns the highest isotope pattern of a peak in this row */ public IsotopePattern getBestIsotopePattern() { Feature peaks[] = getPeaks(); Arrays.sort(peaks, new PeakSorter(SortingProperty.Height, SortingDirection.Descending)); for (Feature peak : peaks) { IsotopePattern ip = peak.getIsotopePattern(); if (ip != null) return ip; } return null; } /** * Returns the highest peak in this row */ public Feature getBestPeak() { Feature peaks[] = getPeaks(); Arrays.sort(peaks, new PeakSorter(SortingProperty.Height, SortingDirection.Descending)); if (peaks.length == 0) return null; return peaks[0]; } @Override public Scan getBestFragmentation() { Double bestTIC = 0.0; Scan bestScan = null; for (Feature peak : this.getPeaks()) { Double theTIC = 0.0; RawDataFile rawData = peak.getDataFile(); int bestScanNumber = peak.getMostIntenseFragmentScanNumber(); Scan theScan = rawData.getScan(bestScanNumber); if (theScan != null) { theTIC = theScan.getTIC(); } if (theTIC > bestTIC) { bestTIC = theTIC; bestScan = theScan; } } return bestScan; } // DorresteinLab edit /** * set the ID number */ public void setID(int id) { myID = id; return; } // End DorresteinLab edit // Gauthier edit /** * Update average values */ public void update() { this.calculateAverageValues(); } // End Gauthier edit } // End DorresteinLab edit
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.Collator; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableModel; import org.jdesktop.swingx.JXTable.GenericEditor; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.SortKey; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.util.AncientSwingTeam; import org.jdesktop.swingx.util.CellEditorReport; import org.jdesktop.swingx.util.PropertyChangeReport; /** * Test to exposed known issues of <code>JXTable</code>. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class JXTableIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTableIssues.class .getName()); /** * Issue 373-swingx: table must unsort column on sortable change. * */ public void testTableUnsortedColumnOnColumnSortableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.toggleSortOrder(0); assertTrue(table.getSortOrder(0).isSorted()); columnExt.setSortable(false); assertFalse("table must have unsorted column on sortable change", table.getSortOrder(0).isSorted()); } /** * Issue 372-swingx: table must cancel edit if column property * changes to not editable. * Here we test if the table is not editing after the change. */ public void testTableNotEditingOnColumnEditableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); columnExt.setEditable(false); assertFalse(table.isCellEditable(0, 0)); assertFalse("table must have terminated edit",table.isEditing()); } /** * Issue 372-swingx: table must cancel edit if column property * changes to not editable. * Here we test if the table actually canceled the edit. */ public void testTableCanceledEditOnColumnEditableChange() { JXTable table = new JXTable(10, 2); TableColumnExt columnExt = table.getColumnExt(0); table.editCellAt(0, 0); // sanity assertTrue(table.isEditing()); assertEquals(0, table.getEditingColumn()); TableCellEditor editor = table.getCellEditor(); CellEditorReport report = new CellEditorReport(); editor.addCellEditorListener(report); columnExt.setEditable(false); // sanity assertFalse(table.isCellEditable(0, 0)); assertEquals("editor must have fired canceled", 1, report.getCanceledEventCount()); assertEquals("editor must not have fired stopped",0, report.getStoppedEventCount()); } /** * a quick sanity test: reporting okay?. * (doesn't belong here, should test the tools * somewhere else) * */ public void testCellEditorFired() { JXTable table = new JXTable(10, 2); table.editCellAt(0, 0); CellEditorReport report = new CellEditorReport(); TableCellEditor editor = table.getCellEditor(); editor.addCellEditorListener(report); editor.cancelCellEditing(); assertEquals("total count must be equals to canceled", report.getCanceledEventCount(), report.getEventCount()); assertEquals("editor must have fired canceled", 1, report.getCanceledEventCount()); assertEquals("editor must not have fired stopped", 0, report.getStoppedEventCount()); report.clear(); assertEquals("canceled cleared", 0, report.getCanceledEventCount()); assertEquals("total cleared", 0, report.getStoppedEventCount()); // same cell, same editor table.editCellAt(0, 0); editor.stopCellEditing(); assertEquals("total count must be equals to stopped", report.getStoppedEventCount(), report.getEventCount()); assertEquals("editor must not have fired canceled", 0, report.getCanceledEventCount()); // JW: surprising... it really fires twice? assertEquals("editor must have fired stopped", 1, report.getStoppedEventCount()); } /** * Issue #359-swing: find suitable rowHeight. * * Text selection in textfield has row of metrics.getHeight. * Suitable rowHeight should should take border into account: * for a textfield that's the metrics height plus 2. */ public void testRowHeightFontMetrics() { JXTable table = new JXTable(10, 2); TableCellEditor editor = table.getCellEditor(1, 1); Component comp = table.prepareEditor(editor, 1, 1); assertEquals(comp.getPreferredSize().height, table.getRowHeight()); } /** * Issue??-swingx: turn off scrollbar doesn't work if the * table was initially in autoResizeOff mode. * * Problem with state management. * */ public void testHorizontalScrollEnabled() { JXTable table = new JXTable(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); assertEquals("horizontalScroll must be on", true, table.isHorizontalScrollEnabled()); table.setHorizontalScrollEnabled(false); assertEquals("horizontalScroll must be off", false, table.isHorizontalScrollEnabled()); } /** * we have a slight inconsistency in event values: setting the * client property to null means "false" but the event fired * has the newValue null. * * The way out is to _not_ set the client prop manually, always go * through the property setter. */ public void testClientPropertyNull() { JXTable table = new JXTable(); // sanity assert: setting client property set's property PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.putClientProperty("terminateEditOnFocusLost", null); assertFalse(table.isTerminateEditOnFocusLost()); assertEquals(1, report.getEventCount()); assertEquals(1, report.getEventCount("terminateEditOnFocusLost")); assertEquals(false, report.getLastNewValue("terminateEditOnFocusLost")); } /** * JXTable has responsibility to guarantee usage of * TableColumnExt comparator and update the sort if * the columns comparator changes. * */ public void testComparatorToPipelineDynamic() { JXTable table = new JXTable(new AncientSwingTeam()); TableColumnExt columnX = table.getColumnExt(0); table.toggleSortOrder(0); columnX.setComparator(Collator.getInstance()); // invalid assumption .. only the comparator must be used. // assertEquals("interactive sorter must be same as sorter in column", // columnX.getSorter(), table.getFilters().getSorter()); SortKey sortKey = SortKey.getFirstSortKeyForColumn(table.getFilters().getSortController().getSortKeys(), 0); assertNotNull(sortKey); assertEquals(columnX.getComparator(), sortKey.getComparator()); } /** * Issue #256-swingX: viewport - toggle track height must * revalidate. * * PENDING JW: the visual test looks okay - probably something wrong with the * test setup ... invoke doesn't help * */ public void testToggleTrackViewportHeight() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run trackViewportHeight - headless environment"); return; } final JXTable table = new JXTable(10, 2); table.setFillsViewportHeight(true); final Dimension tablePrefSize = table.getPreferredSize(); JScrollPane scrollPane = new JScrollPane(table); JXFrame frame = wrapInFrame(scrollPane, ""); frame.setSize(500, tablePrefSize.height * 2); frame.setVisible(true); assertEquals("table height be equal to viewport", table.getHeight(), scrollPane.getViewport().getHeight()); table.setFillsViewportHeight(false); assertEquals("table height be equal to table pref height", tablePrefSize.height, table.getHeight()); } public void testComponentAdapterCoordinates() { JXTable table = new JXTable(createAscendingModel(0, 10)); Object originalFirstRowValue = table.getValueAt(0,0); Object originalLastRowValue = table.getValueAt(table.getRowCount() - 1, 0); assertEquals("view row coordinate equals model row coordinate", table.getModel().getValueAt(0, 0), originalFirstRowValue); // sort first column - actually does not change anything order table.toggleSortOrder(0); // sanity asssert assertEquals("view order must be unchanged ", table.getValueAt(0, 0), originalFirstRowValue); // invert sort table.toggleSortOrder(0); // sanity assert assertEquals("view order must be reversed changed ", table.getValueAt(0, 0), originalLastRowValue); ComponentAdapter adapter = table.getComponentAdapter(); assertEquals("adapter filteredValue expects view coordinates", table.getValueAt(0, 0), adapter.getFilteredValueAt(0, 0)); // adapter coordinates are view coordinates adapter.row = 0; adapter.column = 0; assertEquals("adapter filteredValue expects view coordinates", table.getValueAt(0, 0), adapter.getValue()); } //-------------------- adapted jesse wilson: #223 /** * Enhancement: modifying (= filtering by resetting the content) should keep * selection * */ public void testModifyTableContentAndSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" }); Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" }); assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterModify); } /** * Enhancement: modifying (= filtering by resetting the content) should keep * selection */ public void testModifyXTableContentAndSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.setContents(new Object[] { "B", "C", "D", "F", "G", "H" }); Object[] selectedObjectsAfterModify = (new Object[] { "C", "D", "F" }); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterModify); } /** * test: deleting row below selection - should not change */ public void testDeleteRowBelowSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); Object[] selectedObjects = new Object[] { "C", "D", "E", "F" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1); assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); } /** * test: deleting last row in selection - should remove last item from selection. */ public void testDeleteLastRowInSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(7, 8); compare.xTable.getSelectionModel().setSelectionInterval(7, 8); Object[] selectedObjects = new Object[] { "H", "I" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjects); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjects); compare.tableModel.removeRow(compare.tableModel.getRowCount() - 1); Object[] selectedObjectsAfterDelete = new Object[] { "H" }; assertSelection(compare.tableModel, compare.table.getSelectionModel(), selectedObjectsAfterDelete); assertSelection(compare.tableModel, compare.xTable.getSelectionModel(), selectedObjectsAfterDelete); } private void assertSelection(TableModel tableModel, ListSelectionModel selectionModel, Object[] expected) { List selected = new ArrayList(); for(int r = 0; r < tableModel.getRowCount(); r++) { if(selectionModel.isSelectedIndex(r)) selected.add(tableModel.getValueAt(r, 0)); } List expectedList = Arrays.asList(expected); assertEquals("selected Objects must be as expected", expectedList, selected); } /** * Issue #393-swingx: localized NumberEditor. * * Playing ... Nearly working ... but not reliably. * */ public void interactiveFloatingPointEditor(){ DefaultTableModel model = new DefaultTableModel(10, 3) { @Override public Class<?> getColumnClass(int columnIndex) { if (columnIndex == 0) { return Double.class; } if (columnIndex == 1) { return Integer.class; } return Object.class; } }; JXTable table = new JXTable(model); table.setSurrendersFocusOnKeystroke(true); table.setValueAt(10.2f, 0, 0); table.setDefaultEditor(Double.class, new DoubleEditor()); table.setDefaultEditor(Float.class, new DoubleEditor()); showWithScrollingInFrame(table, "localized NumberFormatter in first float column?"); } public static class DoubleEditor extends GenericEditor { public DoubleEditor() { this((NumberFormat) null); } public DoubleEditor(NumberFormat format) { this(new JFormattedTextField(format != null ? format : NumberFormat.getInstance())); } public DoubleEditor(final JFormattedTextField textField) { super(textField); removeDefaultCellEditorDelegate(textField); System.out.println("listener count" + textField.getActionListeners().length); delegate = new EditorDelegate() { public void setValue(Object value) { textField.setValue(value); } public Object getCellEditorValue() { try { textField.commitEdit(); return String.valueOf(textField.getValue()); } catch (ParseException e) { // TODO Auto-generated catch block return null; } } }; textField.addActionListener(delegate); textField.setHorizontalAlignment(JTextField.RIGHT); } private void removeDefaultCellEditorDelegate(final JFormattedTextField textField) { ActionListener[] listeners = textField.getActionListeners(); for (int i = 0; i < listeners.length; i++) { if (listeners[i].getClass().getName().contains("DefaultCellEditor")) { textField.removeActionListener(listeners[i]); return; } } } } public void interactiveDeleteRowAboveSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(2, 5); compare.xTable.getSelectionModel().setSelectionInterval(2, 5); JComponent box = createContent(compare, createRowDeleteAction(0, compare.tableModel)); JFrame frame = wrapInFrame(box, "delete above selection"); frame.setVisible(true); } public void interactiveDeleteRowBelowSelection() { CompareTableBehaviour compare = new CompareTableBehaviour(new Object[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" }); compare.table.getSelectionModel().setSelectionInterval(6, 7); compare.xTable.getSelectionModel().setSelectionInterval(6, 7); JComponent box = createContent(compare, createRowDeleteAction(-1, compare.tableModel)); JFrame frame = wrapInFrame(box, "delete below selection"); frame.setVisible(true); } /** * Issue #370-swingx: "jumping" selection while dragging. * */ public void interactiveExtendSelection() { final UpdatingTableModel model = new UpdatingTableModel(); JXTable table = new JXTable(model); // Swing Timer - EDT in Timer ActionListener l = new ActionListener() { int i = 0; public void actionPerformed(ActionEvent e) { model.updateCell(i++ % 10); } }; Timer timer = new Timer(1000, l); timer.start(); JXFrame frame = wrapWithScrollingInFrame(table, "#370 - extend selection by dragging"); frame.setVisible(true); } /** * Simple model for use in continous update tests. * Issue #370-swingx: jumping selection on dragging. */ private class UpdatingTableModel extends AbstractTableModel { private int[][] data = new int[10][5]; public UpdatingTableModel() { for (int row = 0; row < data.length; row++) { fillRow(row); } } public int getRowCount() { return 10; } public int getColumnCount() { return 5; } public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } /** * update first column of row on EDT. * @param row */ public void invokeUpdateCell(final int row) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateCell(row); } }); } /** * update first column of row. Sorting on any column except the first * doesn't change row sequence - shouldn't interfere with selection * extension. * * @param row */ public void updateCell(final int row) { updateCell(row, 0); fireTableCellUpdated(row, 0); } public void fillRow(int row) { for (int col = 0; col < data[row].length; col++) { updateCell(row, col); } } /** * Fills the given cell with random value. * @param row * @param col */ private void updateCell(int row, int col) { data[row][col] = (int) Math.round(Math.random() * 200); } } /** * Issue #282-swingx: compare disabled appearance of * collection views. * */ public void interactiveDisabledCollectionViews() { final JXTable table = new JXTable(new AncientSwingTeam()); table.setEnabled(false); final JXList list = new JXList(new String[] {"one", "two", "and something longer"}); list.setEnabled(false); final JXTree tree = new JXTree(new FileSystemModel()); tree.setEnabled(false); JComponent box = Box.createHorizontalBox(); box.add(new JScrollPane(table)); box.add(new JScrollPane(list)); box.add(new JScrollPane(tree)); JXFrame frame = wrapInFrame(box, "disabled collection views"); AbstractAction action = new AbstractAction("toggle disabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); list.setEnabled(!list.isEnabled()); tree.setEnabled(!tree.isEnabled()); } }; addAction(frame, action); frame.setVisible(true); } public void interactiveDataChanged() { final DefaultTableModel model = createAscendingModel(0, 10, 5, false); JXTable xtable = new JXTable(model); xtable.setRowSelectionInterval(0, 0); JTable table = new JTable(model); table.setRowSelectionInterval(0, 0); AbstractAction action = new AbstractAction("fire dataChanged") { public void actionPerformed(ActionEvent e) { model.fireTableDataChanged(); } }; JXFrame frame = wrapWithScrollingInFrame(xtable, table, "selection after data changed"); addAction(frame, action); frame.setVisible(true); } private JComponent createContent(CompareTableBehaviour compare, Action action) { JComponent box = new JPanel(new BorderLayout()); box.add(new JScrollPane(compare.table), BorderLayout.WEST); box.add(new JScrollPane(compare.xTable), BorderLayout.EAST); box.add(new JButton(action), BorderLayout.SOUTH); return box; } private Action createRowDeleteAction(final int row, final ReallySimpleTableModel simpleTableModel) { Action delete = new AbstractAction("DeleteRow " + ((row < 0) ? "last" : "" + row)) { public void actionPerformed(ActionEvent e) { int rowToDelete = row; if (row < 0) { rowToDelete = simpleTableModel.getRowCount() - 1; } if ((rowToDelete < 0) || (rowToDelete >= simpleTableModel.getRowCount())) { return; } simpleTableModel.removeRow(rowToDelete); if (simpleTableModel.getRowCount() == 0) { setEnabled(false); } } }; return delete; } public static class CompareTableBehaviour { public ReallySimpleTableModel tableModel; public JTable table; public JXTable xTable; public CompareTableBehaviour(Object[] model) { tableModel = new ReallySimpleTableModel(); tableModel.setContents(model); table = new JTable(tableModel); xTable = new JXTable(tableModel); table.getColumnModel().getColumn(0).setHeaderValue("JTable"); xTable.getColumnModel().getColumn(0).setHeaderValue("JXTable"); } }; /** * A one column table model where all the data is in an Object[] array. */ static class ReallySimpleTableModel extends AbstractTableModel { private List contents = new ArrayList(); public void setContents(List contents) { this.contents.clear(); this.contents.addAll(contents); fireTableDataChanged(); } public void setContents(Object[] contents) { setContents(Arrays.asList(contents)); } public void removeRow(int row) { contents.remove(row); fireTableRowsDeleted(row, row); } public int getRowCount() { return contents.size(); } public int getColumnCount() { return 1; } public Object getValueAt(int row, int column) { if(column != 0) throw new IllegalArgumentException(); return contents.get(row); } } /** * returns a tableModel with count rows filled with * ascending integers in first column * starting from startRow. * @param startRow the value of the first row * @param rowCount the number of rows * @return */ private DefaultTableModel createAscendingModel(int startRow, final int rowCount, final int columnCount, boolean fillLast) { DefaultTableModel model = new DefaultTableModel(rowCount, columnCount) { public Class getColumnClass(int column) { Object value = rowCount > 0 ? getValueAt(0, column) : null; return value != null ? value.getClass() : super.getColumnClass(column); } }; int filledColumn = fillLast ? columnCount - 1 : 0; for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, filledColumn); } return model; } private DefaultTableModel createAscendingModel(int startRow, int count) { DefaultTableModel model = new DefaultTableModel(count, 5); for (int i = 0; i < model.getRowCount(); i++) { model.setValueAt(new Integer(startRow++), i, 0); } return model; } /** * Issue #??: JXTable pattern search differs from * PatternHighlighter/Filter. * * Fixing the issue (respect the pattern as is by calling * pattern.matcher().matches instead of the find()) must * make sure that the search methods taking the string * include wildcards. * * Note: this method passes as long as the issue is not * fixed! * * TODO: check status! */ public void testWildCardInSearchByString() { JXTable table = new JXTable(createAscendingModel(0, 11)); int row = 1; String lastName = table.getValueAt(row, 0).toString(); int found = table.getSearchable().search(lastName, -1); assertEquals("found must be equal to row", row, found); found = table.getSearchable().search(lastName, found); assertEquals("search must succeed", 10, found); } public static void main(String args[]) { JXTableIssues test = new JXTableIssues(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Siz.*"); // test.runInteractiveTests("interactive.*Render.*"); // test.runInteractiveTests("interactive.*Toggle.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } }
package net.zyuiop.permissions.bungee; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; import net.zyuiop.crosspermissions.api.PermissionsAPI; import net.zyuiop.crosspermissions.api.database.JedisDatabase; import net.zyuiop.crosspermissions.api.database.JedisSentinelDatabase; import net.zyuiop.crosspermissions.api.rawtypes.RawPlayer; import net.zyuiop.crosspermissions.api.rawtypes.RawPlugin; import java.io.File; import java.nio.file.Files; import java.util.*; import java.util.concurrent.TimeUnit; public class PermissionBungee extends Plugin implements RawPlugin { public static PermissionsAPI api; public void onEnable() { // Registering listener if (!getDataFolder().exists()) getDataFolder().mkdir(); String defaultGroup = null; try { File file = new File(getDataFolder(), "config.yml"); if (!file.exists()) { Files.copy(getResourceAsStream("config.yml"), file.toPath()); } Configuration config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file); defaultGroup = config.getString("default-group"); if (config.getBoolean("redis-sentinel.enabled", false)) { logInfo("Trying to load API with database mode : REDIS SENTINEL."); String master = config.getString("redis-sentinel.master", null); String auth = config.getString("redis-sentinel.auth", null); List<String> ips = config.getStringList("redis-sentinel.sentinels"); if (master == null || auth == null || ips == null) { logSevere("Configuration is not complete. Plugin failed to load."); return; } else { try { Set<String> iplist = new HashSet<>(); iplist.addAll(ips); JedisSentinelDatabase database = new JedisSentinelDatabase(iplist, master, auth); api = new PermissionsAPI(this, config.getString("default-group"), database); } catch (Exception e) { logSevere("Configuration is not correct. Plugin failed to load."); e.printStackTrace(); return; } } } else if (config.getBoolean("redis.enabled", false)) { logInfo("Trying to load API with database mode : REDIS."); String address = config.getString("redis.address"); String auth = config.getString("redis.auth"); int port = config.getInt("redis.port", 6379); if (address == null || auth == null) { logSevere("Configuration is not complete. Plugin failed to load."); return; } else { try { JedisDatabase database = new JedisDatabase(address, port, auth); api = new PermissionsAPI(this, config.getString("default-group"), database); } catch (Exception e) { logSevere("Configuration is not correct. Plugin failed to load."); e.printStackTrace(); return; } } } else { logSevere("ERROR : NO DATABASE BACKEND ENABLED."); logSevere("To use this plugin, you have to enable redis or redis sentinel"); return; } } catch (Exception e) { this.getLogger().info("An error occured while trying to load configuration."); this.getLogger().info("API will be loaded with a null default group."); } this.getProxy().getPluginManager().registerCommand(this, new CommandRefresh(api)); this.getProxy().getPluginManager().registerListener(this, new PlayerListener(this)); } @Override public void logSevere(String s) { this.getLogger().severe(s); } @Override public void logWarning(String s) { this.getLogger().warning(s); } @Override public void logInfo(String s) { this.getLogger().info(s); } @Override public void runRepeatedTaskAsync(Runnable runnable, long delay, long before) { this.getProxy().getScheduler().schedule(this, runnable, before * 50, delay * 50, TimeUnit.MILLISECONDS); // Un tick = 50 ms } @Override public void runAsync(Runnable runnable) { this.getProxy().getScheduler().runAsync(this, runnable); } @Override public boolean isOnline(UUID uuid) { return (getProxy().getPlayer(uuid) != null); } @Override public RawPlayer getPlayer(UUID player) { return new VirtPlayer(player); } @Override public UUID getPlayerId(String name) { ProxiedPlayer player = getProxy().getPlayer(name); return (player == null) ? null : player.getUniqueId(); } @Override public String getPlayerName(UUID id) { ProxiedPlayer player = getProxy().getPlayer(id); return (player == null) ? null : player.getName(); } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Locale; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.UIManager; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.test.PropertyChangeReport; import org.jdesktop.test.TestUtils; /** * Test to expose known issues around <code>Locale</code> setting. * * Ideally, there would be at least one failing test method per open * Issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour. * * @author Jeanette Winzenburg */ public class XLocalizeTest extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(XLocalizeTest.class .getName()); private static final Locale A_LOCALE = Locale.FRENCH; private static final Locale OTHER_LOCALE = Locale.GERMAN; private Locale originalLocale; // test scope is static anyway... static { // force the addon to load LookAndFeelAddons.getAddon(); } public static void main(String[] args) { // setSystemLF(true); XLocalizeTest test = new XLocalizeTest(); try { test.runInteractiveTests(); // test.runInteractiveTests("interactive.*TwoTable.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @Override protected void setUp() throws Exception { originalLocale = Locale.getDefault(); super.setUp(); } @Override protected void tearDown() throws Exception { Locale.setDefault(originalLocale); super.tearDown(); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... dooohhh. * * Here: test JXDialog. */ /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... * * Here: test FindPanel */ public void testLocaleDialogPropertyNotificationInListener() { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run localeDialogPropertyNotificationInListener - headless environment"); return; } final String prefix = PatternModel.SEARCH_PREFIX; final JXFindPanel findPanel = new JXFindPanel(); final JXDialog dialog = new JXDialog(findPanel); final String titleKey = AbstractPatternPanel.SEARCH_TITLE; // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... findPanel.addNotify(); String name = dialog.getTitle(); String uiValue = UIManagerExt.getString(prefix + titleKey, findPanel .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(dialog); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity // wrong assumption: find widgets name is changed as well // assertTrue("locale property changed, instead: " + evt.getPropertyName(), "locale".equals(evt.getPropertyName())); if (!"locale".equals(evt.getPropertyName())) return; String altUIValue = UIManagerExt.getString(prefix + titleKey, alternative); String altName = dialog.getTitle(); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; dialog.addPropertyChangeListener(report); PropertyChangeReport r = new PropertyChangeReport(); dialog.addPropertyChangeListener(r); dialog.setLocale(alternative); // sanity: guarantee that we got a locale change notification assertEquals(1, r.getEventCount("locale")); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... dooohhh. * * Here: test FindBar. */ public void testLocaleFindBarPropertyNotificationInListener() { final String prefix = PatternModel.SEARCH_PREFIX; final JXFindBar findPanel = new JXFindBar(); final String actionCommand = JXFindBar.FIND_NEXT_ACTION_COMMAND; // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... findPanel.addNotify(); final Action action = findPanel.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, findPanel .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(findPanel); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity // assertTrue("locale property changed", "locale".equals(evt.getPropertyName())); if (!"locale".equals(evt.getPropertyName())) return; String altUIValue = UIManagerExt.getString(prefix + actionCommand, alternative); String altName = (String) action.getValue(Action.NAME); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; PropertyChangeReport r = new PropertyChangeReport(); findPanel.addPropertyChangeListener(r); findPanel.setLocale(alternative); assertEquals(1, r.getEventCount("locale")); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... * * Here: test FindPanel */ public void testLocaleFindPanelPropertyNotificationInListener() { final String prefix = PatternModel.SEARCH_PREFIX; final JXFindPanel findPanel = new JXFindPanel(); final String actionCommand = AbstractPatternPanel.MATCH_ACTION_COMMAND; // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... findPanel.addNotify(); final Action action = findPanel.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, findPanel .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(findPanel); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity // wrong assumption: find widgets name is changed as well // assertTrue("locale property changed, instead: " + evt.getPropertyName(), "locale".equals(evt.getPropertyName())); if (!"locale".equals(evt.getPropertyName())) return; String altUIValue = UIManagerExt.getString(prefix + actionCommand, alternative); String altName = (String) action.getValue(Action.NAME); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; findPanel.addPropertyChangeListener(report); PropertyChangeReport r = new PropertyChangeReport(); findPanel.addPropertyChangeListener(r); findPanel.setLocale(alternative); assertEquals(1, r.getEventCount("locale")); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... dooohhh. */ public void testLocaleTablePropertyNotification() { String prefix = "JXTable."; JXTable table = new JXTable(10, 2); String actionCommand = JXTable.HORIZONTALSCROLL_ACTION_COMMAND; Action action = table.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, table .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); Locale old = table.getLocale(); Locale alternative = getAlternativeLocale(table); PropertyChangeReport report = new PropertyChangeReport(); table.addPropertyChangeListener(report); table.setLocale(alternative); TestUtils.assertPropertyChangeEvent(report, "locale", old, alternative); } /** * test correct PropertyChangeNotification: must fire after * all internal state is set ... * * Here: test JXTable. */ public void testLocaleTablePropertyNotificationInListener() { final String prefix = "JXTable."; final JXTable table = new JXTable(10, 2); final String actionCommand = JXTable.HORIZONTALSCROLL_ACTION_COMMAND; final Action action = table.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, table .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); final Locale alternative = getAlternativeLocale(table); PropertyChangeListener report = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // sanity assertTrue("locale property changed", "locale".equals(evt.getPropertyName())); String altUIValue = UIManagerExt.getString(prefix + actionCommand, alternative); String altName = (String) action.getValue(Action.NAME); assertEquals("name must be updated before fire propertyChange", altUIValue, altName); }}; table.addPropertyChangeListener(report); table.setLocale(alternative); } private Locale getAlternativeLocale(final Component table) { Locale alternative = OTHER_LOCALE; if (alternative.getLanguage().equals(table.getLocale().getLanguage())) { alternative = A_LOCALE; } return alternative; } /** * Issue #635-swingx: find widgets must support dynamic localization * Here: test findPanel's actions (incomplete ..) */ public void testLocaleFindPanel() { JXFindPanel panel = new JXFindPanel(); // JW: arrrgghh ... dirty! Consequence of dirty initialization // of AbstractPatternPanel subclasses ... panel.addNotify(); String prefix = PatternModel.SEARCH_PREFIX; assertLocaleActionUpdate(panel, prefix, AbstractPatternPanel.MATCH_ACTION_COMMAND); assertLocaleActionUpdate(panel, prefix, JXFindPanel.FIND_NEXT_ACTION_COMMAND); assertLocaleActionUpdate(panel, prefix, JXFindPanel.FIND_PREVIOUS_ACTION_COMMAND); } /** * Issue #459-swingx: JXTable setLocale doesn't update localized column * control properties. <p> * * Pass/fail expectation: * <ul> * <li> fails always with jdk5 independent of LookAndFeelAddon resource * bundle registration. * <li> fails with jdk6 and LookAndFeelAddon copy resource bundle values. * <li> passes with jdk6 and LookAndFeelAddon addResourceBundle. * </ul> */ public void testLocaleColumnControl() { String prefix = "JXTable."; JXTable table = new JXTable(10, 2); assertLocaleActionUpdate(table, prefix, JXTable.HORIZONTALSCROLL_ACTION_COMMAND); assertLocaleActionUpdate(table, prefix, JXTable.PACKALL_ACTION_COMMAND); assertLocaleActionUpdate(table, prefix, JXTable.PACKSELECTED_ACTION_COMMAND); } private void assertLocaleActionUpdate(JComponent table, String prefix, String actionCommand) { Action action = table.getActionMap().get(actionCommand); String name = (String) action.getValue(Action.NAME); String uiValue = UIManagerExt.getString(prefix + actionCommand, table .getLocale()); // sanity assertNotNull(uiValue); assertEquals(name, uiValue); Locale alternative = OTHER_LOCALE; if (alternative.getLanguage().equals(table.getLocale().getLanguage())) { alternative = A_LOCALE; } table.setLocale(alternative); String altUIValue = UIManagerExt.getString(prefix + actionCommand, table.getLocale()); // sanity assertNotNull(altUIValue); // sanity to track unexpected failure during refactoring assertFalse("new uiValue must be different: " + uiValue + "/" + altUIValue, uiValue.equals(altUIValue)); String altName = (String) action.getValue(Action.NAME); // here are the real asserts assertFalse("new action name must be different: " + name + "/" + altName, name.equals(altName)); assertEquals(altName, altUIValue); } public void testGetLocaleUIDefaults() { String key = "JXTable.column.packAll"; Object alternativeValue = UIManagerExt.getString(key, OTHER_LOCALE); // sanity - the value must be available assertNotNull(alternativeValue); Object defaultValue = UIManagerExt.getString(key, A_LOCALE); // sanity - the value must be available assertNotNull(defaultValue); assertFalse("values must be different: " + defaultValue + "/" + alternativeValue, defaultValue.equals(alternativeValue)); } /** * Issue #459-swingx: columnControl properties not updated on locale setting. * */ public void interactiveLocaleColumnControl() { final JXTable table = new JXTable(10, 4); table.setColumnControlVisible(true); table.getColumnExt(0).setTitle(table.getLocale().getLanguage()); Action toggleLocale = new AbstractActionExt("toggleLocale") { public void actionPerformed(ActionEvent e) { Locale old = table.getLocale(); table.setLocale(old == A_LOCALE ? OTHER_LOCALE : A_LOCALE); table.getColumnExt(0).setTitle(table.getLocale().getLanguage()); } }; JXFrame frame = wrapWithScrollingInFrame(table, "toggle locale on table - column control not updated"); addAction(frame, toggleLocale); frame.setVisible(true); } /** * Issue #459-swingx: columnControl properties not updated on locale setting. * * */ public void interactiveLocaleColumnControlTwoTables() { final JXTable table = new JXTable(10, 4); table.setColumnControlVisible(true); table.getColumnExt(0).setTitle(table.getLocale().getLanguage()); JXTable other = new JXTable(10, 4); other.setColumnControlVisible(true); other.setLocale(A_LOCALE); other.getColumnExt(0).setTitle(other.getLocale().getLanguage()); JXFrame frame = wrapWithScrollingInFrame(table, other, "different locals: de <--> vs fr"); Action toggleLocale = new AbstractActionExt("toggle useFindBar") { private boolean useFindBar; public void actionPerformed(ActionEvent e) { useFindBar = !useFindBar; SearchFactory.getInstance().setUseFindBar(useFindBar); } }; addAction(frame, toggleLocale); addMessage(frame, "Find panel/bar should be localized per-table"); frame.pack(); frame.setVisible(true); } }
package nl.tudelft.lifetiles.tree; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; /*** * a tree to store the relation between samples. * * @author Albert Smit * */ public class PhylogeneticTreeItem { /** * Used to give each node a unique id. */ private static AtomicInteger nextID = new AtomicInteger(); /** * The parent node, null when this node is the root node. */ private PhylogeneticTreeItem parent; /** * The list of children of this node. */ private List<PhylogeneticTreeItem> children; /** * The name of the sample. This is an optional field. */ private String name; /** * The distance between samples. This is an optinal field. */ private double distance; /** * A unique id for each node. */ private int id; /** * Creates a new PhylogeneticTreeItem. Will initialize the ArrayList storing * the children and assign a new and unique id to the node. */ public PhylogeneticTreeItem() { children = new ArrayList<PhylogeneticTreeItem>(); this.id = nextID.incrementAndGet(); } /** * Returns a String representation of the PhylogeneticTreeItem. The String * will have the following format: <Node: id, name: name, Distance: * distance, parent: parentID> or when the PhylogeneticTreeItem has no * parent: <Node: id, Name: name, Distance: distance, ROOT> * * @return the String version of the object. */ public final String toString() { String result = "<Node: " + id + ", Name: " + name + ", Distance: " + distance; if (parent != null) { result += ", parent: " + parent.getId(); } else { result += ", ROOT "; } return result + ">"; } /** * Adds a child to the PhylogeneticTreeItem. This method will add the * PhylogeneticTreeItem child to the ArrayList storing the children of this * node * * @param child * the PhylogeneticTreeItem that needs to be added to the tree */ public final void addChild(final PhylogeneticTreeItem child) { children.add(child); } /** * Returns the ArrayList of children. * * @return the ArrayList containing all children of this node */ public final List<PhylogeneticTreeItem> getChildren() { return children; } /** * Sets the parent to be the node passed to the method This method will set * the parent and also add itself to the list of children in the parent * node. * * @param parentNode * the node that will be this nodes parent */ public final void setParent(final PhylogeneticTreeItem parentNode) { this.parent = parentNode; this.parent.addChild(this); } /** * Returns this nodes parent node. * * @return the PhylogeneticTreeItem that is this nodes parent */ public final PhylogeneticTreeItem getParent() { return parent; } /** * Calculates a hash for the tree. */ @Override public final int hashCode() { final int prime = 31; int result = 1; result = prime * result + children.hashCode(); long temp; temp = Double.doubleToLongBits(distance); result = prime * result + (int) (temp ^ (temp >>> 32)); if (name != null) { result = prime * result + name.hashCode(); } else { result = prime * result; } return result; } /** * compares this with another Object. returns true when both are the same. * two PhylogeneticTreeItems are considered the same when: * * 1. both have the same name or both have no name * 2. both have the same distance * 3. both have the same children, order does not matter * * @param other * the object to compare with * * @return true if both are the same, otherwise false */ @Override public final boolean equals(final Object other) { if (other == null) { return false; } else if (other == this) { return true; } else if (other instanceof PhylogeneticTreeItem) { PhylogeneticTreeItem that = (PhylogeneticTreeItem) other; boolean result; // compare name if (name == null && that.getName() == null) { // both are empty and thus the same result = true; } else if (name == null) { // the names are not both empty so not the same result = false; } else { // name is not null check if it is the same result = name.equals(that.getName()); } // compare distance result = result && (distance == that.getDistance()); // compare children for (PhylogeneticTreeItem child : children) { result = result && that.getChildren().contains(child); } return result; } else { return false; } } /** * Returns the name stored in this node. name is an optional property, so * this method can return null. * * @return the name of this node */ public final String getName() { return name; } /** * Set this nodes name to the passed String. * * @param n * the name of this node */ public final void setName(final String n) { this.name = n; } /** * Returns the distance stored in this node. distance is an optional * property, so the distance can often be 0.0. * * @return the distance of this node */ public final double getDistance() { return distance; } /** * Sets this nodes distance to the passed double. * * @param d * the distance between the nodes */ public final void setDistance(final double d) { this.distance = d; } /** * Returns the Id of this node. because name and distance are optional this * provides an easy way of identifying nodes * * @return the unique id of this PhylogeneticTreeItem */ public final int getId() { return id; } }
package nl.tudelft.lifetiles.tree; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; /*** * a tree to store the relation between samples. * * @author Albert Smit * */ public class PhylogeneticTreeItem { /** * Used to give each node a unique id. */ private static AtomicInteger nextID = new AtomicInteger(); /** * The parent node, null when this node is the root node. */ private PhylogeneticTreeItem parent; /** * The list of children of this node. */ private ArrayList<PhylogeneticTreeItem> children; /** * The name of the sample. This is an optional field. */ private String name; /** * The distance between samples. This is an optinal field. */ private double distance; /** * A unique id for each node. */ private int id; /** * Creates a new PhylogeneticTreeItem. Will initialize the ArrayList storing * the children and assign a new and unique id to the node. */ public PhylogeneticTreeItem() { children = new ArrayList<PhylogeneticTreeItem>(); this.id = nextID.incrementAndGet(); } /** * Returns a String representation of the PhylogeneticTreeItem. The String * will have the following format: <Node: id, name: name, Distance: * distance, parent: parentID> or when the PhylogeneticTreeItem has no * parent: <Node: id, Name: name, Distance: distance, ROOT> * * @return the String version of the object. */ public final String toString() { String result = "<Node: " + id + ", Name: " + name + ", Distance: " + distance; if (parent != null) { result += ", parent: " + parent.getId(); } else { result += ", ROOT "; } return result + ">"; } /** * Adds a child to the PhylogeneticTreeItem. This method will add the * PhylogeneticTreeItem child to the ArrayList storing the children of this * node * * @param child * the PhylogeneticTreeItem that needs to be added to the tree */ public final void addChild(final PhylogeneticTreeItem child) { children.add(child); } /** * Returns the ArrayList of children. * * @return the ArrayList containing all children of this node */ public final ArrayList<PhylogeneticTreeItem> getChildren() { return children; } /** * Sets the parent to be the node passed to the method This method will set * the parent and also add itself to the list of children in the parent * node. * * @param parentNode * the node that will be this nodes parent */ public final void setParent(final PhylogeneticTreeItem parentNode) { this.parent = parentNode; this.parent.addChild(this); } /** * Returns this nodes parent node. * * @return the PhylogeneticTreeItem that is this nodes parent */ public final PhylogeneticTreeItem getParent() { return parent; } /** * Calculates a hash for the tree. */ @Override public final int hashCode() { final int prime = 31; int result = 1; result = prime * result + children.hashCode(); long temp; temp = Double.doubleToLongBits(distance); result = prime * result + (int) (temp ^ (temp >>> 32)); if (name != null) { result = prime * result + name.hashCode(); } else { result = prime * result; } return result; } /** * compares this with another Object. returns true when both are the same. * two PhylogeneticTreeItems are considered the same when: * * 1. both have the same name or both have no name * 2. both have the same distance * 3. both have the same children, order does not matter * * @param other * the object to compare with * * @return true if both are the same, otherwise false */ @Override public final boolean equals(final Object other) { if (other == null) { return false; } else if (other == this) { return true; } else if (other instanceof PhylogeneticTreeItem) { PhylogeneticTreeItem that = (PhylogeneticTreeItem) other; boolean result; // compare name if (name == null && that.getName() == null) { // both are empty and thus the same result = true; } else if (name == null) { // the names are not both empty so not the same result = false; } else { // name is not null check if it is the same result = name.equals(that.getName()); } // compare distance result = result && (distance == that.getDistance()); // compare children for (PhylogeneticTreeItem child : children) { result = result && that.getChildren().contains(child); } return result; } else { return false; } } /** * Returns the name stored in this node. name is an optional property, so * this method can return null. * * @return the name of this node */ public final String getName() { return name; } /** * Set this nodes name to the passed String. * * @param n * the name of this node */ public final void setName(final String n) { this.name = n; } /** * Returns the distance stored in this node. distance is an optional * property, so the distance can often be 0.0. * * @return the distance of this node */ public final double getDistance() { return distance; } /** * Sets this nodes distance to the passed double. * * @param d * the distance between the nodes */ public final void setDistance(final double d) { this.distance = d; } /** * Returns the Id of this node. because name and distance are optional this * provides an easy way of identifying nodes * * @return the unique id of this PhylogeneticTreeItem */ public final int getId() { return id; } }
package org.agmip.translators.dssat; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * DSSAT Run File I/O API Class * * @author Meng Zhang * @version 1.0 */ public class DssatRunFileOutput extends DssatCommonOutput implements DssatBtachFile { /** * DSSAT Run File Output method * * @param arg0 file output path * @param results array of data holder object */ public void writeFile(String arg0, ArrayList<HashMap> results) { writeFile(arg0, new HashMap()); } /** * DSSAT Run File Output method * * @param arg0 file output path * @param result data holder object */ @Override public void writeFile(String arg0, Map result) { // Initial variables BufferedWriter bwR; // output object try { // Initial BufferedWriter arg0 = revisePath(arg0); outputFile = new File(arg0 + "Run.bat"); bwR = new BufferedWriter(new FileWriter(outputFile)); // Output Run File bwR.write("C:\\dssat45\\dscsm045 b dssbatch.v45\r\n"); bwR.write("@echo off\r\n"); bwR.write("pause\r\n"); bwR.write("exit\r\n"); // Output finish bwR.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package org.cobaltians.cobalt.fragments; import android.content.ComponentName; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import org.cobaltians.cobalt.Cobalt; import org.cobaltians.cobalt.R; import org.cobaltians.cobalt.activities.CobaltActivity; import org.cobaltians.cobalt.customviews.CobaltSwipeRefreshLayout; import org.cobaltians.cobalt.customviews.IScrollListener; import org.cobaltians.cobalt.customviews.OverScrollingWebView; import org.cobaltians.cobalt.database.LocalStorageJavaScriptInterface; import org.cobaltians.cobalt.plugin.CobaltPluginManager; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NavUtils; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.*; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import java.util.ArrayList; import java.util.Calendar; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * {@link Fragment} allowing interactions between native and Web * * @author Diane Moebs */ public abstract class CobaltFragment extends Fragment implements IScrollListener, SwipeRefreshLayout.OnRefreshListener { // TAG protected final static String TAG = CobaltFragment.class.getSimpleName(); protected Context mContext; protected ViewGroup mWebViewContainer; protected OverScrollingWebView mWebView; protected CobaltSwipeRefreshLayout mSwipeRefreshLayout; protected Handler mHandler = new Handler(); private ArrayList<JSONObject> mWaitingJavaScriptCallsQueue = new ArrayList<JSONObject>(); private boolean mPreloadOnCreate = true; private boolean mCobaltIsReady = false; private boolean mIsInfiniteScrollRefreshing = false; private CobaltPluginManager mPluginManager; private boolean mAllowCommit; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPluginManager = CobaltPluginManager.getInstance(mContext); setRetainInstance(true); mAllowCommit = true; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); try { View view = inflater.inflate(getLayoutToInflate(), container, false); setUpViews(view); setUpListeners(); return view; } catch (InflateException e) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCreateView: InflateException"); e.printStackTrace(); } return null; } /** * Restores Web view state. */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mWebView != null) { mWebView.restoreState(savedInstanceState); } } @Override public void onStart() { super.onStart(); addWebView(); preloadContent(); } @Override public void onResume() { mAllowCommit = true; super.onResume(); JSONObject data = ((CobaltActivity) mContext).getDataNavigation(); sendEvent(Cobalt.JSEventOnPageShown, data, null); ((CobaltActivity) mContext).setDataNavigation(null); } @Override public void onStop() { super.onStop(); // Fragment will rotate or be destroyed, so we don't preload content defined in fragment's arguments again mPreloadOnCreate = false; removeWebViewFromPlaceholder(); } /** * Saves the Web view state. */ @Override public void onSaveInstanceState(Bundle outState) { mAllowCommit = false; super.onSaveInstanceState(outState); if (mWebView != null) { mWebView.saveState(outState); } } @Override public void onDestroy() { super.onDestroy(); mPluginManager.onFragmentDestroyed(mContext, this); } /** * This method should be overridden in subclasses. * @return Layout id inflated by this fragment */ protected int getLayoutToInflate() { if (isPullToRefreshActive()) return R.layout.fragment_refresh_cobalt; else return R.layout.fragment_cobalt; } /** * Sets up the fragment's properties according to the inflated layout. * This method should be overridden in subclasses. * @param rootView: parent view */ protected void setUpViews(View rootView) { mWebViewContainer = ((ViewGroup) rootView.findViewById(getWebViewContainerId())); if (isPullToRefreshActive()) { mSwipeRefreshLayout = ((CobaltSwipeRefreshLayout) rootView.findViewById(getSwipeRefreshContainerId())); if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setColorSchemeResources(R.color.cobalt_blue_bright, R.color.cobalt_blue_light, R.color.cobalt_blue_dark, R.color.cobalt_blue_light); } else if (Cobalt.DEBUG) Log.w(Cobalt.TAG, TAG + " - setUpViews: SwipeRefresh container not found!"); } if (Cobalt.DEBUG && mWebViewContainer == null) Log.w(Cobalt.TAG, TAG + " - setUpViews: WebView container not found!"); } protected int getWebViewContainerId() { return R.id.web_view_container; } protected int getSwipeRefreshContainerId() { return R.id.swipe_refresh_container; } /**c * Sets up listeners for components inflated from the given layout and the parent view. * This method should be overridden in subclasses. */ protected void setUpListeners() { } /** * Called to add the Web view in the placeholder (and creates it if necessary). * This method SHOULD NOT be overridden in subclasses. */ protected void addWebView() { if (mWebView == null) { mWebView = new OverScrollingWebView(mContext); setWebViewSettings(this); if (isPullToRefreshActive() && mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setOnRefreshListener(this); mSwipeRefreshLayout.setWebView(mWebView); } } if (mWebViewContainer != null) { mWebViewContainer.addView(mWebView); } } protected void setWebViewSettings(CobaltFragment javascriptInterface) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) mWebView.setLayerType(View.LAYER_TYPE_HARDWARE ,null); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) mWebView.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS); mWebView.setScrollListener(this); mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY); // Enables JS WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); // Enables and setups JS local storage webSettings.setDomStorageEnabled(true); webSettings.setDatabaseEnabled(true); //@deprecated since API 19. But calling this method have simply no effect for API 19+ webSettings.setDatabasePath(mContext.getFilesDir().getParentFile().getPath() + "/databases/"); // Enables cross-domain calls for Ajax allowAjax(); // Fix some focus issues on old devices like HTC Wildfire // keyboard was not properly showed on input touch. mWebView.requestFocus(View.FOCUS_DOWN); mWebView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (! view.hasFocus()) { view.requestFocus(); } break; default: break; } return false; } }); //Enable Webview debugging from chrome desktop if (Cobalt.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); } // Add JavaScript interface so JavaScript can call native functions. mWebView.addJavascriptInterface(javascriptInterface, "Android"); mWebView.addJavascriptInterface(new LocalStorageJavaScriptInterface(mContext), "LocalStorage"); WebViewClient webViewClient = new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { executeWaitingCalls(); } }; mWebView.setWebViewClient(webViewClient); } @SuppressLint("NewApi") private void allowAjax() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { // TODO: see how to restrict only to local files mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true); } } private void preloadContent() { String page = (getPage() != null) ? getPage() : "index.html"; if (mPreloadOnCreate) { loadFileFromAssets(page); } } /** * Load the given file in the Web view * @param file: file name to load. * @warning All application HTML files should be found in the same subfolder in ressource path */ private void loadFileFromAssets(String file) { mWebView.loadUrl(Cobalt.getInstance(mContext).getResourcePath() + file); } /** * Called when fragment is about to rotate or be destroyed * This method SHOULD NOT be overridden in subclasses. */ private void removeWebViewFromPlaceholder() { if (mWebViewContainer != null) { mWebViewContainer.removeView(mWebView); } } // TODO: find a way to keep in the queue not sent messages /** * Sends script to be executed by JavaScript in Web view * @param jsonObj: JSONObject containing script. */ private void executeScriptInWebView(final JSONObject jsonObj) { if (jsonObj != null) { if (mCobaltIsReady) { mWebView.post(new Runnable() { @Override public void run() { // Line & paragraph separators are not JSON compliant but supported by JSONObject String script = jsonObj.toString().replaceAll("[\u2028\u2029]", ""); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Since KitKat, messages are automatically urldecoded when received from the web. encoding them to fix this. script = script.replaceAll("%","%25"); } String url = "javascript:cobalt.execute(" + script + ");"; mWebView.loadUrl(url); } }); } else { if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - executeScriptInWebView: adding message to queue: " + jsonObj); mWaitingJavaScriptCallsQueue.add(jsonObj); } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - executeScriptInWebView: jsonObj is null!"); } private void executeWaitingCalls() { int waitingJavaScriptCallsQueueLength = mWaitingJavaScriptCallsQueue.size(); for (int i = 0 ; i < waitingJavaScriptCallsQueueLength ; i++) { if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - executeWaitingCalls: execute " + mWaitingJavaScriptCallsQueue.get(i).toString()); executeScriptInWebView(mWaitingJavaScriptCallsQueue.get(i)); } mWaitingJavaScriptCallsQueue.clear(); } /** * Calls the Web callback with an object containing response fields * @param callbackId: the Web callback. * @param data: the object containing response fields */ public void sendCallback(final String callbackId, final JSONObject data) { if (callbackId != null && callbackId.length() > 0) { try { JSONObject jsonObj = new JSONObject(); jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeCallBack); jsonObj.put(Cobalt.kJSCallback, callbackId); jsonObj.put(Cobalt.kJSData, data); executeScriptInWebView(jsonObj); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendCallback: JSONException"); exception.printStackTrace(); } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendCallback: callbackId is null or empty!"); } /** * Calls the Web callback with an object containing response fields * @param event: the name of the event. * @param data: the object containing response fields * @param callbackID: the Web callback. */ public void sendEvent(final String event, final JSONObject data, final String callbackID) { if (event != null && event.length() > 0) { try { JSONObject jsonObj = new JSONObject(); jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeEvent); jsonObj.put(Cobalt.kJSEvent, event); jsonObj.put(Cobalt.kJSData, data); jsonObj.put(Cobalt.kJSCallback, callbackID); executeScriptInWebView(jsonObj); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendEvent: JSONException"); exception.printStackTrace(); } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendEvent: event is null or empty!"); } /** * Calls the Web callback with an object containing response fields * @param plugin: the name of the plugin. * @param data: the object containing response fields * @param callbackID: the Web callback. */ public void sendPlugin(final String plugin, final JSONObject data, final String callbackID) { if (plugin != null && plugin.length() > 0) { try { JSONObject jsonObj = new JSONObject(); jsonObj.put(Cobalt.kJSType, Cobalt.JSTypePlugin); jsonObj.put(Cobalt.kJSPluginName, plugin); jsonObj.put(Cobalt.kJSData, data); jsonObj.put(Cobalt.kJSCallback, callbackID); executeScriptInWebView(jsonObj); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendPlugin: JSONException"); exception.printStackTrace(); } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendPlugin: plugin is null or empty!"); } /** * Calls the Web callback with an object containing response fields * @param message: the object containing response fields */ public void sendMessage(final JSONObject message) { if (message != null) { executeScriptInWebView(message); } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendMessage: message is null !"); } /** * This method is called when the JavaScript sends a message to the native side. * This method should be overridden in subclasses. * @param message : the JSON-message sent by JavaScript. * @return true if the message was handled by the native, false otherwise * @details some basic operations are already implemented : navigation, logs, toasts, native alerts, web alerts * @details this method may be called from a secondary thread. */ // This method must be public !!! @JavascriptInterface public boolean onCobaltMessage(String message) { try { final JSONObject jsonObj = new JSONObject(message); // TYPE if (jsonObj.has(Cobalt.kJSType)) { String type = jsonObj.getString(Cobalt.kJSType); final JSONObject data; String callback; String action; switch (type) { // CALLBACK case Cobalt.JSTypeCallBack: String callbackID = jsonObj.getString(Cobalt.kJSCallback); data = jsonObj.optJSONObject(Cobalt.kJSData); return handleCallback(callbackID, data); // COBALT IS READY case Cobalt.JSTypeCobaltIsReady: String versionWeb = jsonObj.optString(Cobalt.kJSVersion, null); String versionNative = getResources().getString(R.string.version_name); if (versionWeb != null && !versionWeb.equals(versionNative)) Log.e(TAG, "Warning : Cobalt version mismatch : Android Cobalt version is " + versionNative + " but Web Cobalt version is " + versionWeb + ". You should fix this. "); onCobaltIsReady(); return true; // EVENT case Cobalt.JSTypeEvent: String event = jsonObj.getString(Cobalt.kJSEvent); data = jsonObj.optJSONObject(Cobalt.kJSData); callback = jsonObj.optString(Cobalt.kJSCallback, null); return handleEvent(event, data, callback); // INTENT case Cobalt.JSTypeIntent: action = jsonObj.getString(Cobalt.kJSAction); // OPEN EXTERNAL URL if (action.equals(Cobalt.JSActionIntentOpenExternalUrl)) { data = jsonObj.getJSONObject(Cobalt.kJSData); String url = data.getString(Cobalt.kJSUrl); openExternalUrl(url); return true; } // UNHANDLED INTENT else { onUnhandledMessage(jsonObj); break; } // LOG case Cobalt.JSTypeLog: String text = jsonObj.getString(Cobalt.kJSValue); Log.d(Cobalt.TAG, "JS LOG: " + text); return true; // NAVIGATION case Cobalt.JSTypeNavigation: action = jsonObj.getString(Cobalt.kJSAction); String page; String controller; switch (action) { // PUSH case Cobalt.JSActionNavigationPush: data = jsonObj.getJSONObject(Cobalt.kJSData); push(data); return true; // POP case Cobalt.JSActionNavigationPop: data = jsonObj.optJSONObject(Cobalt.kJSData); if (data != null) { page = data.optString(Cobalt.kJSPage, null); controller = data.optString(Cobalt.kJSController, null); JSONObject dataToPop = data.optJSONObject(Cobalt.kJSData); if (page != null) pop(controller, page, dataToPop); else pop(dataToPop); } else pop(); return true; // MODAL case Cobalt.JSActionNavigationModal: data = jsonObj.getJSONObject(Cobalt.kJSData); String callbackId = jsonObj.optString(Cobalt.kJSCallback, null); presentModal(data, callbackId); return true; // DISMISS case Cobalt.JSActionNavigationDismiss: // TODO: not present in iOS data = jsonObj.getJSONObject(Cobalt.kJSData); controller = data.getString(Cobalt.kJSController); page = data.getString(Cobalt.kJSPage); JSONObject dataForDissmiss = data.optJSONObject(Cobalt.kJSData); dismissModal(controller, page, dataForDissmiss); return true; // REPLACE case Cobalt.JSActionNavigationReplace: data = jsonObj.getJSONObject(Cobalt.kJSData); replace(data); return true; // UNHANDLED NAVIGATION default: onUnhandledMessage(jsonObj); break; } break; // PLUGIN case Cobalt.JSTypePlugin: mPluginManager.onMessage(mContext, this, jsonObj); break; case Cobalt.JSTypeUI: String control = jsonObj.getString(Cobalt.kJSUIControl); data = jsonObj.getJSONObject(Cobalt.kJSData); callback = jsonObj.optString(Cobalt.kJSCallback, null); return handleUi(control, data, callback); // WEB LAYER case Cobalt.JSTypeWebLayer: action = jsonObj.getString(Cobalt.kJSAction); // SHOW if (action.equals(Cobalt.JSActionWebLayerShow)) { data = jsonObj.getJSONObject(Cobalt.kJSData); mHandler.post(new Runnable() { @Override public void run() { showWebLayer(data); } }); return true; } // UNHANDLED WEB LAYER else { onUnhandledMessage(jsonObj); break; } // UNHANDLED TYPE default: onUnhandledMessage(jsonObj); break; } } // UNHANDLED MESSAGE else { onUnhandledMessage(jsonObj); } } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: JSONException"); exception.printStackTrace(); } catch (NullPointerException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: NullPointerException"); exception.printStackTrace(); } return false; } private void onCobaltIsReady() { if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onReady - version "+getResources().getString(R.string.version_name)); mCobaltIsReady = true; executeWaitingCalls(); onReady(); } protected void onReady() { } private boolean handleCallback(String callback, JSONObject data) { switch(callback) { case Cobalt.JSCallbackOnBackButtonPressed: try { onBackPressed(data.getBoolean(Cobalt.kJSValue)); return true; } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - handleCallback: JSONException"); exception.printStackTrace(); return false; } case Cobalt.JSCallbackPullToRefreshDidRefresh: mHandler.post(new Runnable() { @Override public void run() { onPullToRefreshDidRefresh(); } }); return true; case Cobalt.JSCallbackInfiniteScrollDidRefresh: mHandler.post(new Runnable() { @Override public void run() { onInfiniteScrollDidRefresh(); } }); return true; default: return onUnhandledCallback(callback, data); } } protected abstract boolean onUnhandledCallback(String callback, JSONObject data); private boolean handleEvent(String event, JSONObject data, String callback) { return onUnhandledEvent(event, data, callback); } protected abstract boolean onUnhandledEvent(String event, JSONObject data, String callback); private boolean handleUi(String control, JSONObject data, String callback) { try { switch (control) { // PICKER case Cobalt.JSControlPicker: String type = data.getString(Cobalt.kJSType); // DATE if (type.equals(Cobalt.JSPickerDate)) { JSONObject date = data.optJSONObject(Cobalt.kJSDate); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); if (date != null && date.has(Cobalt.kJSYear) && date.has(Cobalt.kJSMonth) && date.has(Cobalt.kJSDay)) { year = date.getInt(Cobalt.kJSYear); month = date.getInt(Cobalt.kJSMonth) - 1; day = date.getInt(Cobalt.kJSDay); } JSONObject texts = data.optJSONObject(Cobalt.kJSTexts); String title = texts.optString(Cobalt.kJSTitle, null); //String delete = texts.optString(Cobalt.kJSDelete, null); String clear = texts.optString(Cobalt.kJSClear, null); String cancel = texts.optString(Cobalt.kJSCancel, null); String validate = texts.optString(Cobalt.kJSValidate, null); showDatePickerDialog(year, month, day, title, clear, cancel, validate, callback); return true; } break; // ALERT case Cobalt.JSControlAlert: showAlertDialog(data, callback); return true; // TOAST case Cobalt.JSControlToast: String message = data.getString(Cobalt.kJSMessage); Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show(); return true; // BARS case Cobalt.JSControlBars: String action = data.getString(Cobalt.kJSAction); switch(action) { // SET BARS case Cobalt.JSActionSetBars: JSONObject bars = data.optJSONObject(Cobalt.kJSBars); setBars(bars); return true; case Cobalt.JSActionSetActionBadge: String name = data.optString(Cobalt.kActionName, null); String badge = data.optString(Cobalt.kActionBadge, null); ((CobaltActivity)getActivity()).setBadgeMenuItem(name, badge); return true; case Cobalt.JSActionSetActionContent: String nameContent = data.optString(Cobalt.kActionName, null); JSONObject content = data.optJSONObject(Cobalt.kContent); ((CobaltActivity)getActivity()).setContentMenuItem(nameContent, content); return true; default: break; } break; default: break; } } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException"); exception.printStackTrace(); } // UNHANDLED UI try { JSONObject jsonObj = new JSONObject(); jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeUI); jsonObj.put(Cobalt.kJSUIControl, control); jsonObj.put(Cobalt.kJSData, data); jsonObj.put(Cobalt.kJSCallback, callback); onUnhandledMessage(jsonObj); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException"); exception.printStackTrace(); } return false; } protected void setBars(final JSONObject actionBar) { Intent intent = ((CobaltActivity) mContext).getIntent(); Bundle bundle = intent.getExtras(); if (bundle == null) { bundle = new Bundle(); } Bundle extras = bundle.getBundle(Cobalt.kExtras); if (extras == null) { extras = new Bundle(); bundle.putBundle(Cobalt.kExtras, extras); } extras.putString(Cobalt.kBars, actionBar.toString()); intent.putExtras(bundle); ((CobaltActivity) mContext).runOnUiThread(new Runnable() { @Override public void run() { ((CobaltActivity) mContext).setupBars(actionBar); ((CobaltActivity) mContext).supportInvalidateOptionsMenu(); } }); } protected abstract void onUnhandledMessage(JSONObject message); private void push(JSONObject data) { try { String page = data.getString(Cobalt.kJSPage); String controller = data.optString(Cobalt.kJSController, null); JSONObject bars = data.optJSONObject(Cobalt.kJSBars); JSONObject dataToPush = data.optJSONObject(Cobalt.kJSData); Intent intent = Cobalt.getInstance(mContext).getIntentForController(controller, page); if (intent != null) { if (bars != null) { Bundle configuration = intent.getBundleExtra(Cobalt.kExtras); configuration.putString(Cobalt.kBars, bars.toString()); } if (dataToPush != null) { intent.putExtra(Cobalt.kJSData, dataToPush.toString()); } mContext.startActivity(intent); } else if (Cobalt.DEBUG) { Log.e(Cobalt.TAG, TAG + " - push: unable to push " + controller + " controller."); } } catch(JSONException exception) { if (Cobalt.DEBUG) { Log.e(Cobalt.TAG, TAG + " - push: missing mandatory page field."); } exception.printStackTrace(); } } private void pop() { onBackPressed(true); } private void pop(JSONObject data) { ((CobaltActivity) mContext).dataForPop(data); pop(); } private void pop(String controller, String page, JSONObject data) { ((CobaltActivity) mContext).popTo(controller, page, data); } private void presentModal(JSONObject data, String callBackID) { try { String page = data.getString(Cobalt.kJSPage); String controller = data.optString(Cobalt.kJSController, null); JSONObject bars = data.optJSONObject(Cobalt.kJSBars); JSONObject dataForModal = data.optJSONObject(Cobalt.kJSData); Intent intent = Cobalt.getInstance(mContext).getIntentForController(controller, page); if (intent != null) { intent.putExtra(Cobalt.kPushAsModal, true); if (bars != null) { Bundle configuration = intent.getBundleExtra(Cobalt.kExtras); configuration.putString(Cobalt.kBars, bars.toString()); } if (dataForModal != null) { intent.putExtra(Cobalt.kJSData, dataForModal.toString()); } mContext.startActivity(intent); // Sends callback to store current activity & HTML page for dismiss try { JSONObject callbackData = new JSONObject(); callbackData.put(Cobalt.kJSPage, getPage()); callbackData.put(Cobalt.kJSController, mContext.getClass().getName()); sendCallback(callBackID, callbackData); } catch (JSONException exception) { exception.printStackTrace(); } } else if (Cobalt.DEBUG) { Log.e(Cobalt.TAG, TAG + " - presentModal: unable to present modal " + controller + " controller."); } } catch(JSONException exception) { if (Cobalt.DEBUG) { Log.e(Cobalt.TAG, TAG + " - presentModal: missing mandatory page field."); } exception.printStackTrace(); } } private void dismissModal(String controller, String page, JSONObject dataForDissmiss) { try { Class<?> pClass = Class.forName(controller); // Instantiates intent only if class inherits from Activity if (Activity.class.isAssignableFrom(pClass)) { Bundle bundle = new Bundle(); bundle.putString(Cobalt.kPage, page); Intent intent = new Intent(mContext, pClass); intent.putExtra(Cobalt.kExtras, bundle); intent.putExtra(Cobalt.kPopAsModal, true); if (dataForDissmiss != null) { intent.putExtra(Cobalt.kJSData, dataForDissmiss.toString()); } NavUtils.navigateUpTo((Activity) mContext, intent); } else if(Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - dismissModal: unable to dismiss modal since " + controller + " does not inherit from Activity"); } catch (ClassNotFoundException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - dismissModal: " + controller + "not found"); exception.printStackTrace(); } } private void replace(JSONObject data) { try { String page = data.getString(Cobalt.kJSPage); String controller = data.optString(Cobalt.kJSController, null); JSONObject bars = data.optJSONObject(Cobalt.kJSBars); JSONObject dataForReplace = data.optJSONObject(Cobalt.kJSData); boolean animated = data.optBoolean(Cobalt.kJSAnimated); boolean clearHistory = data.optBoolean(Cobalt.kJSClearHistory, false); Intent intent = Cobalt.getInstance(mContext).getIntentForController(controller, page); if (intent != null) { intent.putExtra(Cobalt.kJSAnimated, animated); if (bars != null) { Bundle configuration = intent.getBundleExtra(Cobalt.kExtras); configuration.putString(Cobalt.kBars, bars.toString()); } if (dataForReplace != null) { intent.putExtra(Cobalt.kJSData, dataForReplace.toString()); } if (clearHistory) { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); } mContext.startActivity(intent); ((Activity) mContext).finish(); } else if (Cobalt.DEBUG) { Log.e(Cobalt.TAG, TAG + " - replace: unable to replace " + controller + " controller."); } } catch(JSONException exception) { if (Cobalt.DEBUG) { Log.e(Cobalt.TAG, TAG + " - replace: missing mandatory page field."); } exception.printStackTrace(); } } public void askWebViewForBackPermission() { sendEvent(Cobalt.JSEventOnBackButtonPressed, null, Cobalt.JSCallbackOnBackButtonPressed); } /** * Called when the Web view allowed or not the onBackPressed event. * @param allowedToBack: true if the WebView allowed the onBackPressed event * false otherwise. * @details if allowedToBack is true, the onBackPressed method of the activity will be called. * This method should not be overridden in subclasses. */ protected void onBackPressed(boolean allowedToBack) { if (allowedToBack) { if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onBackPressed: onBackPressed event allowed by Web view"); ((CobaltActivity) mContext).back(); } else if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - onBackPressed: onBackPressed event denied by Web view"); } private void showWebLayer(JSONObject data) { try { String page = data.getString(Cobalt.kJSPage); double fadeDuration = data.optDouble(Cobalt.kJSWebLayerFadeDuration, 0.3); Bundle bundle = new Bundle(); bundle.putString(Cobalt.kPage, page); CobaltWebLayerFragment webLayerFragment = getWebLayerFragment(); if (webLayerFragment != null) { webLayerFragment.setArguments(bundle); FragmentTransaction fragmentTransition = ((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction(); if (fadeDuration > 0) { fragmentTransition.setCustomAnimations( android.R.anim.fade_in, android.R.anim.fade_out, android.R.anim.fade_in, android.R.anim.fade_out); } else { fragmentTransition.setTransition(FragmentTransaction.TRANSIT_NONE); } if (CobaltActivity.class.isAssignableFrom(mContext.getClass())) { // Dismiss current Web layer if one is already shown CobaltActivity activity = (CobaltActivity) mContext; Fragment currentFragment = activity.getSupportFragmentManager().findFragmentById(activity.getFragmentContainerId()); if (currentFragment != null && CobaltWebLayerFragment.class.isAssignableFrom(currentFragment.getClass())) { ((CobaltWebLayerFragment) currentFragment).dismissWebLayer(null); } // Shows Web layer if (activity.findViewById(activity.getFragmentContainerId()) != null) { fragmentTransition.add(activity.getFragmentContainerId(), webLayerFragment); if (allowFragmentCommit()) fragmentTransition.commit(); } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - showWebLayer: fragment container not found"); } } else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - showWebLayer: getWebLayerFragment returned null!"); } catch (JSONException exception) { if(Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - showWebLayer: JSONException"); exception.printStackTrace(); } } /** * Returns new instance of a {@link CobaltWebLayerFragment} * @return a new instance of a {@link CobaltWebLayerFragment} * This method may be overridden in subclasses if the {@link CobaltWebLayerFragment} must implement customized stuff. */ protected CobaltWebLayerFragment getWebLayerFragment() { return new CobaltWebLayerFragment(); } /** * Called from the corresponding {@link CobaltWebLayerFragment} when dismissed. * This method may be overridden in subclasses. */ public void onWebLayerDismiss(final String page, final JSONObject data) { mHandler.post(new Runnable() { @Override public void run() { try { JSONObject jsonObj = new JSONObject(); jsonObj.put(Cobalt.kJSPage, page); jsonObj.put(Cobalt.kJSData, data); sendEvent(Cobalt.JSEventWebLayerOnDismiss, jsonObj, null); } catch (JSONException exception) { if(Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - onWebLayerDismiss: JSONException"); exception.printStackTrace(); } } }); } public boolean allowFragmentCommit() { return mAllowCommit; } private void showAlertDialog(JSONObject data, final String callback) { try { String title = data.optString(Cobalt.kJSAlertTitle); String message = data.optString(Cobalt.kJSMessage); boolean cancelable = data.optBoolean(Cobalt.kJSAlertCancelable, false); JSONArray buttons = data.has(Cobalt.kJSAlertButtons) ? data.getJSONArray(Cobalt.kJSAlertButtons) : new JSONArray(); AlertDialog alertDialog = new AlertDialog.Builder(mContext) .setTitle(title) .setMessage(message) .create(); alertDialog.setCancelable(cancelable); if (buttons.length() == 0) { alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callback != null) { try { JSONObject data = new JSONObject(); data.put(Cobalt.kJSAlertButtonIndex, 0); sendCallback(callback, data); } catch (JSONException exception) { if(Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException"); exception.printStackTrace(); } } } }); } else { int buttonsLength = Math.min(buttons.length(), 3); for (int i = 0 ; i < buttonsLength ; i++) { int buttonId; switch(i) { case 0: default: buttonId = DialogInterface.BUTTON_NEGATIVE; break; case 1: buttonId = DialogInterface.BUTTON_NEUTRAL; break; case 2: buttonId = DialogInterface.BUTTON_POSITIVE; break; } alertDialog.setButton(buttonId, buttons.getString(i), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callback != null) { int buttonIndex; switch(which) { case DialogInterface.BUTTON_NEGATIVE: default: buttonIndex = 0; break; case DialogInterface.BUTTON_NEUTRAL: buttonIndex = 1; break; case DialogInterface.BUTTON_POSITIVE: buttonIndex = 2; break; } try { JSONObject data = new JSONObject(); data.put(Cobalt.kJSAlertButtonIndex, buttonIndex); sendCallback(callback, data); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException"); exception.printStackTrace(); } } } }); } } alertDialog.show(); } catch (JSONException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - showAlertDialog: JSONException"); exception.printStackTrace(); } } private void showDatePickerDialog(int year, int month, int day, String title, String delete, String cancel, String validate, String callbackID) { Bundle args = new Bundle(); args.putInt(CobaltDatePickerFragment.ARG_YEAR, year); args.putInt(CobaltDatePickerFragment.ARG_MONTH, month); args.putInt(CobaltDatePickerFragment.ARG_DAY, day); args.putString(CobaltDatePickerFragment.ARG_TITLE, title); args.putString(CobaltDatePickerFragment.ARG_DELETE, delete); args.putString(CobaltDatePickerFragment.ARG_CANCEL, cancel); args.putString(CobaltDatePickerFragment.ARG_VALIDATE, validate); args.putString(CobaltDatePickerFragment.ARG_CALLBACK_ID, callbackID); CobaltDatePickerFragment fragment = new CobaltDatePickerFragment(); fragment.setArguments(args); fragment.setListener(this); fragment.show(((FragmentActivity) mContext).getSupportFragmentManager(), "datePicker"); } protected void sendDate(int year, int month, int day, String callbackID) { try { if (year != -1 && month != -1 && day != -1) { JSONObject date = new JSONObject(); date.put(Cobalt.kJSYear, year); date.put(Cobalt.kJSMonth, ++month); date.put(Cobalt.kJSDay, day); sendCallback(callbackID, date); } else { sendCallback(callbackID, null); } } catch (JSONException e) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - sendDate: JSONException"); e.printStackTrace(); } } private void openExternalUrl(String url) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } /** * Set the four colors used in the progress animation from color resources. * The first color will also be the color of the bar that grows in response to a user swipe gesture. * Must be called only after super.onStart(). * @param colorResource1 the first color resource * @param colorResource2 the second color resource * @param colorResource3 the third color resource * @param colorResource4 the last color resource */ protected void setRefreshColorScheme(int colorResource1, int colorResource2, int colorResource3, int colorResource4) { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setColorSchemeResources(colorResource1, colorResource2, colorResource3, colorResource4); else if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - setColorScheme: Pull-to-refresh must be active and method called after super.onStart()!"); } @Override public void onRefresh() { refreshWebView(); } private void refreshWebView() { mHandler.post(new Runnable() { @Override public void run() { sendEvent(Cobalt.JSEventPullToRefresh, null, Cobalt.JSCallbackPullToRefreshDidRefresh); } }); } private void onPullToRefreshDidRefresh() { mSwipeRefreshLayout.setRefreshing(false); onPullToRefreshRefreshed(); } /** * This method may be overridden in subclasses. */ protected void onPullToRefreshRefreshed() { } @Override public void onOverScrolled(int scrollX, int scrollY, int oldscrollX, int oldscrollY) { int height = mWebView.getHeight(); long contentHeight = (long) Math.floor(mWebView.getContentHeight() * mContext.getResources().getDisplayMetrics().density); if (isInfiniteScrollActive() && ! mIsInfiniteScrollRefreshing && scrollY >= oldscrollY && scrollY + height >= contentHeight - height * getInfiniteScrollOffset() / 100) { infiniteScrollRefresh(); } } private void infiniteScrollRefresh() { mHandler.post(new Runnable() { @Override public void run() { sendEvent(Cobalt.JSEventInfiniteScroll, null, Cobalt.JSCallbackInfiniteScrollDidRefresh); mIsInfiniteScrollRefreshing = true; } }); } private void onInfiniteScrollDidRefresh() { mIsInfiniteScrollRefreshing = false; onInfiniteScrollRefreshed(); } /** * This method may be overridden in subclasses. */ protected void onInfiniteScrollRefreshed() { } private boolean isPullToRefreshActive() { Bundle args = getArguments(); return args != null && args.getBoolean(Cobalt.kPullToRefresh); } private boolean isInfiniteScrollActive() { Bundle args = getArguments(); return args != null && args.getBoolean(Cobalt.kInfiniteScroll); } private int getInfiniteScrollOffset() { Bundle args = getArguments(); if (args != null) { return args.getInt(Cobalt.kInfiniteScrollOffset); } else { return Cobalt.INFINITE_SCROLL_OFFSET_DEFAULT_VALUE; } } protected String getPage() { Bundle args = getArguments(); if (args != null) { return args.getString(Cobalt.kPage); } else { return null; } } }
package tgbungeeauth.bungee; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.regex.PatternSyntaxException; import com.google.common.base.Charsets; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.Connection; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.Server; import net.md_5.bungee.api.event.ChatEvent; import net.md_5.bungee.api.event.PlayerDisconnectEvent; import net.md_5.bungee.api.event.PostLoginEvent; import net.md_5.bungee.api.event.PreLoginEvent; import net.md_5.bungee.api.event.ServerConnectEvent; import net.md_5.bungee.api.event.ServerPreConnectedEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import net.md_5.bungee.event.EventHandler; import net.md_5.bungee.event.EventPriority; import tgbungeeauth.bungee.auth.db.AuthDatabase; import tgbungeeauth.bungee.auth.db.FileDataBackend; import tgbungeeauth.bungee.auth.db.PlayerAuth; import tgbungeeauth.bungee.auth.managment.AsyncLogin; import tgbungeeauth.bungee.commands.AdminCommand; import tgbungeeauth.bungee.commands.LicenseCommand; import tgbungeeauth.bungee.commands.LoginCommand; import tgbungeeauth.bungee.commands.RegisterCommand; import tgbungeeauth.bungee.config.Messages; import tgbungeeauth.bungee.config.Settings; import tgbungeeauth.shared.ChannelNames; public class TGBungeeAuthBungee extends Plugin implements Listener { private static TGBungeeAuthBungee instance; public static TGBungeeAuthBungee getInstance() { return instance; } public TGBungeeAuthBungee() { instance = this; } private final Set<UUID> succauth = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final Map<UUID, ServerInfo> targetservers = new ConcurrentHashMap<>(); public boolean isAuthed(ProxiedPlayer player) { return succauth.contains(player.getUniqueId()); } public void finishAuth(ProxiedPlayer player) { succauth.add(player.getUniqueId()); player.connect(targetservers.get(player.getUniqueId())); } private final AuthDatabase authdatabase = new AuthDatabase(new FileDataBackend(), 60); private final SecurityDatabase securitydatabase = new SecurityDatabase(); public AuthDatabase getAuthDatabase() { return authdatabase; } public SecurityDatabase getSecDatabase() { return securitydatabase; } @Override public void onEnable() { getDataFolder().mkdir(); File file = new File(getDataFolder(), "config.yml"); if (!file.exists()) { try (InputStream in = getResourceAsStream("config.yml")) { Files.copy(in, file.toPath()); } catch (IOException e) { } } try { Class.forName(ServerPreConnectedEvent.class.getName()); } catch (Throwable t) { getLogger().severe("Unable to find special event"); ProxyServer.getInstance().stop(); } try { Settings.loadConfig(); Messages.loadConfig(); } catch (IOException e) { getLogger().severe("Unable to load config"); ProxyServer.getInstance().stop(); } try { authdatabase.load(); securitydatabase.load(); } catch (IOException e) { getLogger().severe("Unable to load database"); ProxyServer.getInstance().stop(); } PluginManager pm = ProxyServer.getInstance().getPluginManager(); pm.registerCommand(this, new LicenseCommand()); pm.registerCommand(this, new AdminCommand()); pm.registerCommand(this, new LoginCommand()); pm.registerCommand(this, new RegisterCommand()); pm.registerListener(this, this); } @Override public void onDisable() { authdatabase.save(); securitydatabase.save(); } @EventHandler(priority = EventPriority.LOWEST) public void onPreLogin(PreLoginEvent event) { String name = event.getConnection().getName(); String regex = Settings.nickRegex; if ((name.length() > Settings.maxNickLength) || (name.length() < Settings.minNickLength)) { event.setCancelReason(new TextComponent(Messages.restrictionNameLength)); return; } try { if (!name.matches(regex)) { event.setCancelled(true); event.setCancelReason(new TextComponent(Messages.restrictionRegex.replace("REG_EX", regex))); return; } } catch (PatternSyntaxException pse) { event.setCancelled(true); event.setCancelReason(new TextComponent("Invalid regex configured. Please norify administrator about this")); return; } if (authdatabase.isAuthAvailable(name)) { PlayerAuth auth = authdatabase.getAuth(name); String realnickname = auth.getRealNickname(); if (!realnickname.isEmpty() && !name.equals(realnickname)) { event.setCancelled(true); event.setCancelReason(new TextComponent(Messages.restrictionInvalidCase.replace("REALNAME", realnickname))); return; } } ProxiedPlayer oplayer = null; try { oplayer = ProxyServer.getInstance().getPlayer(name); } catch (Throwable t) { event.setCancelled(true); event.setCancelReason(new TextComponent("Error while logging in, please try again")); } if ((oplayer != null) && !oplayer.getAddress().getAddress().getHostAddress().equals(event.getConnection().getAddress().getHostString())) { event.setCancelled(true); event.setCancelReason(new TextComponent(Messages.restrictionAlreadyPlaying)); return; } if (securitydatabase.isOnlineMode(name)) { event.getConnection().setOnlineMode(true); event.getConnection().setForcedUniqueId(UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8))); } } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerJoin(PostLoginEvent event) { ProxiedPlayer player = event.getPlayer(); long timeout = Settings.timeout; if (timeout != 0) { ProxyServer.getInstance().getScheduler().schedule(TGBungeeAuthBungee.this, () -> { if (player.isConnected() && !isAuthed(player)) { player.disconnect(new TextComponent(Messages.timedOut)); } }, timeout, TimeUnit.SECONDS); } String helpmsg = authdatabase.isAuthAvailable(player.getName()) ? Messages.loginHelp : Messages.registerHelp; Runnable msgtask = new Runnable() { @Override public void run() { if (player.isConnected() && !isAuthed(player)) { player.sendMessage(new TextComponent(helpmsg)); ProxyServer.getInstance().getScheduler().schedule(TGBungeeAuthBungee.this, this, Settings.messageInterval, TimeUnit.SECONDS); } } }; msgtask.run(); } private final HashSet<String> allowedCommands = new HashSet<>(Arrays.asList("/l", "/login", "/reg", "/register")); @EventHandler(priority = EventPriority.LOWEST) public void onCommand(ChatEvent event) { Connection sender = event.getSender(); if (sender instanceof ProxiedPlayer) { ProxiedPlayer player = (ProxiedPlayer) sender; if (!isAuthed(player)) { String[] split = event.getMessage().split("\\s+"); if (!allowedCommands.contains(split[0])) { event.setCancelled(true); player.sendMessage(new TextComponent(Messages.notloggedin)); } } } } @EventHandler(priority = EventPriority.LOWEST) public void onQuit(PlayerDisconnectEvent event) { ProxiedPlayer player = event.getPlayer(); succauth.remove(player.getUniqueId()); targetservers.remove(player.getUniqueId()); } @EventHandler(priority = EventPriority.LOWEST) public void onServerConnect(ServerConnectEvent event) { ProxiedPlayer player = event.getPlayer(); if (!isAuthed(player)) { targetservers.put(player.getUniqueId(), event.getTarget()); ServerInfo authserveri = ProxyServer.getInstance().getServerInfo(Settings.authserver); if (authserveri == null) { player.disconnect(new TextComponent(ChatColor.RED + "Auth server not found")); return; } event.setTarget(authserveri); if (securitydatabase.isOnlineMode(player.getName())) { ProxyServer.getInstance().getScheduler().runAsync(this, new AsyncLogin(player, "forcelogin", true)); } } } @EventHandler(priority = EventPriority.LOWEST) public void onPreConnect(ServerPreConnectedEvent event) throws IOException { ProxiedPlayer player = event.getPlayer(); Server server = event.getServer(); if (!server.getInfo().getName().equals(Settings.authserver) && succauth.contains(player.getUniqueId())) { MessageWriter.writeMessage(server, ChannelNames.SECUREKEY_SUBCHANNEL, stream -> { stream.writeUTF(Settings.securekey); }); } } }
package org.cs4j.core.mains; import org.cs4j.core.OutputResult; import org.cs4j.core.SearchAlgorithm; import org.cs4j.core.SearchDomain; import org.cs4j.core.SearchResult; import org.cs4j.core.algorithms.EESwithNRR; import org.cs4j.core.algorithms.WAStarWithNRR; import org.cs4j.core.data.Weights; import org.cs4j.core.domains.Utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.FileAlreadyExistsException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class WRAStar_General_Experiment { private Weights weights = new Weights(); private String HEADER_PREFIX = "WR"; /** * Creates a header line for writing into output * * @return The created header line */ private String _getHeader() { return "InstanceID,Wg,Wh,Weight," + HEADER_PREFIX + "-Slv," + HEADER_PREFIX + "-Dep," + HEADER_PREFIX + "-Cst," + HEADER_PREFIX + "-Gen," + HEADER_PREFIX + "-FExp," + HEADER_PREFIX + "-Exp," + HEADER_PREFIX + "-Dup," + HEADER_PREFIX + "-Oup," + HEADER_PREFIX + "-Rep," + HEADER_PREFIX + "-Itc," + // Iterations Count HEADER_PREFIX + "-Tme,"; } /*** * Write a header line into the output * @param outputResult The output result which points to a file * @throws IOException */ private void _writeHeaderLineToOutput(OutputResult outputResult) throws IOException { // Write the header line outputResult.writeln(this._getHeader()); } /** * Returns an array for NoSolution * * @param result The search result data structure * * @return A double array which contains default values to write in case no solution was found */ private double[] _getNoSolutionResult(SearchResult result) { return new double[]{ // solution-not-found 0, // no-length -1, // no-cost -1, result.getGenerated(), result.getFirstIterationExpanded(), result.getExpanded(), result.getDuplicates(), result.getUpdatedInOpen(), result.getReopened(), result.getIterationsCount(), result.getWallTimeMillis(), }; } /** * Returns an array for a found solution * * @param result The search result data structure * * @return A new double array which contains all the fields for the solution */ private double[] _getSolutionResult(SearchResult result) { SearchResult.Solution solution = result.getSolutions().get(0); return new double[]{ 1, solution.getLength(), solution.getCost(), result.getGenerated(), result.getFirstIterationExpanded(), result.getExpanded(), result.getDuplicates(), result.getUpdatedInOpen(), result.getReopened(), result.getIterationsCount(), result.getWallTimeMillis(), }; } /** * Returns an array for OutOfMemory * * @return A double array which contains default values to write in case there is no memory for solution */ private double[] _getOutOfMemoryResult() { return new double[]{-1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0}; } /** * Returns an initialized outputResult object * * @param outputPath The output path * @param prefix A prefix to add to the created random file * @param writeHeader Whether to add a header line immediately * * @return The created output result */ private OutputResult getOutputResult(String outputPath, String prefix, boolean writeHeader) throws IOException { OutputResult output = null; if (prefix == null) { prefix = ""; } try { output = new OutputResult(outputPath, prefix, true); } catch (FileAlreadyExistsException e) { System.err.println("Output file " + outputPath + " already exists"); System.exit(-1); } // Add the header immediately if needed if (writeHeader) { this._writeHeaderLineToOutput(output); } return output; } /** * Runs an experiment using the WAStarWithNRR and EES algorithms in a SINGLE THREAD! * * @param domain The domain to run with (can be null) * @param firstInstance The id of the first instance to solve * @param instancesCount The number of instances to solve * @param outputPath The name of the output file (can be null : in this case a random path will be chosen) * @param optimalCosts The optimal costs of the instances * @param needHeader Whether to add the header line to list * * @return Name of all the created output files * * @throws java.io.IOException */ public String[] runGridPathFindingWithPivotsExperimentNRRStar( String NRRType, String gridName, SearchDomain domain, int firstInstance, int instancesCount, String outputPath, Map<Integer, Double> optimalCosts, boolean needHeader) throws IOException { // Prepare the weights Weights.SingleWeight[] weights = Utils.concatenate( this.weights.VERY_LOW_WEIGHTS, this.weights.PAPER_ADDITIONAL_WEIGHTS); Arrays.sort(weights); int[] pivotsCounts = new int[]{10}; List<String> allOutputFiles = new ArrayList<>(pivotsCounts.length); if (domain == null) { // Create the domain by reading the first instance (the pivots DB is read once!) domain = DomainsCreation.createGridPathFindingInstanceFromAutomaticallyGeneratedWithTDH( gridName, firstInstance + ".in", 10); } for (int pivotsCount : pivotsCounts) { System.out.println("[INFO] Runs experiment with " + pivotsCount + " pivots"); OutputResult output = this.getOutputResult(outputPath + "-" + pivotsCount, null, needHeader); // Go over all the possible combinations and solve! for (int i = firstInstance; i <= instancesCount; ++i) { // Create the domain by reading the relevant instance file domain = DomainsCreation.createGridPathFindingInstanceFromAutomaticallyGeneratedWithTDH( gridName, domain, i + ".in", pivotsCount); // Bypass not found files if (domain == null) { continue; } // Set the optimal cost if required if (optimalCosts != null) { double optimalCost = optimalCosts.get(i); domain.setOptimalSolutionCost(optimalCost); System.out.println("[INFO] Instance " + i + " optimal cost is " + optimalCost); } for (Weights.SingleWeight w : weights) { double weight = w.getWeight(); output.write(i + "," + w.wg + "," + w.wh + "," + weight + ","); //SearchAlgorithm alg = new WAStarWithNRR(); SearchAlgorithm alg = new EESwithNRR(); alg.setAdditionalParameter("weight", weight + ""); alg.setAdditionalParameter("nrr-type", NRRType.toLowerCase()); //alg.setAdditionalParameter("bpmx", true + ""); //alg.setAdditionalParameter("iteration-to-start-reopening", "1" + ""); //alg.setAdditionalParameter("w-admissibility-deviation-percentage", 20.0d + ""); System.out.println("[INFO] Algorithm: " + alg.getName() + ", Instance: " + i + ", Weight: " + weight); try { SearchResult result = alg.search(domain); // No solution if (!result.hasSolution()) { output.appendNewResult(this._getNoSolutionResult(result)); System.out.println("[INFO] Done: NoSolution"); } else { double[] resultData = this._getSolutionResult(result); System.out.println("[INFO] Done: " + Arrays.toString(resultData)); output.appendNewResult(resultData); } } catch (OutOfMemoryError e) { System.out.println("[INFO] Done: OutOfMemory"); output.appendNewResult(this._getOutOfMemoryResult()); } output.newline(); } } output.close(); allOutputFiles.add(output.getFname()); } return allOutputFiles.toArray(new String[allOutputFiles.size()]); } /** * Runs an experiment using the WAStarWithNRR and EES algorithms in a SINGLE THREAD! * * @param firstInstance The id of the first instance to solve * @param instancesCount The number of instances to solve * @param outputPath The name of the output file (can be null : in this case a random path will be chosen) * @param optimalCosts The optimal costs of the instances * @param needHeader Whether to add the header line to list * * @return Name of all the created output files * * @throws java.io.IOException */ public String[] runGridPathFindingWithPivotsExperimentNRRStar( String NRRType, String gridName, int firstInstance, int instancesCount, String outputPath, Map<Integer, Double> optimalCosts, boolean needHeader) throws IOException { return this.runGridPathFindingWithPivotsExperimentNRRStar( NRRType, gridName, null, firstInstance, instancesCount, outputPath, optimalCosts, needHeader); } /** * TODO: Document */ public String[] runTopSpin16ExperimentNRR( String NRRType, int firstInstance, int instancesCount, String outputPath, Map<Integer, Double> optimalCosts, boolean needHeader) throws IOException { return this.runTopSpin16ExperimentNRR( NRRType, null, firstInstance, instancesCount, outputPath, optimalCosts, needHeader); } /** * TODO: Document */ public String[] runTopSpin16ExperimentNRR( String NRRType, SearchDomain domain, int firstInstance, int instancesCount, String outputPath, Map<Integer, Double> optimalCosts, boolean needHeader) throws IOException { // Prepare the weights Weights.SingleWeight[] weights = Utils.concatenate( this.weights.VERY_LOW_WEIGHTS, this.weights.PAPER_ADDITIONAL_WEIGHTS); Arrays.sort(weights); int[] pivotsCounts = new int[]{10}; List<String> allOutputFiles = new ArrayList<>(pivotsCounts.length); if (domain == null) { // Create the domain by reading the first instance (the pivots DB is read once!) domain = DomainsCreation.createTopSpin16InstanceWithPDBs(firstInstance + ".in"); } OutputResult output = this.getOutputResult(outputPath, null, needHeader); // Go over all the possible combinations and solve! for (int i = firstInstance; i <= instancesCount; ++i) { // Create the domain by reading the relevant instance file domain = DomainsCreation.createTopSpin16InstanceWithPDBs(domain, i + ".in"); // Bypass not found files if (domain == null) { continue; } // Set the optimal cost if required if (optimalCosts != null) { double optimalCost = optimalCosts.get(i); domain.setOptimalSolutionCost(optimalCost); System.out.println("[INFO] Instance " + i + " optimal cost is " + optimalCost); } for (Weights.SingleWeight w : weights) { double weight = w.getWeight(); output.write(i + "," + w.wg + "," + w.wh + "," + weight + ","); SearchAlgorithm alg = new WAStarWithNRR(); alg.setAdditionalParameter("weight", weight + ""); alg.setAdditionalParameter("nrr-type", NRRType.toLowerCase()); //alg.setAdditionalParameter("bpmx", true + ""); //alg.setAdditionalParameter("iteration-to-start-reopening", "1" + ""); //alg.setAdditionalParameter("w-admissibility-deviation-percentage", 20.0d + ""); System.out.println("[INFO] Algorithm: " + alg.getName() + ", Instance: " + i + ", Weight: " + weight); try { SearchResult result = alg.search(domain); // No solution if (!result.hasSolution()) { output.appendNewResult(this._getNoSolutionResult(result)); System.out.println("[INFO] Done: NoSolution"); } else { double[] resultData = this._getSolutionResult(result); System.out.println("[INFO] Done: " + Arrays.toString(resultData)); output.appendNewResult(resultData); } } catch (OutOfMemoryError e) { System.out.println("[INFO] Done: OutOfMemory"); output.appendNewResult(this._getOutOfMemoryResult()); } output.newline(); } } output.close(); allOutputFiles.add(output.getFname()); return allOutputFiles.toArray(new String[allOutputFiles.size()]); } /** * The function reads the optimal costs of all the instances, stored in the input file * * @param path The path of the file that contains the optimal costs * * NOTE: The file must be of the following format: * <instance-i1-id>,<i1-optimal-cost> * <instance-i2-id>,<i2-optimal-cost> * ... * ... * @return An mapping from instance id to the optimal cost of this instance */ public static Map<Integer, Double> readOptimalCosts(String path) throws IOException { System.out.println("[INFO] Reading optimal costs"); Map<Integer, Double> toReturn = new HashMap<>(); InputStream is = new FileInputStream(new File(path)); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String currentLine; while ((currentLine = in.readLine()) != null) { String[] split = currentLine.split(","); assert split.length == 2; Integer instanceID = Integer.parseInt(split[0]); assert !toReturn.containsKey(instanceID); Double cost = Double.parseDouble(split[1]); assert cost >= 0; toReturn.put(instanceID, cost); } System.out.println("[INFO] Done reading optimal costs, read " + toReturn.size() + " costs in total"); return toReturn; } /** * For Different domains + different NRR types */ public static void mainTopSpin16Experiment() { // Solve with 100 instances String[] NRRTypes = new String[]{ "NRR1"}; for (String NRRType : NRRTypes) { try { WRAStar_General_Experiment experiment = new WRAStar_General_Experiment(); // TODO: Make this local variable experiment.HEADER_PREFIX = NRRType.toUpperCase(); experiment.runTopSpin16ExperimentNRR( NRRType, // First instance ID 1, // Instances Count 100, // Output Path "results/topspin/topspin16-9pdbs/wastar-random-pdb-" + NRRType.toLowerCase(), null, // Add header true); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } } } /** * For GridPathFinding with pivots - Runs different NRR types */ public static void mainGridPathFindingExperimentWithPivotsNRR() { // Solve with 100 instances // Solve with 100 instances String gridName = "brc202d.map"; //"NRR1", String[] NRRTypes = new String[]{ "NRR2"}; for (String NRRType : NRRTypes) { try { WRAStar_General_Experiment experiment = new WRAStar_General_Experiment(); // TODO: Make this local variable experiment.HEADER_PREFIX = NRRType.toUpperCase(); experiment.runGridPathFindingWithPivotsExperimentNRRStar( NRRType, // Name of the map file gridName, // First instance ID 1, // Instances Count 100, // Output Path "results/gridpathfinding/generated/"+ gridName+ "/Inconsistent/RANDOM_PIVOT_10/ees-random-pivot-10-"+ NRRType.toLowerCase(), //"results/gridpathfinding/generated/maze512-1-6.map/generated+wrastar+extended", null, //WRAStar_General_Experiment.readOptimalCosts("input/gridpathfinding/generated/brc202d.map/optimal.raw"), //WRAStar_General_Experiment.readOptimalCosts("input/gridpathfinding/generated/ost003d.map/optimal.raw"), //WRAStar_General_Experiment.readOptimalCosts("input/gridpathfinding/generated/den400d.map/optimal.raw"), // Add header true); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } } } public static void main(String[] args) { //Utils.disablePrints(); //WAStar_EES_GeneralExperiment.cleanAllSearchFiles(); WRAStar_General_Experiment.mainGridPathFindingExperimentWithPivotsNRR(); //WRAStar_General_Experiment.mainTopSpin16Experiment(); //WAStar_EES_GeneralExperiment.mainGeneralExperimentMultiThreaded(); } }
package org.elasticsearch.service.statsd; import java.util.List; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.cluster.node.stats.NodeStats; import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.collect.Lists; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.component.Lifecycle; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.index.service.IndexService; import org.elasticsearch.index.shard.service.IndexShard; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.NodeIndicesStats; import org.elasticsearch.node.service.NodeService; import org.elasticsearch.cluster.ClusterState; import com.timgroup.statsd.NonBlockingStatsDClient; import com.timgroup.statsd.StatsDClient; public class StatsdService extends AbstractLifecycleComponent<StatsdService> { private final ClusterService clusterService; private final IndicesService indicesService; private final NodeService nodeService; private final String statsdHost; private final Integer statsdPort; private final TimeValue statsdRefreshInternal; private final String statsdPrefix; private final String statsdNodeName; private final Boolean statsdReportIndices; private final Boolean statsdReportShards; private final Boolean statsdReportFsDetails; private final StatsDClient statsdClient; private volatile Thread statsdReporterThread; private volatile boolean closed; @Inject public StatsdService(Settings settings, ClusterService clusterService, IndicesService indicesService, NodeService nodeService) { super(settings); this.clusterService = clusterService; this.indicesService = indicesService; this.nodeService = nodeService; this.statsdRefreshInternal = settings.getAsTime( "metrics.statsd.every", TimeValue.timeValueMinutes(1) ); this.statsdHost = settings.get( "metrics.statsd.host" ); this.statsdPort = settings.getAsInt( "metrics.statsd.port", 8125 ); this.statsdPrefix = settings.get( "metrics.statsd.prefix", "elasticsearch" + "." + settings.get("cluster.name") ); this.statsdNodeName = settings.get( "metrics.statsd.node_name" ); this.statsdReportIndices = settings.getAsBoolean( "metrics.statsd.report.indices", true ); this.statsdReportShards = settings.getAsBoolean( "metrics.statsd.report.shards", false ); this.statsdReportFsDetails = settings.getAsBoolean( "metrics.statsd.report.fs_details", false ); this.statsdClient = new NonBlockingStatsDClient(this.statsdPrefix, this.statsdHost, this.statsdPort); } @Override protected void doStart() throws ElasticsearchException { if (this.statsdHost != null && this.statsdHost.length() > 0) { this.statsdReporterThread = EsExecutors .daemonThreadFactory(this.settings, "statsd_reporter") .newThread(new StatsdReporterThread()); this.statsdReporterThread.start(); this.logger.info( "StatsD reporting triggered every [{}] to host [{}:{}] with metric prefix [{}]", this.statsdRefreshInternal, this.statsdHost, this.statsdPort, this.statsdPrefix ); } else { this.logger.error( "StatsD reporting disabled, no statsd host configured" ); } } @Override protected void doStop() throws ElasticsearchException { if (this.closed) { return; } if (this.statsdReporterThread != null) { this.statsdReporterThread.interrupt(); } this.closed = true; this.logger.info("StatsD reporter stopped"); } @Override protected void doClose() throws ElasticsearchException { } public class StatsdReporterThread implements Runnable { @Override public void run() { while (!StatsdService.this.closed) { DiscoveryNode node = StatsdService.this.clusterService.localNode(); ClusterState state = StatsdService.this.clusterService.state(); boolean isClusterStarted = StatsdService.this.clusterService .lifecycleState() .equals(Lifecycle.State.STARTED); if (node != null && state != null && isClusterStarted) { // Report node stats -- runs for all nodes StatsdReporter nodeStatsReporter = new StatsdReporterNodeStats( StatsdService.this.nodeService.stats( new CommonStatsFlags().clear(), // indices true, true, // process true, // jvm true, // threadPool true, // network true, true, // transport true, // http false // circuitBreaker ), StatsdService.this.statsdNodeName == null ? node.getName() : StatsdService.this.statsdNodeName, StatsdService.this.statsdReportFsDetails ); nodeStatsReporter .setStatsDClient(StatsdService.this.statsdClient) .run(); // Master node is the only one allowed to send cluster wide sums / stats if (state.nodes().localNodeMaster()) { // Report cluster wide index totals StatsdReporter nodeIndicesStatsReporter = new StatsdReporterNodeIndicesStats( StatsdService.this.indicesService.stats( false // includePrevious ) ); nodeIndicesStatsReporter .setStatsDClient(StatsdService.this.statsdClient) .run(); // Maybe breakdown numbers by index or shard if ( StatsdService.this.statsdReportIndices || StatsdService.this.statsdReportShards ) { StatsdReporter indicesReporter = new StatsdReporterIndices( this.getIndexShards(StatsdService.this.indicesService), StatsdService.this.statsdReportShards ); indicesReporter .setStatsDClient(StatsdService.this.statsdClient) .run(); } } } try { Thread.sleep(StatsdService.this.statsdRefreshInternal.millis()); } catch (InterruptedException e1) { continue; } } } private List<IndexShard> getIndexShards(IndicesService indicesService) { List<IndexShard> indexShards = Lists.newArrayList(); String[] indices = indicesService.indices().toArray(new String[] {}); for (String indexName : indices) { IndexService indexService = indicesService.indexServiceSafe(indexName); for (int shardId : indexService.shardIds()) { indexShards.add(indexService.shard(shardId)); } } return indexShards; } } }
package org.helianto.seed; import java.io.IOException; import java.nio.charset.Charset; import java.text.ParseException; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Properties; import javax.inject.Inject; import org.helianto.security.resolver.CurrentUserHandlerMethodArgumentResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.format.Formatter; import org.springframework.format.FormatterRegistry; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; import com.fasterxml.jackson.databind.ObjectMapper; import freemarker.template.TemplateException; /** * Configuracao Java. * * @author mauriciofernandesdecastro */ public abstract class AbstractServletContextConfig extends WebMvcConfigurerAdapter { public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Inject private ObjectMapper mapper; @Bean public CurrentUserHandlerMethodArgumentResolver currentUserHandlerMethodArgumentResolver() { return new CurrentUserHandlerMethodArgumentResolver(); } /** * Required to allow matrix type params. * @return */ @Bean public RequestMappingHandlerMapping requestMappingHandlerMapping() { final RequestMappingHandlerMapping requestMappingHandlerMapping = new RequestMappingHandlerMapping(); requestMappingHandlerMapping.setRemoveSemicolonContent(false); return requestMappingHandlerMapping; } /** * Argument resolvers. */ @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.addAll( Arrays.asList( currentUserHandlerMethodArgumentResolver() ) ); } /** * Freemarker configurer. * * @throws TemplateException * @throws IOException */ @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setPreferFileSystemAccess(false); configurer.setTemplateLoaderPaths( new String[] {"/WEB-INF/classes/freemarker/" ,"/WEB-INF/freemarker/" ,"classpath:/freemarker/"} ); Properties props = new Properties(); props.put("default_encoding", "utf-8"); props.put("number_format", "computer"); props.put("whitespace_stripping", "true"); configurer.setFreemarkerSettings(props); return configurer; } /** * Freemarker view resolver. */ public ViewResolver freeMarkerViewResolver() { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); resolver.setExposeSpringMacroHelpers(true); resolver.setCache(true); resolver.setPrefix(""); resolver.setSuffix(".ftl"); resolver.setContentType("text/html;charset=iso-8859-1"); return resolver; } @Bean public ViewResolver viewResolver() { ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver(); resolver.setViewResolvers(Arrays.asList(freeMarkerViewResolver())); return resolver; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } /** * Formatters. */ @Override public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new StringFormatter()); super.addFormatters(registry); } public class StringFormatter implements Formatter<String>{ @Override public String print(String object, Locale locale) { return object; } @Override public String parse(String text, Locale locale) throws ParseException { return new String(text); } } /** * Jackson json converter. */ @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(mapper); converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,APPLICATION_JSON_UTF8)); return converter; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //para converter String direto pra json StringHttpMessageConverter stringConverter = new StringHttpMessageConverter( Charset.forName("UTF-8")); stringConverter.setSupportedMediaTypes(Arrays.asList( MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON)); //Converter byte[] para imagem ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); arrayHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.IMAGE_JPEG , MediaType.IMAGE_PNG , MediaType.IMAGE_GIF)); converters.add(arrayHttpMessageConverter); converters.add(stringConverter); converters.add(mappingJackson2HttpMessageConverter()); super.configureMessageConverters(converters); } /** * Commons multipart resolver. */ @Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(10000000); return resolver; } }
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.help.HelpFile; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.IdBasedFetcher; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.WebFetchers; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.strings.StringUtil; public class TitleFetcher implements IdBasedFetcher { private final ImportFormatPreferences preferences; public TitleFetcher(ImportFormatPreferences preferences) { this.preferences = preferences; } @Override public String getName() { return "Title"; } @Override public Optional<HelpFile> getHelpPage() { return Optional.of(HelpFile.FETCHER_TITLE); } @Override public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { if (StringUtil.isBlank(identifier)) { return Optional.empty(); } BibEntry entry = new BibEntry(); entry.setField(StandardField.TITLE, identifier); Optional<DOI> doi = WebFetchers.getIdFetcherForIdentifier(DOI.class).findIdentifier(entry); if (doi.isEmpty()) { return Optional.empty(); } DoiFetcher doiFetcher = new DoiFetcher(this.preferences); return doiFetcher.performSearchById(doi.get().getDOI()); } }
package org.jfree.chart.renderer.category; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.LegendItem; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.AreaRendererEndType; import org.jfree.chart.util.ParamChecks; import org.jfree.data.category.CategoryDataset; /** * A category item renderer that draws area charts. You can use this renderer * with the {@link CategoryPlot} class. The example shown here is generated * by the <code>AreaChartDemo1.java</code> program included in the JFreeChart * Demo Collection: * <br><br> * <img src="../../../../../images/AreaRendererSample.png" * alt="AreaRendererSample.png"> */ public class AreaRenderer extends AbstractCategoryItemRenderer implements Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -4231878281385812757L; /** A flag that controls how the ends of the areas are drawn. */ private AreaRendererEndType endType; /** * Creates a new renderer. */ public AreaRenderer() { super(); this.endType = AreaRendererEndType.TAPER; setDefaultLegendShape(new Rectangle2D.Double(-4.0, -4.0, 8.0, 8.0)); } /** * Returns a token that controls how the renderer draws the end points. * The default value is {@link AreaRendererEndType#TAPER}. * * @return The end type (never <code>null</code>). * * @see #setEndType */ public AreaRendererEndType getEndType() { return this.endType; } /** * Sets a token that controls how the renderer draws the end points, and * sends a {@link RendererChangeEvent} to all registered listeners. * * @param type the end type (<code>null</code> not permitted). * * @see #getEndType() */ public void setEndType(AreaRendererEndType type) { ParamChecks.nullNotPermitted(type, "type"); this.endType = type; fireChangeEvent(); } /** * Returns a legend item for a series. * * @param datasetIndex the dataset index (zero-based). * @param series the series index (zero-based). * * @return The legend item. */ @Override public LegendItem getLegendItem(int datasetIndex, int series) { // if there is no plot, there is no dataset to access... CategoryPlot cp = getPlot(); if (cp == null) { return null; } // check that a legend item needs to be displayed... if (!isSeriesVisible(series) || !isSeriesVisibleInLegend(series)) { return null; } CategoryDataset dataset = cp.getDataset(datasetIndex); String label = getLegendItemLabelGenerator().generateLabel(dataset, series); String description = label; String toolTipText = null; if (getLegendItemToolTipGenerator() != null) { toolTipText = getLegendItemToolTipGenerator().generateLabel( dataset, series); } String urlText = null; if (getLegendItemURLGenerator() != null) { urlText = getLegendItemURLGenerator().generateLabel(dataset, series); } Shape shape = lookupLegendShape(series); Paint paint = lookupSeriesPaint(series); Paint outlinePaint = lookupSeriesOutlinePaint(series); Stroke outlineStroke = lookupSeriesOutlineStroke(series); LegendItem result = new LegendItem(label, description, toolTipText, urlText, shape, paint, outlineStroke, outlinePaint); result.setLabelFont(lookupLegendTextFont(series)); Paint labelPaint = lookupLegendTextPaint(series); if (labelPaint != null) { result.setLabelPaint(labelPaint); } result.setDataset(dataset); result.setDatasetIndex(datasetIndex); result.setSeriesKey(dataset.getRowKey(series)); result.setSeriesIndex(series); return result; } /** * Draw a single data item. * * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the data plot area. * @param plot the plot. * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param row the row index (zero-based). * @param column the column index (zero-based). * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, int pass) { // do nothing if item is not visible or null if (!getItemVisible(row, column)) { return; } Number value = dataset.getValue(row, column); if (value == null) { return; } PlotOrientation orientation = plot.getOrientation(); RectangleEdge axisEdge = plot.getDomainAxisEdge(); int count = dataset.getColumnCount(); float x0 = (float) domainAxis.getCategoryStart(column, count, dataArea, axisEdge); float x1 = (float) domainAxis.getCategoryMiddle(column, count, dataArea, axisEdge); float x2 = (float) domainAxis.getCategoryEnd(column, count, dataArea, axisEdge); x0 = Math.round(x0); x1 = Math.round(x1); x2 = Math.round(x2); if (this.endType == AreaRendererEndType.TRUNCATE) { if (column == 0) { x0 = x1; } else if (column == getColumnCount() - 1) { x2 = x1; } } double yy1 = value.doubleValue(); double yy0 = 0.0; if (this.endType == AreaRendererEndType.LEVEL) { yy0 = yy1; } if (column > 0) { Number n0 = dataset.getValue(row, column - 1); if (n0 != null) { yy0 = (n0.doubleValue() + yy1) / 2.0; } } double yy2 = 0.0; if (column < dataset.getColumnCount() - 1) { Number n2 = dataset.getValue(row, column + 1); if (n2 != null) { yy2 = (n2.doubleValue() + yy1) / 2.0; } } else if (this.endType == AreaRendererEndType.LEVEL) { yy2 = yy1; } RectangleEdge edge = plot.getRangeAxisEdge(); float y0 = (float) rangeAxis.valueToJava2D(yy0, dataArea, edge); float y1 = (float) rangeAxis.valueToJava2D(yy1, dataArea, edge); float y2 = (float) rangeAxis.valueToJava2D(yy2, dataArea, edge); float yz = (float) rangeAxis.valueToJava2D(0.0, dataArea, edge); double labelXX = x1; double labelYY = y1; g2.setPaint(getItemPaint(row, column)); g2.setStroke(getItemStroke(row, column)); GeneralPath area = new GeneralPath(); if (orientation == PlotOrientation.VERTICAL) { area.moveTo(x0, yz); area.lineTo(x0, y0); area.lineTo(x1, y1); area.lineTo(x2, y2); area.lineTo(x2, yz); } else if (orientation == PlotOrientation.HORIZONTAL) { area.moveTo(yz, x0); area.lineTo(y0, x0); area.lineTo(y1, x1); area.lineTo(y2, x2); area.lineTo(yz, x2); double temp = labelXX; labelXX = labelYY; labelYY = temp; } area.closePath(); g2.setPaint(getItemPaint(row, column)); g2.fill(area); // draw the item labels if there are any... if (isItemLabelVisible(row, column)) { drawItemLabel(g2, orientation, dataset, row, column, labelXX, labelYY, (value.doubleValue() < 0.0)); } // submit the current data point as a crosshair candidate int datasetIndex = plot.findDatasetIndex(dataset); updateCrosshairValues(state.getCrosshairState(), dataset.getRowKey(row), dataset.getColumnKey(column), yy1, datasetIndex, x1, y1, orientation); // add an item entity, if this information is being collected EntityCollection entities = state.getEntityCollection(); if (entities != null) { addItemEntity(entities, dataset, row, column, area); } } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object to test (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof AreaRenderer)) { return false; } AreaRenderer that = (AreaRenderer) obj; if (!this.endType.equals(that.endType)) { return false; } return super.equals(obj); } /** * Returns an independent copy of the renderer. * * @return A clone. * * @throws CloneNotSupportedException should not happen. */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package org.jscep.transport; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import net.jcip.annotations.ThreadSafe; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.bouncycastle.util.encoders.Base64; import org.jscep.transport.request.PkiOperationRequest; import org.jscep.transport.request.Request; import org.jscep.transport.response.ScepResponseHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AbstractTransport representing the <code>HTTP POST</code> method. */ @ThreadSafe final class UrlConnectionPostTransport extends AbstractTransport { private static final Logger LOGGER = LoggerFactory .getLogger(UrlConnectionPostTransport.class); /** * Creates a new <tt>HttpPostTransport</tt> for the given <tt>URL</tt>. * * @param url * the <tt>URL</tt> to send <tt>POST</tt> requests to. */ public UrlConnectionPostTransport(final URL url) { super(url); } /** * {@inheritDoc} */ @Override public <T> T sendRequest(final Request msg, final ScepResponseHandler<T> handler) throws TransportException { if (!PkiOperationRequest.class.isAssignableFrom(msg.getClass())) { throw new IllegalArgumentException( "POST transport may not be used for " + msg.getOperation() + " messages."); } URL url = getUrl(msg.getOperation()); HttpURLConnection conn; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/octet-stream"); } catch (IOException e) { throw new TransportException(e); } conn.setDoOutput(true); byte[] message; try { message = Base64.decode(msg.getMessage().getBytes( Charsets.US_ASCII.name())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } OutputStream stream = null; try { stream = new BufferedOutputStream(conn.getOutputStream()); stream.write(message); } catch (IOException e) { throw new TransportException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { LOGGER.error("Failed to close output stream", e); } } } try { int responseCode = conn.getResponseCode(); String responseMessage = conn.getResponseMessage(); LOGGER.debug("Received '{} {}' when sending {} to {}", varargs(responseCode, responseMessage, msg, url)); if (responseCode != HttpURLConnection.HTTP_OK) { throw new TransportException(responseCode + " " + responseMessage); } } catch (IOException e) { throw new TransportException("Error connecting to server.", e); } byte[] response; try { response = IOUtils.toByteArray(conn.getInputStream()); } catch (IOException e) { throw new TransportException("Error reading response stream", e); } return handler.getResponse(response, conn.getContentType()); } }
package org.lanternpowered.server.util; import com.google.common.reflect.TypeToken; import org.spongepowered.api.CatalogType; import org.spongepowered.api.advancement.Advancement; import org.spongepowered.api.data.DataRegistration; import org.spongepowered.api.data.key.Key; import org.spongepowered.api.data.manipulator.mutable.item.LoreData; import org.spongepowered.api.data.value.BaseValue; import org.spongepowered.api.data.value.mutable.Value; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.entity.living.complex.EnderDragon; import org.spongepowered.api.entity.living.monster.Slime; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import javax.annotation.Nullable; @SuppressWarnings("unchecked") public final class TypeTokenHelper { public static void main(String... args) { test(new TypeToken<Key<?>>() {}, new TypeToken<Key<BaseValue<?>>>() {}); test(new TypeToken<Key<BaseValue<?>>>() {}, new TypeToken<Key<BaseValue<?>>>() {}); test(new TypeToken<Key<BaseValue<?>>>() {}, new TypeToken<Key<BaseValue<CatalogType>>>() {}); test(new TypeToken<Key<BaseValue<?>>>() {}, new TypeToken<Key<BaseValue<? extends CatalogType>>>() {}); test(new TypeToken<Key<BaseValue<?>>>() {}, new TypeToken<Key<BaseValue<? extends Advancement>>>() {}); test(new TypeToken<Key<BaseValue<Advancement>>>() {}, new TypeToken<Key<BaseValue<Integer>>>() {}); test(new TypeToken<Key<BaseValue<Slime>>>() {}, new TypeToken<Key<BaseValue<? extends EnderDragon>>>() {}); test(new TypeToken<Key<BaseValue<EnderDragon>>>() {}, new TypeToken<Key<BaseValue<? extends Living>>>() {}); test(new TypeToken<Key<BaseValue<EnderDragon>>>() {}, new TypeToken<Key<BaseValue<? extends Living>>>() {}); test(TypeToken.of(Key.class), new TypeToken<Key<BaseValue<? extends Living>>>() {}); test(new TypeToken<DataRegistration>() {}, new TypeToken<DataRegistration<?,?>>() {}); test(new TypeToken<DataRegistration>() {}, new TypeToken<DataRegistration<LoreData,?>>() {}); test(new TypeToken<DataRegistration<?,?>>() {}, new TypeToken<DataRegistration<LoreData,?>>() {}); // Enclosing classes testing test(new TypeToken<A<Object>.B<Value<Double>>>() {}, new TypeToken<A<Object>.B<Value<? extends Number>>>() {}); test(new TypeToken<A<Key<BaseValue<EnderDragon>>>.B<Value<Double>>>() {}, new TypeToken<A<Key<BaseValue<Slime>>>.B<Value<? extends Number>>>() {}); test(new TypeToken<A<Key<BaseValue<EnderDragon>>>.B<Value<Double>>>() {}, new TypeToken<A<Key<BaseValue<? extends Living>>>.B<Value<? extends Number>>>() {}); } private static class A<T> { private class B<V> { } } private static void test(TypeToken<?> a, TypeToken<?> b) { System.out.printf("{\n\tA: %s\n\tB: %s\n\tAB: %s\n\tBA: %s\n}\n", a, b, isAssignable(a, b), isAssignable(b, a)); } public static boolean isAssignable(TypeToken<?> type, TypeToken<?> toType) { return isAssignable(type.getType(), toType.getType()); } public static boolean isAssignable(Type type, Type toType) { return isAssignable(type, toType, null, 0); } private static boolean isAssignable(Type type, Type toType, @Nullable Type parent, int index) { if (type.equals(toType)) { return true; } if (toType instanceof Class) { return isAssignable(type, (Class<?>) toType, parent, index); } if (toType instanceof ParameterizedType) { return isAssignable(type, (ParameterizedType) toType, parent, index); } if (toType instanceof TypeVariable) { return isAssignable(type, (TypeVariable) toType, parent, index); } if (toType instanceof WildcardType) { return isAssignable(type, (WildcardType) toType, parent, index); } if (toType instanceof GenericArrayType) { return isAssignable(type, (GenericArrayType) toType, parent, index); } throw new IllegalStateException("Unsupported type: " + type); } private static boolean isAssignable(Type type, Class<?> toType, @Nullable Type parent, int index) { if (type instanceof Class) { final Class<?> other = (Class<?>) type; final Class<?> toEnclosing = toType.getEnclosingClass(); if (toEnclosing != null && !Modifier.isStatic(toType.getModifiers())) { final Class<?> otherEnclosing = other.getEnclosingClass(); if (otherEnclosing == null || !isAssignable(otherEnclosing, toEnclosing, null, 0)) { return false; } } return toType.isAssignableFrom(other); } if (type instanceof ParameterizedType) { final ParameterizedType other = (ParameterizedType) type; final Class<?> toEnclosing = toType.getEnclosingClass(); if (toEnclosing != null && !Modifier.isStatic(toType.getModifiers())) { final Type otherEnclosing = other.getOwnerType(); if (otherEnclosing == null || !isAssignable(otherEnclosing, toEnclosing, null, 0)) { return false; } } return toType.isAssignableFrom((Class<?>) other.getRawType()); } if (type instanceof TypeVariable) { final TypeVariable other = (TypeVariable) type; return allSupertypes(type, other.getBounds()); } if (type instanceof WildcardType) { final WildcardType other = (WildcardType) type; return allWildcardSupertypes(toType, other.getUpperBounds(), parent, index) && allAssignable(toType, other.getLowerBounds()); } if (type instanceof GenericArrayType) { final GenericArrayType other = (GenericArrayType) type; return toType.equals(Object.class) || (toType.isArray() && isAssignable(other.getGenericComponentType(), toType.getComponentType(), parent, index)); } throw new IllegalStateException("Unsupported type: " + type); } private static boolean isAssignable(Type type, ParameterizedType toType, @Nullable Type parent, int index) { if (type instanceof Class) { final Class<?> other = (Class<?>) type; final Class<?> toRaw = (Class<?>) toType.getRawType(); final Type toEnclosing = toType.getOwnerType(); if (toEnclosing != null && !Modifier.isStatic(toRaw.getModifiers())) { final Class<?> otherEnclosing = other.getEnclosingClass(); if (otherEnclosing == null || !isAssignable(otherEnclosing, toEnclosing, null, 0)) { return false; } } if (!toRaw.isAssignableFrom(other)) { return false; } // Check if the default generic parameters match the parameters // of the parameterized type final Type[] toTypes = toType.getActualTypeArguments(); final TypeVariable[] types = toRaw.getTypeParameters(); if (types.length != toTypes.length) { return false; } for (int i = 0; i < types.length; i++) { if (!isAssignable(types[i], toTypes[i], other, i)) { return false; } } return true; } if (type instanceof ParameterizedType) { ParameterizedType other = (ParameterizedType) type; final Class<?> otherRaw = (Class<?>) other.getRawType(); final Class<?> toRaw = (Class<?>) toType.getRawType(); if (!toRaw.isAssignableFrom(otherRaw)) { return false; } final Type toEnclosing = toType.getOwnerType(); if (toEnclosing != null && !Modifier.isStatic(toRaw.getModifiers())) { final Type otherEnclosing = other.getOwnerType(); if (otherEnclosing == null || !isAssignable(otherEnclosing, toEnclosing, null, 0)) { return false; } } final Type[] types; if (otherRaw.equals(toRaw)) { types = other.getActualTypeArguments(); } else { // Get the type parameters based on the super class other = (ParameterizedType) TypeToken.of(type).getSupertype((Class) toRaw).getType(); types = other.getActualTypeArguments(); } final Type[] toTypes = toType.getActualTypeArguments(); if (types.length != toTypes.length) { return false; } for (int i = 0; i < types.length; i++) { if (!isAssignable(types[i], toTypes[i], other, i)) { return false; } } return true; } if (type instanceof TypeVariable) { final TypeVariable other = (TypeVariable) type; return allSupertypes(toType, other.getBounds()); } if (type instanceof WildcardType) { final WildcardType other = (WildcardType) type; return allWildcardSupertypes(toType, other.getUpperBounds(), parent, index) && allAssignable(toType, other.getLowerBounds()); } if (type instanceof GenericArrayType) { final GenericArrayType other = (GenericArrayType) type; final Class<?> rawType = (Class<?>) toType.getRawType(); return rawType.equals(Object.class) || (rawType.isArray() && isAssignable(other.getGenericComponentType(), rawType.getComponentType(), parent, index)); } throw new IllegalStateException("Unsupported type: " + type); } private static boolean isAssignable(Type type, TypeVariable toType, @Nullable Type parent, int index) { return allAssignable(type, toType.getBounds()); } private static boolean isAssignable(Type type, WildcardType toType, @Nullable Type parent, int index) { return allWildcardAssignable(type, toType.getUpperBounds(), parent, index) && allSupertypes(type, toType.getLowerBounds()); } private static boolean isAssignable(Type type, GenericArrayType toType, @Nullable Type parent, int index) { if (type instanceof Class) { final Class<?> other = (Class<?>) type; return other.isArray() && isAssignable(other.getComponentType(), toType.getGenericComponentType(), parent, index); } if (type instanceof ParameterizedType) { final ParameterizedType other = (ParameterizedType) type; final Class<?> rawType = (Class<?>) other.getRawType(); return rawType.isArray() && isAssignable(rawType.getComponentType(), toType.getGenericComponentType(), parent, index); } if (type instanceof TypeVariable) { final TypeVariable other = (TypeVariable) type; return allSupertypes(toType, other.getBounds()); } if (type instanceof WildcardType) { final WildcardType other = (WildcardType) type; return allWildcardSupertypes(toType, other.getUpperBounds(), parent, index) && allAssignable(toType, other.getLowerBounds()); } if (type instanceof GenericArrayType) { final GenericArrayType other = (GenericArrayType) type; return isAssignable(other.getGenericComponentType(), toType.getGenericComponentType(), parent, index); } throw new IllegalStateException("Unsupported type: " + type); } private static Type[] processBounds(Type[] bounds, @Nullable Type parent, int index) { if (bounds.length == 0 || (bounds.length == 1 && bounds[0].equals(Object.class))) { Class<?> theClass = null; if (parent instanceof Class) { theClass = (Class<?>) parent; } else if (parent instanceof ParameterizedType) { theClass = (Class<?>) ((ParameterizedType) parent).getRawType(); } if (theClass != null) { final TypeVariable[] typeVariables = theClass.getTypeParameters(); bounds = typeVariables[index].getBounds(); // Strip the new bounds down for (int i = 0; i < bounds.length; i++) { if (bounds[i] instanceof TypeVariable || bounds[i] instanceof WildcardType || bounds[i] instanceof GenericArrayType) { // No idea how to handle this type bounds[i] = Object.class; } else if (bounds[i] instanceof ParameterizedType) { bounds[i] = ((ParameterizedType) bounds[i]).getRawType(); } } } } return bounds; } private static boolean allWildcardSupertypes(Type type, Type[] bounds, @Nullable Type parent, int index) { return allSupertypes(type, processBounds(bounds, parent, index)); } private static boolean allWildcardAssignable(Type type, Type[] bounds, @Nullable Type parent, int index) { return allAssignable(type, processBounds(bounds, parent, index)); } private static boolean allAssignable(Type type, Type[] bounds) { for (Type toType : bounds) { // Skip the Object class if (!isAssignable(type, toType, null, 0)) { return false; } } return true; } private static boolean allSupertypes(Type type, Type[] bounds) { for (Type toType : bounds) { // Skip the Object class if (!isAssignable(toType, type, null, 0)) { return false; } } return true; } private TypeTokenHelper() { } }
package org.lesscss4j.transform; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import org.lesscss4j.error.ErrorUtils; import org.lesscss4j.error.LessCssException; import org.lesscss4j.model.Declaration; import org.lesscss4j.model.PositionAware; import org.lesscss4j.model.expression.Expression; import org.lesscss4j.transform.manager.TransformerManager; public class DeclarationTransformer extends AbstractTransformer<Declaration> { public DeclarationTransformer() { } public DeclarationTransformer(TransformerManager transformerManager) { super(transformerManager); } public List<Declaration> transform(Declaration declaration, EvaluationContext context) { if (declaration.getValues() == null) return null; Declaration transformed = new Declaration(declaration, false); for (ListIterator<Object> iter = declaration.getValues().listIterator(); iter.hasNext();) { Object value = iter.next(); value = transformDeclarationValue(value, declaration, context); transformed.addValue(value); } return Arrays.asList(transformed); } protected Object transformDeclarationValue(Object value, Declaration declaration, EvaluationContext context) { if (value instanceof Expression) { try { value = ((Expression) value).evaluate(context); } catch (LessCssException ex) { ErrorUtils.handleError(context.getErrorHandler(), (PositionAware) value, ex); } } return value; } }
package org.restlet.engine.connector; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.List; import org.restlet.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpsExchange; /** * The default {@link HttpExchangeCall} fails to extract certificates from the SSL connection. * This class implements {@link #getCertificates()} to extract certificates. */ @SuppressWarnings("restriction") public class HttpsExchangeCall extends HttpExchangeCall { private static final Logger log = LoggerFactory.getLogger(HttpsExchangeCall.class); private final HttpsExchange sexchange; public HttpsExchangeCall(Server server, HttpExchange exchange) { this(server, exchange, true); } public HttpsExchangeCall(Server server, HttpExchange exchange, boolean confidential) { super(server, exchange, confidential); if (exchange instanceof HttpsExchange) { sexchange = (HttpsExchange) exchange; } else { sexchange = null; } } @Override public List<Certificate> getCertificates() { if (sexchange == null) { log.debug("Cannot extract peer certificates from unsecure connection."); return null; } Certificate[] certs = null; try { certs = sexchange.getSSLSession().getPeerCertificates(); if (log.isDebugEnabled()) { log.debug("Found " + (certs == null ? "no" : Integer.toString(certs.length)) + " peer certificate(s)."); } } catch (Exception e) { log.debug("Unable to find peer certificates - " + e); } List<Certificate> lcerts = null; if (certs != null) { lcerts = new ArrayList<Certificate>(); for (int i = 0; i < certs.length; i++) { lcerts.add(certs[i]); } } return lcerts; } }
package org.robolectric.shadows; import org.robolectric.Robolectric; import org.robolectric.internal.Implementation; import org.robolectric.internal.Implements; import java.util.HashMap; import java.util.Map; @Implements(value = Robolectric.Anything.class, className = "android.os.SystemProperties") public class ShadowSystemProperties { private static final Map<String, Object> VALUES = new HashMap<String, Object>(); static { VALUES.put("ro.build.version.sdk", 12); VALUES.put("ro.debuggable", 0); VALUES.put("log.closeguard.Animation", false); } @Implementation public static String get(String key) { complain("SystemProperties.get(" + key + ")"); return VALUES.get(key).toString(); } @Implementation public static String get(String key, String def) { complain("SystemProperties.get(" + key + ", " + def + ")"); Object value = VALUES.get(key); return value == null ? def : value.toString(); } @Implementation public static int getInt(String key, int def) { complain("SystemProperties.getInt(" + key + ", " + def + ")"); Object value = VALUES.get(key); return value == null ? def : (Integer) value; } @Implementation public static long getLong(String key, long def) { complain("SystemProperties.getLong(" + key + ", " + def + ")"); Object value = VALUES.get(key); return value == null ? def : (Long) value; } @Implementation public static boolean getBoolean(String key, boolean def) { complain("SystemProperties.getBoolean(" + key + ", " + def + ")"); Object value = VALUES.get(key); return value == null ? def : (Boolean) value; } private static void complain(String s) { // new RuntimeException(s).printStackTrace(); } }
package org.spongepowered.api.event; import com.flowpowered.math.vector.Vector3d; import com.flowpowered.math.vector.Vector3f; import com.flowpowered.math.vector.Vector3i; import com.google.common.base.Optional; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Maps; import org.spongepowered.api.Game; import org.spongepowered.api.block.BlockLoc; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityInteractionType; import org.spongepowered.api.entity.Item; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.entity.player.gamemode.GameMode; import org.spongepowered.api.entity.projectile.FishHook; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.entity.projectile.source.ProjectileSource; import org.spongepowered.api.entity.weather.Lightning; import org.spongepowered.api.event.block.BlockBreakEvent; import org.spongepowered.api.event.block.BlockBurnEvent; import org.spongepowered.api.event.block.BlockChangeEvent; import org.spongepowered.api.event.block.BlockDispenseEvent; import org.spongepowered.api.event.block.BlockIgniteEvent; import org.spongepowered.api.event.block.BlockInteractEvent; import org.spongepowered.api.event.block.BlockMoveEvent; import org.spongepowered.api.event.block.BlockPlaceEvent; import org.spongepowered.api.event.block.BlockRandomTickEvent; import org.spongepowered.api.event.block.BlockUpdateEvent; import org.spongepowered.api.event.block.FloraGrowEvent; import org.spongepowered.api.event.block.FluidSpreadEvent; import org.spongepowered.api.event.block.LeafDecayEvent; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.event.entity.EntityBreakBlockEvent; import org.spongepowered.api.event.entity.EntityChangeBlockEvent; import org.spongepowered.api.event.entity.EntityChangeHealthEvent; import org.spongepowered.api.event.entity.EntityCollisionEvent; import org.spongepowered.api.event.entity.EntityCollisionWithBlockEvent; import org.spongepowered.api.event.entity.EntityCollisionWithEntityEvent; import org.spongepowered.api.event.entity.EntityDeathEvent; import org.spongepowered.api.event.entity.EntityDismountEvent; import org.spongepowered.api.event.entity.EntityDropItemEvent; import org.spongepowered.api.event.entity.EntityInteractBlockEvent; import org.spongepowered.api.event.entity.EntityInteractEntityEvent; import org.spongepowered.api.event.entity.EntityInteractEvent; import org.spongepowered.api.event.entity.EntityMountEvent; import org.spongepowered.api.event.entity.EntityMoveEvent; import org.spongepowered.api.event.entity.EntityPickUpItemEvent; import org.spongepowered.api.event.entity.EntityPlaceBlockEvent; import org.spongepowered.api.event.entity.EntitySpawnEvent; import org.spongepowered.api.event.entity.EntityTameEvent; import org.spongepowered.api.event.entity.EntityTeleportEvent; import org.spongepowered.api.event.entity.EntityUpdateEvent; import org.spongepowered.api.event.entity.ProjectileLaunchEvent; import org.spongepowered.api.event.entity.living.player.PlayerBreakBlockEvent; import org.spongepowered.api.event.entity.living.player.PlayerChangeBlockEvent; import org.spongepowered.api.event.entity.living.player.PlayerChangeGameModeEvent; import org.spongepowered.api.event.entity.living.player.PlayerChangeWorldEvent; import org.spongepowered.api.event.entity.living.player.PlayerChatEvent; import org.spongepowered.api.event.entity.living.player.PlayerDeathEvent; import org.spongepowered.api.event.entity.living.player.PlayerDropItemEvent; import org.spongepowered.api.event.entity.living.player.PlayerInteractBlockEvent; import org.spongepowered.api.event.entity.living.player.PlayerInteractEntityEvent; import org.spongepowered.api.event.entity.living.player.PlayerInteractEvent; import org.spongepowered.api.event.entity.living.player.PlayerJoinEvent; import org.spongepowered.api.event.entity.living.player.PlayerMoveEvent; import org.spongepowered.api.event.entity.living.player.PlayerPickUpItemEvent; import org.spongepowered.api.event.entity.living.player.PlayerPlaceBlockEvent; import org.spongepowered.api.event.entity.living.player.PlayerQuitEvent; import org.spongepowered.api.event.entity.living.player.PlayerUpdateEvent; import org.spongepowered.api.event.entity.living.player.fishing.PlayerCastFishingLineEvent; import org.spongepowered.api.event.entity.living.player.fishing.PlayerHookedEntityEvent; import org.spongepowered.api.event.entity.living.player.fishing.PlayerRetractFishingLineEvent; import org.spongepowered.api.event.message.CommandEvent; import org.spongepowered.api.event.message.MessageEvent; import org.spongepowered.api.event.server.StatusPingEvent; import org.spongepowered.api.event.weather.LightningStrikeEvent; import org.spongepowered.api.event.weather.WeatherChangeEvent; import org.spongepowered.api.event.world.ChunkForcedEvent; import org.spongepowered.api.event.world.ChunkLoadEvent; import org.spongepowered.api.event.world.ChunkPostGenerateEvent; import org.spongepowered.api.event.world.ChunkPostPopulateEvent; import org.spongepowered.api.event.world.ChunkPreGenerateEvent; import org.spongepowered.api.event.world.ChunkPrePopulateEvent; import org.spongepowered.api.event.world.ChunkUnforcedEvent; import org.spongepowered.api.event.world.ChunkUnloadEvent; import org.spongepowered.api.event.world.GameRuleChangeEvent; import org.spongepowered.api.event.world.WorldLoadEvent; import org.spongepowered.api.event.world.WorldUnloadEvent; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.status.StatusClient; import org.spongepowered.api.text.message.Message; import org.spongepowered.api.util.Direction; import org.spongepowered.api.util.command.CommandSource; import org.spongepowered.api.util.event.factory.ClassGeneratorProvider; import org.spongepowered.api.util.event.factory.EventFactory; import org.spongepowered.api.util.event.factory.FactoryProvider; import org.spongepowered.api.util.event.factory.NullPolicy; import org.spongepowered.api.world.Chunk; import org.spongepowered.api.world.ChunkManager.LoadingTicket; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import org.spongepowered.api.world.gen.Populator; import org.spongepowered.api.world.weather.Weather; import org.spongepowered.api.world.weather.WeatherVolume; import java.util.Collection; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * Generates Sponge event implementations. */ public final class SpongeEventFactory { private static final FactoryProvider factoryProvider; private static final LoadingCache<Class<?>, EventFactory<?>> factories; static { factoryProvider = new ClassGeneratorProvider("org.spongepowered.api.event.impl"); factoryProvider.setNullPolicy(NullPolicy.NON_NULL_BY_DEFAULT); factories = CacheBuilder.newBuilder() .build( new CacheLoader<Class<?>, EventFactory<?>>() { @Override public EventFactory<?> load(Class<?> type) { return factoryProvider.create(type, AbstractEvent.class); } }); } private SpongeEventFactory() { } @SuppressWarnings("unchecked") private static <T> T createEvent(Class<T> type, Map<String, Object> values) { return (T) factories.getUnchecked(type).apply(values); } /** * Creates a new {@link BlockBreakEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @param exp The experience to give, or take for negative values * @param droppedItems The items to drop * @return A new instance of the event */ public static BlockBreakEvent createBlockBreak(Game game, Cause cause, BlockLoc block, BlockSnapshot replacementBlock, double exp, Collection<Item> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("replacementBlock", replacementBlock); values.put("exp", exp); values.put("droppedItems", droppedItems); return createEvent(BlockBreakEvent.class, values); } /** * Creates a new {@link BlockBurnEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static BlockBurnEvent createBlockBurn(Game game, Cause cause, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("replacementBlock", replacementBlock); return createEvent(BlockBurnEvent.class, values); } /** * Creates a new {@link BlockChangeEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static BlockChangeEvent createBlockChange(Game game, Cause cause, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("replacementBlock", replacementBlock); return createEvent(BlockChangeEvent.class, values); } /** * Creates a new {@link BlockDispenseEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param velocity The velocity to dispense the item at * @param dispensedItem The item to dispense from the block * @return A new instance of the event */ public static BlockDispenseEvent createBlockDispense(Game game, Cause cause, BlockLoc block, Vector3d velocity, ItemStack dispensedItem) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("velocity", velocity); values.put("dispensedItem", dispensedItem); return createEvent(BlockDispenseEvent.class, values); } /** * Creates a new {@link BlockIgniteEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @return A new instance of the event */ public static BlockIgniteEvent createBlockIgnite(Game game, Cause cause, BlockLoc block) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); return createEvent(BlockIgniteEvent.class, values); } /** * Creates a new {@link BlockInteractEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @return A new instance of the event */ public static BlockInteractEvent createBlockInteract(Game game, Cause cause, BlockLoc block) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); return createEvent(BlockInteractEvent.class, values); } /** * Creates a new {@link BlockMoveEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param blocks The blocks affected by this event * @return A new instance of the event */ public static BlockMoveEvent createBlockMove(Game game, Cause cause, List<BlockLoc> blocks) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("blocks", blocks); return createEvent(BlockMoveEvent.class, values); } /** * Creates a new {@link BlockPlaceEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static BlockPlaceEvent createBlockPlace(Game game, Cause cause, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("replacementBlock", replacementBlock); return createEvent(BlockPlaceEvent.class, values); } /** * Creates a new {@link BlockRandomTickEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @return A new instance of the event */ public static BlockRandomTickEvent createBlockRandomTick(Game game, Cause cause, BlockLoc block) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); return createEvent(BlockRandomTickEvent.class, values); } /** * Creates a new {@link BlockUpdateEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param causeBlockType The block causing the update * @return A new instance of the event */ public static BlockUpdateEvent createBlockUpdate(Game game, Cause cause, BlockLoc block, BlockType causeBlockType) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("causeBlockType", causeBlockType); return createEvent(BlockUpdateEvent.class, values); } /** * Creates a new {@link FloraGrowEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static FloraGrowEvent createFloraGrow(Game game, Cause cause, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("replacementBlock", replacementBlock); return createEvent(FloraGrowEvent.class, values); } /** * Creates a new {@link FluidSpreadEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param blocks The blocks affected by this event * @return A new instance of the event */ public static FluidSpreadEvent createFluidSpread(Game game, Cause cause, List<BlockLoc> blocks) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("blocks", blocks); return createEvent(FluidSpreadEvent.class, values); } /** * Creates a new {@link LeafDecayEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static LeafDecayEvent createLeafDecay(Game game, Cause cause, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("replacementBlock", replacementBlock); return createEvent(LeafDecayEvent.class, values); } /** * Creates a new {@link EntityBreakBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @param exp The experience to give, or take for negative values * @param droppedItems The items to drop * @return A new instance of the event */ public static EntityBreakBlockEvent createEntityBreakBlock(Game game, Cause cause, Entity entity, BlockLoc block, BlockSnapshot replacementBlock, double exp, Collection<Item> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", entity); values.put("replacementBlock", replacementBlock); values.put("exp", exp); values.put("droppedItems", droppedItems); return createEvent(EntityBreakBlockEvent.class, values); } /** * Creates a new {@link EntityChangeBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static EntityChangeBlockEvent createEntityChangeBlock(Game game, Cause cause, Entity entity, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", entity); values.put("replacementBlock", replacementBlock); return createEvent(EntityChangeBlockEvent.class, values); } /** * Creates a new {@link EntityChangeHealthEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param newHealth The entity's new health * @param oldHealth The entity's old health * @return A new instance of the event */ public static EntityChangeHealthEvent createEntityChangeHealth(Game game, Cause cause, Entity entity, double newHealth, double oldHealth) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("entity", entity); values.put("newHealth", newHealth); values.put("oldHealth", oldHealth); return createEvent(EntityChangeHealthEvent.class, values); } /** * Creates a new {@link EntityCollisionEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @return A new instance of the event */ public static EntityCollisionEvent createEntityCollision(Game game, Cause cause, Entity entity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("entity", entity); return createEvent(EntityCollisionEvent.class, values); } /** * Creates a new {@link EntityCollisionWithBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param block The block affected by this event * @return A new instance of the event */ public static EntityCollisionWithBlockEvent createEntityCollisionWithBlock(Game game, Cause cause, Entity entity, BlockLoc block) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", entity); return createEvent(EntityCollisionWithBlockEvent.class, values); } /** * Creates a new {@link EntityCollisionWithEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param collided The entity that was collided with * @return A new instance of the event */ public static EntityCollisionWithEntityEvent createEntityCollisionWithEntity(Game game, Cause cause, Entity entity, Entity collided) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("entity", entity); values.put("collided", collided); return createEvent(EntityCollisionWithEntityEvent.class, values); } /** * Creates a new {@link EntityDeathEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param location The location of death * @param droppedItems The items to drop * @return A new instance of the event */ public static EntityDeathEvent createEntityDeath(Game game, Cause cause, Entity entity, Location location, Collection<Item> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("entity", entity); values.put("droppedItems", droppedItems); values.put("location", location); return createEvent(EntityDeathEvent.class, values); } /** * Creates a new {@link EntityDismountEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @param dismounted The entity being dismounted from * @return A new instance of the event */ public static EntityDismountEvent createEntityDismount(Game game, Entity entity, Entity dismounted) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("dismounted", dismounted); return createEvent(EntityDismountEvent.class, values); } /** * Creates a new {@link EntityDropItemEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @param droppedItems The items to drop * @return A new instance of the event */ public static EntityDropItemEvent createEntityDropItem(Game game, Entity entity, Collection<ItemStack> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("droppedItems", droppedItems); return createEvent(EntityDropItemEvent.class, values); } /** * Creates a new {@link EntityInteractBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param block The block affected by this event * @return A new instance of the event */ public static EntityInteractBlockEvent createEntityInteractBlock(Game game, Cause cause, Entity entity, BlockLoc block) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", entity); return createEvent(EntityInteractBlockEvent.class, values); } /** * Creates a new {@link EntityInteractEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @param targetEntity The entity being interacted with * @return A new instance of the event */ public static EntityInteractEntityEvent createEntityInteractEntity(Game game, Entity entity, Entity targetEntity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("targetEntity", targetEntity); return createEvent(EntityInteractEntityEvent.class, values); } /** * Creates a new {@link EntityInteractEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @return A new instance of the event */ public static EntityInteractEvent createEntityInteract(Game game, Entity entity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); return createEvent(EntityInteractEvent.class, values); } /** * Creates a new {@link EntityMountEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @param vehicle The entity being mounted * @return A new instance of the event */ public static EntityMountEvent createEntityMount(Game game, Entity entity, Entity vehicle) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("vehicle", vehicle); return createEvent(EntityMountEvent.class, values); } /** * Creates a new {@link EntityMoveEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @param oldLocation The previous location of the entity * @param newLocation The new location of the entity * @return A new instance of the event */ public static EntityMoveEvent createEntityMove(Game game, Entity entity, Location oldLocation, Location newLocation) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("oldLocation", oldLocation); values.put("newLocation", newLocation); return createEvent(EntityMoveEvent.class, values); } /** * Creates a new {@link EntityPickUpItemEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @param items The items that will be picked up * @return A new instance of the event */ public static EntityPickUpItemEvent createEntityPickUpItem(Game game, Entity entity, Collection<Entity> items) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("items", items); return createEvent(EntityPickUpItemEvent.class, values); } /** * Creates a new {@link EntityPlaceBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static EntityPlaceBlockEvent createEntityPlaceBlock(Game game, Cause cause, Entity entity, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", entity); values.put("replacementBlock", replacementBlock); return createEvent(EntityPlaceBlockEvent.class, values); } /** * Creates a new {@link EntitySpawnEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @param location The location the entity will spawn at * @return A new instance of the event */ public static EntitySpawnEvent createEntitySpawn(Game game, Entity entity, Location location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); values.put("location", location); return createEvent(EntitySpawnEvent.class, values); } /** * Creates a new {@link EntityTameEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @return A new instance of the event */ public static EntityTameEvent createEntityTame(Game game, Entity entity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); return createEvent(EntityTameEvent.class, values); } /** * Creates a new {@link EntityTeleportEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param oldLocation The previous location of the entity * @param newLocation The new location of the entity * @return A new instance of the event */ public static EntityTeleportEvent createEntityTeleport(Game game, Cause cause, Entity entity, Location oldLocation, Location newLocation) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("entity", entity); values.put("oldLocation", oldLocation); values.put("newLocation", newLocation); return createEvent(EntityTeleportEvent.class, values); } /** * Creates a new {@link EntityUpdateEvent}. * * @param game The game instance for this {@link GameEvent} * @param entity The entity involved in this event * @return A new instance of the event */ public static EntityUpdateEvent createEntityUpdate(Game game, Entity entity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", entity); return createEvent(EntityUpdateEvent.class, values); } /** * Creates a new {@link ProjectileLaunchEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param entity The entity involved in this event * @param source The projectile source * @return A new instance of the event */ public static ProjectileLaunchEvent createProjectileLaunch(Game game, Cause cause, Projectile entity, ProjectileSource source) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("entity", entity); values.put("launchedProjectile", entity); values.put("source", Optional.fromNullable(source)); return createEvent(ProjectileLaunchEvent.class, values); } /** * Creates a new {@link CommandEvent}. * * @param game The game instance for this {@link GameEvent} * @param arguments The arguments provided * @param source The source of the command * @param command The command name * @return A new instance of the event */ public static CommandEvent createCommand(Game game, String arguments, CommandSource source, String command) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("arguments", arguments); values.put("source", source); values.put("command", command); return createEvent(CommandEvent.class, values); } /** * Creates a new {@link MessageEvent}. * * @param game The game instance for this {@link GameEvent} * @param source The source of the message * @param message The message to say * @return A new instance of the event */ public static MessageEvent createMessage(Game game, CommandSource source, String message) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("source", source); values.put("message", message); return createEvent(MessageEvent.class, values); } /** * Creates a new {@link PlayerBreakBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param player The player involved in this event * @param direction The block direction the player was breaking * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @param exp The experience to give, or take for negative values * @param droppedItems The items to drop * @return A new instance of the event */ public static PlayerBreakBlockEvent createPlayerBreakBlock(Game game, Cause cause, Player player, Direction direction, BlockLoc block, BlockSnapshot replacementBlock, double exp, Collection<Item> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", player); values.put("replacementBlock", replacementBlock); values.put("player", player); values.put("human", player); values.put("living", player); values.put("blockFaceDirection", direction); return createEvent(PlayerBreakBlockEvent.class, values); } /** * Creates a new {@link PlayerCastFishingLineEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param fishHook The {@link FishHook} effected by this event * @return A new instance of the event */ public static PlayerCastFishingLineEvent createPlayerCastFishingLineEvent(Game game, Player player, FishHook fishHook) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("player", player); values.put("human", player); values.put("living", player); values.put("fishHook", fishHook); return createEvent(PlayerCastFishingLineEvent.class, values); } /** * Creates a new {@link PlayerHookedEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param fishHook The {@link FishHook} affected by this event * @param caughtEntity The {@link Entity} caught by the player, can be null * @return A new instance of the event */ public static PlayerHookedEntityEvent createPlayerHookedEntityEvent(Game game, Player player, FishHook fishHook, Entity caughtEntity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("player", player); values.put("human", player); values.put("living", player); values.put("fishHook", fishHook); values.put("caughtEntity", Optional.fromNullable(caughtEntity)); return createEvent(PlayerHookedEntityEvent.class, values); } /** * Creates a new {@link PlayerRetractFishingLineEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param fishHook The {@link FishHook} affected by this event * @param caughtItem The {@link ItemStack} caught by the player, can be null * @param caughtEntity The {@link Entity} caught by the player, can be null * @return A new instance of the event */ public static PlayerRetractFishingLineEvent createPlayerRetractFishingLineEvent(Game game, Player player, FishHook fishHook, ItemStack caughtItem, Entity caughtEntity) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("player", player); values.put("human", player); values.put("living", player); values.put("fishHook", fishHook); values.put("caughtEntity", Optional.fromNullable(caughtEntity)); values.put("caughtItem", Optional.fromNullable(caughtItem)); return createEvent(PlayerRetractFishingLineEvent.class, values); } /** * Creates a new {@link PlayerChangeBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param player The player involved in this event * @param direction The direction of the block the player was changing * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @return A new instance of the event */ public static PlayerChangeBlockEvent createPlayerChangeBlock(Game game, Cause cause, Player player, Direction direction, BlockLoc block, BlockSnapshot replacementBlock) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", player); values.put("replacementBlock", replacementBlock); values.put("player", player); values.put("human", player); values.put("living", player); values.put("blockFaceDirection", direction); return createEvent(PlayerChangeBlockEvent.class, values); } /** * Creates a new {@link PlayerChangeGameModeEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param newGameMode The game mode to change to * @param oldGameMode The Player's old game mode * @return A new instance of the event */ public static PlayerChangeGameModeEvent createPlayerChangeGameMode(Game game, Player player, GameMode newGameMode, GameMode oldGameMode) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("newGameMode", newGameMode); values.put("oldGameMode", oldGameMode); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerChangeGameModeEvent.class, values); } /** * Creates a new {@link PlayerChangeWorldEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param fromWorld The world the player was in * @param toWorld The world the player is changing to * @return A new instance of the event */ public static PlayerChangeWorldEvent createPlayerChangeWorld(Game game, Player player, World fromWorld, World toWorld) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("fromWorld", fromWorld); values.put("toWorld", toWorld); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerChangeWorldEvent.class, values); } /** * Creates a new {@link PlayerChatEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param source The source of the message * @param message The message to say * @return A new instance of the event */ public static PlayerChatEvent createPlayerChat(Game game, Player player, CommandSource source, String message) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("source", source); values.put("message", message); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerChatEvent.class, values); } /** * Creates a new {@link PlayerDeathEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param player The player involved in this event * @param location The location of death * @param deathMessage The message to show to the player because they died * @param droppedItems The items to drop * @return A new instance of the event */ public static PlayerDeathEvent createPlayerDeath(Game game, Cause cause, Player player, Location location, Message deathMessage, Collection<Item> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("entity", player); values.put("deathMessage", deathMessage); values.put("player", player); values.put("location", location); values.put("human", player); values.put("living", player); values.put("droppedItems", droppedItems); return createEvent(PlayerDeathEvent.class, values); } /** * Creates a new {@link PlayerDropItemEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param droppedItems The items to drop * @return A new instance of the event */ public static PlayerDropItemEvent createPlayerDropItem(Game game, Player player, Collection<ItemStack> droppedItems) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("droppedItems", droppedItems); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerDropItemEvent.class, values); } /** * Creates a new {@link PlayerInteractBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param player The player involved in this event * @param block The block affected by this event * @param interactionType The type of interaction used * @param location The location of the interaction * @return A new instance of the event */ public static PlayerInteractBlockEvent createPlayerInteractBlock(Game game, Cause cause, Player player, BlockLoc block, EntityInteractionType interactionType, @Nullable Vector3f location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", player); values.put("human", player); values.put("living", player); values.put("interactionType", interactionType); values.put("player", player); values.put("clickedPosition", Optional.fromNullable(location)); return createEvent(PlayerInteractBlockEvent.class, values); } /** * Creates a new {@link PlayerInteractEntityEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param targetEntity The entity being interacted with * @param interactionType The type of interaction used * @param location The location of the targeted interaction * @return A new instance of the event */ public static PlayerInteractEntityEvent createPlayerInteractEntity(Game game, Player player, Entity targetEntity, EntityInteractionType interactionType, @Nullable Vector3f location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("targetEntity", targetEntity); values.put("interactionType", interactionType); values.put("player", player); values.put("human", player); values.put("living", player); values.put("clickedPosition", Optional.fromNullable(location)); return createEvent(PlayerInteractEntityEvent.class, values); } /** * Creates a new {@link PlayerInteractEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param interactionType The type of interaction used * @param location The location of the interaction * @return A new instance of the event */ public static PlayerInteractEvent createPlayerInteract(Game game, Player player, EntityInteractionType interactionType, @Nullable Vector3f location) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("interactionType", interactionType); values.put("player", player); values.put("human", player); values.put("living", player); values.put("clickedPosition", Optional.fromNullable(location)); return createEvent(PlayerInteractEvent.class, values); } /** * Creates a new {@link PlayerJoinEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param joinMessage The message displayed when the player joins * @return A new instance of the event */ public static PlayerJoinEvent createPlayerJoin(Game game, Player player, Message joinMessage) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("joinMessage", joinMessage); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerJoinEvent.class, values); } /** * Creates a new {@link PlayerMoveEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param oldLocation The previous location of the entity * @param newLocation The new location of the entity * @return A new instance of the event */ public static PlayerMoveEvent createPlayerMove(Game game, Player player, Location oldLocation, Location newLocation) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("oldLocation", oldLocation); values.put("newLocation", newLocation); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerMoveEvent.class, values); } /** * Creates a new {@link PlayerPickUpItemEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param items The items that will be picked up * @return A new instance of the event */ public static PlayerPickUpItemEvent createPlayerPickUpItem(Game game, Player player, Collection<Entity> items) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("items", items); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerPickUpItemEvent.class, values); } /** * Creates a new {@link PlayerPlaceBlockEvent}. * * @param game The game instance for this {@link GameEvent} * @param cause The cause of the event, can be null * @param player The player involved in this event * @param block The block affected by this event * @param replacementBlock The block that will replace the existing block * @param direction The direction the block was placed * @return A new instance of the event */ public static PlayerPlaceBlockEvent createPlayerPlaceBlock(Game game, Cause cause, Player player, BlockLoc block, BlockSnapshot replacementBlock, Direction direction) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("cause", Optional.fromNullable(cause)); values.put("block", block); values.put("entity", player); values.put("replacementBlock", replacementBlock); values.put("player", player); values.put("human", player); values.put("living", player); values.put("blockFaceDirection", direction); return createEvent(PlayerPlaceBlockEvent.class, values); } /** * Creates a new {@link PlayerQuitEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @param quitMessage The message to display to the player because they quit * @return A new instance of the event */ public static PlayerQuitEvent createPlayerQuit(Game game, Player player, Message quitMessage) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("quitMessage", quitMessage); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerQuitEvent.class, values); } /** * Creates a new {@link PlayerUpdateEvent}. * * @param game The game instance for this {@link GameEvent} * @param player The player involved in this event * @return A new instance of the event */ public static PlayerUpdateEvent createPlayerUpdate(Game game, Player player) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("entity", player); values.put("player", player); values.put("human", player); values.put("living", player); return createEvent(PlayerUpdateEvent.class, values); } /** * Creates a new {@link LightningStrikeEvent}. * * @param game The game instance for this {@link GameEvent} * @param weatherVolume The volume the weather changed in * @param lightningStrike The lightning entity that struck * @param struckEntities The entities the lightning had struck * @param struckBlocks The blocks the lightning had struck * @return A new instance of the event */ public static LightningStrikeEvent createLightningStrike(Game game, WeatherVolume weatherVolume, Lightning lightningStrike, List<Entity> struckEntities, List<BlockLoc> struckBlocks) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("lightningStrike", lightningStrike); values.put("weatherVolume", weatherVolume); values.put("struckEntities", struckEntities); values.put("struckBlocks", struckBlocks); return createEvent(LightningStrikeEvent.class, values); } /** * Creates a new {@link WeatherChangeEvent}. * * @param game The game instance for this {@link GameEvent} * @param weatherVolume The volume the weather changed in * @param initialWeather The previous weather * @param resultingWeather The weather to change to * @return A new instance of the event */ public static WeatherChangeEvent createWeatherChange(Game game, WeatherVolume weatherVolume, Weather initialWeather, Weather resultingWeather) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("initialWeather", initialWeather); values.put("weatherVolume", weatherVolume); values.put("resultingWeather", resultingWeather); return createEvent(WeatherChangeEvent.class, values); } /** * Creates a new {@link ChunkForcedEvent}. * * @param game The game instance for this {@link GameEvent} * @param ticket The ticket that will load the chunk * @param chunkCoords The coordinates of the chunk being added * @return A new instance of the event */ public static ChunkForcedEvent createChunkForced(Game game, LoadingTicket ticket, Vector3i chunkCoords) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("ticket", ticket); values.put("chunkCoords", chunkCoords); return createEvent(ChunkForcedEvent.class, values); } /** * Creates a new {@link ChunkLoadEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static ChunkLoadEvent createChunkLoad(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(ChunkLoadEvent.class, values); } /** * Creates a new {@link ChunkPostGenerateEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static ChunkPostGenerateEvent createChunkPostGenerate(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(ChunkPostGenerateEvent.class, values); } /** * Creates a new {@link ChunkPostPopulateEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static ChunkPostPopulateEvent createChunkPostPopulate(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(ChunkPostPopulateEvent.class, values); } /** * Creates a new {@link ChunkPreGenerateEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static ChunkPreGenerateEvent createChunkPreGenerate(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(ChunkPreGenerateEvent.class, values); } /** * Creates a new {@link ChunkPrePopulateEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @param pendingPopulators All populator's that will populate the chunk * @return A new instance of the event */ public static ChunkPrePopulateEvent createChunkPrePopulate(Game game, Chunk chunk, Iterable<Populator> pendingPopulators) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); values.put("pendingPopulators", pendingPopulators); return createEvent(ChunkPrePopulateEvent.class, values); } /** * Creates a new {@link ChunkUnforcedEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunkCoords The coordinates of the removed chunk * @param ticket The ticket the chunk was removed from * @return A new instance of the event */ public static ChunkUnforcedEvent createChunkUnforced(Game game, Vector3i chunkCoords, LoadingTicket ticket) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("ticket", ticket); values.put("chunkCoords", chunkCoords); return createEvent(ChunkUnforcedEvent.class, values); } /** * Creates a new {@link ChunkUnloadEvent}. * * @param game The game instance for this {@link GameEvent} * @param chunk The chunk involved in this event * @return A new instance of the event */ public static ChunkUnloadEvent createChunkUnload(Game game, Chunk chunk) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("chunk", chunk); return createEvent(ChunkUnloadEvent.class, values); } /** * Creates a new {@link GameRuleChangeEvent}. * * @param game The game instance for this {@link GameEvent} * @param world The world involved in this event * @param name The name of the game rule * @param oldValue The previous value for the rule * @param newValue The new value for the rule * @return A new instance of the event */ public static GameRuleChangeEvent createGameRuleChange(Game game, World world, String name, String oldValue, String newValue) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("world", world); values.put("newValue", newValue); values.put("name", name); values.put("oldValue", oldValue); return createEvent(GameRuleChangeEvent.class, values); } /** * Creates a new {@link WorldLoadEvent}. * * @param game The game instance for this {@link GameEvent} * @param world The world involved in this event * @return A new instance of the event */ public static WorldLoadEvent createWorldLoad(Game game, World world) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("world", world); return createEvent(WorldLoadEvent.class, values); } /** * Creates a new {@link WorldUnloadEvent}. * * @param game The game instance for this {@link GameEvent} * @param world The world involved in this event * @return A new instance of the event */ public static WorldUnloadEvent createWorldUnload(Game game, World world) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("world", world); return createEvent(WorldUnloadEvent.class, values); } /** * Creates a new {@link StatusPingEvent}. * * @param game The game instance for this {@link GameEvent} * @param client The client that is pinging the server * @param response The response to send to the client * @return A new instance of the event */ public static StatusPingEvent createStatusPing(Game game, StatusClient client, StatusPingEvent.Response response) { Map<String, Object> values = Maps.newHashMap(); values.put("game", game); values.put("client", client); values.put("response", response); return createEvent(StatusPingEvent.class, values); } }
package org.threadly.litesockets.utils; import java.util.concurrent.atomic.LongAdder; import org.threadly.util.ArgumentVerifier; import org.threadly.util.Clock; /** * Simple class for trying byteStats. This implementation only tracks global stats. */ public class SimpleByteStats { private final LongAdder bytesRead = new LongAdder(); private final LongAdder bytesWritten = new LongAdder(); private volatile long startTime = Clock.lastKnownForwardProgressingMillis(); protected void addWrite(final int size) { ArgumentVerifier.assertNotNegative(size, "size"); bytesWritten.add(size); } protected void addRead(final int size) { ArgumentVerifier.assertNotNegative(size, "size"); bytesRead.add(size); } /** * @return the total bytes marked as Read since creation. */ public long getTotalRead() { return bytesRead.sum(); } /** * @return the total bytes marked as Written since creation. */ public long getTotalWrite() { return bytesWritten.sum(); } /** * @return the average rate per second that byte have been read, since creation or {@link #resetStats()} */ public double getReadRate() { final double sec = (Clock.lastKnownForwardProgressingMillis() - startTime)/1000.0; return (bytesRead.sum()/sec); } /** * @return the average rate per second that byte have been written, since creation or {@link #resetStats()} */ public double getWriteRate() { final double sec = (Clock.lastKnownForwardProgressingMillis() - startTime)/1000.0; return (bytesWritten.sum()/sec); } /** * Resets all stats. This can be particularly useful when using the * {@link #getReadRate()} / {@link #getWriteRate()}. */ public void resetStats() { startTime = Clock.lastKnownForwardProgressingMillis(); bytesRead.reset(); bytesWritten.reset(); } }
package ru.VirtaMarketAnalyzer.parser; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.PatternLayout; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.VirtaMarketAnalyzer.data.*; import ru.VirtaMarketAnalyzer.main.Utils; import ru.VirtaMarketAnalyzer.main.Wizard; import ru.VirtaMarketAnalyzer.scrapper.Downloader; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static java.util.stream.Collectors.groupingBy; final public class RegionCTIEParser { private static final Logger logger = LoggerFactory.getLogger(RegionCTIEParser.class); public static void main(final String[] args) throws IOException { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%r %d{ISO8601} [%t] %p %c %x - %m%n"))); final String url = Wizard.host + "olga/main/geo/regionENVD/"; final List<Region> regions = new ArrayList<>(); regions.add(new Region("2931", "2961", "Far East", 30)); final List<Product> materials = ProductInitParser.getManufactureProducts(Wizard.host, "olga"); logger.info(Utils.getPrettyGson(materials)); final Map<String, List<RegionCTIE>> allRegionsCTIEList = getAllRegionsCTIEList(url, regions, materials); logger.info(Utils.getPrettyGson(allRegionsCTIEList)); logger.info("\n" + materials.size() + " = " + allRegionsCTIEList.get("2961").size()); } public static Map<String, List<RegionCTIE>> getAllRegionsCTIEList(final String url, final List<Region> regions, final List<Product> materials) throws IOException { return regions.stream().map(region -> { try { return getRegionCTIEList(url, region, materials); } catch (final Exception e) { logger.error(e.getLocalizedMessage(), e); } return null; }) .flatMap(Collection::stream) .collect(groupingBy(RegionCTIE::getRegionId)); } public static List<RegionCTIE> getRegionCTIEList(final String url, final Region region, final List<Product> materials) throws IOException { final Document doc = Downloader.getDoc(url + region.getId()); final Elements imgElems = doc.select("table.list > tbody > tr > td > img"); return imgElems.stream().map(el -> { try { return getRegionCTIEList(el, region, materials); } catch (Exception e) { logger.info(url + region.getId()); logger.error(e.getLocalizedMessage(), e); } return null; }) .filter(Objects::nonNull) .collect(Collectors.toList()); } public static RegionCTIE getRegionCTIEList(final Element elem, final Region region, final List<Product> materials) throws Exception { final Optional<Product> product = materials.stream().filter(p -> p.getImgUrl().equalsIgnoreCase(elem.attr("src"))).findFirst(); if (!product.isPresent()) { throw new Exception("Не найден продукт с изображением '" + elem.attr("src") + "'"); } final String productId = product.get().getId(); try { final Elements child = elem.parent().nextElementSibling().nextElementSibling().children(); if (child != null) { child.remove(); } } catch (final Exception e) { logger.error("html = {}", elem.outerHtml()); throw e; } final int rate = Utils.toInt(elem.parent().nextElementSibling().nextElementSibling().text()); return new RegionCTIE(region.getId(), productId, rate); } }
package skadistats.clarity.processor.entities; import com.google.protobuf.ByteString; import org.slf4j.Logger; import skadistats.clarity.ClarityException; import skadistats.clarity.LogChannel; import skadistats.clarity.decoder.FieldReader; import skadistats.clarity.decoder.bitstream.BitStream; import skadistats.clarity.event.Event; import skadistats.clarity.event.EventListener; import skadistats.clarity.event.Initializer; import skadistats.clarity.event.Insert; import skadistats.clarity.event.InsertEvent; import skadistats.clarity.event.Provides; import skadistats.clarity.logger.PrintfLoggerFactory; import skadistats.clarity.model.DTClass; import skadistats.clarity.model.EngineId; import skadistats.clarity.model.EngineType; import skadistats.clarity.model.Entity; import skadistats.clarity.model.FieldPath; import skadistats.clarity.model.StringTable; import skadistats.clarity.model.state.ClientFrame; import skadistats.clarity.model.state.CloneableEntityState; import skadistats.clarity.processor.reader.OnMessage; import skadistats.clarity.processor.reader.OnReset; import skadistats.clarity.processor.reader.ResetPhase; import skadistats.clarity.processor.runner.OnInit; import skadistats.clarity.processor.sendtables.DTClasses; import skadistats.clarity.processor.sendtables.OnDTClassesComplete; import skadistats.clarity.processor.sendtables.UsesDTClasses; import skadistats.clarity.processor.stringtables.OnStringTableEntry; import skadistats.clarity.util.Predicate; import skadistats.clarity.util.SimpleIterator; import skadistats.clarity.wire.common.proto.Demo; import skadistats.clarity.wire.common.proto.NetMessages; import skadistats.clarity.wire.common.proto.NetworkBaseTypes; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.function.Consumer; import java.util.regex.Pattern; @Provides({UsesEntities.class, OnEntityCreated.class, OnEntityUpdated.class, OnEntityDeleted.class, OnEntityEntered.class, OnEntityLeft.class, OnEntityUpdatesCompleted.class}) @UsesDTClasses public class Entities { public static final String BASELINE_TABLE = "instancebaseline"; private static final Logger log = PrintfLoggerFactory.getLogger(LogChannel.entities); private int entityCount; private FieldReader<DTClass> fieldReader; private int[] deletions; private int serverTick; private LinkedList<ClientFrame> clientFrames = new LinkedList<>(); private Map<Integer, ByteString> rawBaselines = new HashMap<>(); private class Baseline { private int dtClassId = -1; private CloneableEntityState state; private void reset() { state = null; } private void copyFrom(Baseline other) { this.dtClassId = other.dtClassId; this.state = other.state; } } private Baseline[] classBaselines; private Baseline[][] entityBaselines; private final FieldPath[] updatedFieldPaths = new FieldPath[FieldReader.MAX_PROPERTIES]; private ClientFrame currentFrame; private ClientFrame lastFrame; private ClientFrame activeFrame; private ClientFrame deltaFrame; private List<Runnable> lastFrameEvents = new ArrayList<>(); private List<Runnable> currentFrameEvents = new ArrayList<>(); @Insert private EngineType engineType; @Insert private DTClasses dtClasses; @InsertEvent private Event<OnEntityCreated> evCreated; @InsertEvent private Event<OnEntityUpdated> evUpdated; @InsertEvent private Event<OnEntityDeleted> evDeleted; @InsertEvent private Event<OnEntityEntered> evEntered; @InsertEvent private Event<OnEntityLeft> evLeft; @InsertEvent private Event<OnEntityUpdatesCompleted> evUpdatesCompleted; @Initializer(OnEntityCreated.class) public void initOnEntityCreated(final EventListener<OnEntityCreated> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityDeleted.class) public void initOnEntityDeleted(final EventListener<OnEntityDeleted> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityUpdated.class) public void initOnEntityUpdated(final EventListener<OnEntityUpdated> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityEntered.class) public void initOnEntityEntered(final EventListener<OnEntityEntered> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } @Initializer(OnEntityLeft.class) public void initOnEntityLeft(final EventListener<OnEntityLeft> listener) { listener.setInvocationPredicate(getInvocationPredicate(listener.getAnnotation().classPattern())); } private Predicate<Object[]> getInvocationPredicate(String classPattern) { if (".*".equals(classPattern)) { return null; } final Pattern p = Pattern.compile(classPattern); return new Predicate<Object[]>() { @Override public boolean apply(Object[] value) { Entity e = (Entity) value[0]; return p.matcher(e.getDtClass().getDtName()).matches(); } }; } @OnInit public void onInit() { entityCount = 1 << engineType.getIndexBits(); fieldReader = engineType.getNewFieldReader(); deletions = new int[entityCount]; entityBaselines = new Baseline[entityCount][2]; for (int i = 0; i < entityCount; i++) { entityBaselines[i][0] = new Baseline(); entityBaselines[i][1] = new Baseline(); } } @OnDTClassesComplete public void onDTClassesComplete() { classBaselines = new Baseline[dtClasses.getClassCount()]; for (int i = 0; i < classBaselines.length; i++) { classBaselines[i] = new Baseline(); classBaselines[i].dtClassId = i; } } @OnReset public void onReset(Demo.CDemoStringTables packet, ResetPhase phase) { if (phase == ResetPhase.CLEAR) { for (int i = 0; i < classBaselines.length; i++) { classBaselines[i].reset(); } for (int i = 0; i < entityBaselines.length; i++) { entityBaselines[i][0].reset(); entityBaselines[i][1].reset(); } } } @OnStringTableEntry(BASELINE_TABLE) public void onBaselineEntry(StringTable table, int index, String key, ByteString value) { Integer dtClassId = Integer.valueOf(key); rawBaselines.put(dtClassId, value); if (classBaselines != null) { classBaselines[dtClassId].reset(); } } @OnMessage(NetworkBaseTypes.CNETMsg_Tick.class) public void onMessage(NetworkBaseTypes.CNETMsg_Tick message) { serverTick = message.getTick(); } boolean debug = false; @OnMessage(NetMessages.CSVCMsg_PacketEntities.class) public void onPacketEntities(NetMessages.CSVCMsg_PacketEntities message) { if (log.isDebugEnabled()) { log.debug( "processing packet entities: now: %6d, delta-from: %6d, update-count: %5d, baseline: %d, update-baseline: %5s", serverTick, message.getDeltaFrom(), message.getUpdatedEntries(), message.getBaseline(), message.getUpdateBaseline() ); } lastFrame = currentFrame; currentFrame = new ClientFrame(engineType, serverTick); deltaFrame = null; if (message.getIsDelta()) { if (serverTick == message.getDeltaFrom()) { throw new ClarityException("received self-referential delta update for tick %d", serverTick); } deltaFrame = getClientFrame(message.getDeltaFrom(), false); if (deltaFrame == null) { throw new ClarityException("missing client frame for delta update from tick %d", message.getDeltaFrom()); } log.debug("performing delta update, using previous frame from tick %d", deltaFrame.getTick()); } else { log.debug("performing full update"); } if (message.getUpdateBaseline()) { int iFrom = message.getBaseline(); int iTo = 1 - message.getBaseline(); for (Baseline[] baseline : entityBaselines) { baseline[iTo].copyFrom(baseline[iFrom]); } } BitStream stream = BitStream.createBitStream(message.getEntityData()); int updateCount = message.getUpdatedEntries(); int updateIndex; int updateType; int eIdx = 0; while (true) { if (updateCount > 0) { updateIndex = eIdx + stream.readUBitVar(); updateCount } else { updateIndex = entityCount; } if (eIdx < updateIndex) { if (deltaFrame != null) { currentFrame.copyFromOtherFrame(deltaFrame, eIdx, updateIndex - eIdx); } } eIdx = updateIndex; if (eIdx == entityCount) { break; } updateType = stream.readUBitInt(2); switch (updateType) { case 2: // CREATE ENTITY processEntityCreate(eIdx, message, stream); break; case 0: // UPDATE ENTITY processEntityUpdate(eIdx, stream); break; case 1: // LEAVE ENTITY processEntityLeave(eIdx); break; case 3: // DELETE ENTITY processEntityDelete(eIdx); break; } eIdx++; } processDeletions(message, stream); log.debug("update finished for tick %d", currentFrame.getTick()); removeObsoleteClientFrames(message.getDeltaFrom()); clientFrames.add(currentFrame); raiseChangeEvents(); } private void processEntityCreate(int eIdx, NetMessages.CSVCMsg_PacketEntities message, BitStream stream) { CloneableEntityState newState; int dtClassId = stream.readUBitInt(dtClasses.getClassBits()); DTClass dtClass = dtClasses.forClassId(dtClassId); if (dtClass == null) { throw new ClarityException("class for new entity %d is %d, but no dtClass found!.", eIdx, dtClassId); } int serial = stream.readUBitInt(engineType.getSerialBits()); if (engineType.getId() == EngineId.SOURCE2) { // TODO: there is an extra VarInt encoded here for S2, figure out what it is stream.readVarUInt(); } boolean isCreate = true; Set<FieldPath> changedFieldPaths = null; Consumer<FieldPath> changedFieldPathConsumer = null; if (deltaFrame != null && deltaFrame.isValid(eIdx)) { if (deltaFrame.getSerial(eIdx) == serial) { // same entity, only enter isCreate = false; changedFieldPaths = new TreeSet<>(); changedFieldPathConsumer = changedFieldPaths::add; } else { // recreate logModification("DELETE", deltaFrame, eIdx); emitLeftEvent(eIdx); emitDeletedEvent(eIdx); } } if (isCreate) { Baseline baseline = getBaseline(dtClassId, message.getBaseline(), eIdx, message.getIsDelta()); newState = baseline.state.clone(); } else { newState = deltaFrame.getState(eIdx).clone(); } fieldReader.readFields(stream, dtClass, newState, changedFieldPathConsumer, debug); if (isCreate) { currentFrame.createNewEntity(eIdx, dtClass, serial, null, newState); logModification("CREATE", currentFrame, eIdx); emitCreatedEvent(eIdx); emitEnteredEvent(eIdx); } else { currentFrame.updateExistingEntity(deltaFrame, eIdx, changedFieldPaths, newState); currentFrame.setActive(eIdx, true); logModification("ENTER", currentFrame, eIdx); emitEnteredEvent(eIdx); } if (message.getUpdateBaseline()) { Baseline baseline = entityBaselines[eIdx][1 - message.getBaseline()]; baseline.dtClassId = dtClassId; baseline.state = newState.clone(); } } private void processEntityUpdate(int eIdx, BitStream stream) { Set<FieldPath> changedFieldPaths; CloneableEntityState newState; checkDeltaFrameValid("update", eIdx); changedFieldPaths = new TreeSet<>(); newState = deltaFrame.getState(eIdx).clone(); fieldReader.readFields(stream, deltaFrame.getDtClass(eIdx), newState, changedFieldPaths::add, debug); currentFrame.updateExistingEntity(deltaFrame, eIdx, changedFieldPaths, newState); logModification("UPDATE", currentFrame, eIdx); emitUpdatedEvent(eIdx); } private void processEntityLeave(int eIdx) { checkDeltaFrameValid("leave", eIdx); currentFrame.copyFromOtherFrame(deltaFrame, eIdx, 1); currentFrame.setActive(eIdx, false); logModification("LEAVE", currentFrame, eIdx); emitLeftEvent(eIdx); } private void processEntityDelete(int eIdx) { checkDeltaFrameValid("delete", eIdx); logModification("DELETE", deltaFrame, eIdx); emitLeftEvent(eIdx); emitDeletedEvent(eIdx); } private void processDeletions(NetMessages.CSVCMsg_PacketEntities message, BitStream stream) { int eIdx; if (engineType.handleDeletions() && message.getIsDelta()) { int n = fieldReader.readDeletions(stream, engineType.getIndexBits(), deletions); for (int i = 0; i < n; i++) { eIdx = deletions[i]; if (currentFrame.isValid(eIdx)) { log.debug("entity at index %d was ACTUALLY found when ordered to delete, tell the press!", eIdx); if (currentFrame.isActive(eIdx)) { currentFrame.setActive(eIdx, false); emitLeftEvent(eIdx); } emitDeletedEvent(eIdx); currentFrame.deleteEntity(eIdx); } else { log.debug("entity at index %d was not found when ordered to delete.", eIdx); } } } } private void removeObsoleteClientFrames(int deltaFrom) { Iterator<ClientFrame> iter = clientFrames.iterator(); while(iter.hasNext()) { ClientFrame frame = iter.next(); if (frame.getTick() >= deltaFrom) { break; } log.debug("deleting client frame for tick %d", frame.getTick()); iter.remove(); } } private void raiseChangeEvents() { activeFrame = lastFrame; lastFrameEvents.forEach(Runnable::run); lastFrameEvents.clear(); activeFrame = currentFrame; currentFrameEvents.forEach(Runnable::run); currentFrameEvents.clear(); evUpdatesCompleted.raise(); } private void emitCreatedEvent(int i) { if (!evCreated.isListenedTo()) return; currentFrameEvents.add(() -> evCreated.raise(getByIndex(i))); } private void emitEnteredEvent(int i) { if (!evEntered.isListenedTo()) return; currentFrameEvents.add(() -> evEntered.raise(getByIndex(i))); } private void emitUpdatedEvent(int i) { if (!evUpdated.isListenedTo()) return; currentFrameEvents.add(() -> { Set<FieldPath> processedFieldPaths = new TreeSet<>(); for (ClientFrame cf : clientFrames.subList(1, this.clientFrames.size())) { Set<FieldPath> changedFieldPaths = cf.getChangedFieldPaths(i); if (changedFieldPaths != null) { processedFieldPaths.addAll(changedFieldPaths); } } DTClass cls = currentFrame.getDtClass(i); int n = 0; for (FieldPath changedFieldPath : processedFieldPaths) { Object v1 = cls.getValueForFieldPath(changedFieldPath, lastFrame.getState(i)); Object v2 = cls.getValueForFieldPath(changedFieldPath, currentFrame.getState(i)); if ((v1 == null) ^ (v2 == null)) { updatedFieldPaths[n++] = changedFieldPath; } else if (v1 != null && !v1.equals(v2)) { updatedFieldPaths[n++] = changedFieldPath; } } //Arrays.sort(updatedFieldPaths, 0, n); if (n > 0) { evUpdated.raise(getByIndex(i), updatedFieldPaths, n); } }); } private void emitLeftEvent(int i) { if (!evLeft.isListenedTo()) return; lastFrameEvents.add(() -> { if (lastFrame != null && lastFrame.isValid(i) && lastFrame.isActive(i)) { evLeft.raise(getByIndex(i)); } }); } private void emitDeletedEvent(int i) { if (!evDeleted.isListenedTo()) return; lastFrameEvents.add(() -> { if (lastFrame != null && lastFrame.isValid(i)) { evDeleted.raise(getByIndex(i)); } }); } private void checkDeltaFrameValid(String which, int eIdx) { if (deltaFrame == null) { throw new ClarityException("no delta frame on entity %s", which); } if (!deltaFrame.isValid(eIdx)) { throw new ClarityException("entity at index %d was not found in delta frame for %s", eIdx, which); } } private void logModification(String which, ClientFrame frame, int eIdx) { if (!log.isDebugEnabled()) return; log.debug("\t%6s: index: %4d, serial: %03x, handle: %7d, class: %s", which, eIdx, frame.getSerial(eIdx), frame.getHandle(eIdx), frame.getDtClass(eIdx).getDtName() ); } private ClientFrame getClientFrame(int tick, boolean exact) { Iterator<ClientFrame> iter = clientFrames.iterator(); ClientFrame lastFrame = clientFrames.peekFirst(); while (iter.hasNext()) { ClientFrame frame = iter.next(); if (frame.getTick() >= tick) { if (frame.getTick() == tick) { return frame; } if (exact) { return null; } return lastFrame; } lastFrame = frame; } if (exact) { return null; } return lastFrame; } private Baseline getBaseline(int clsId, int baseline, int entityIdx, boolean delta) { Baseline b; if (delta) { b = entityBaselines[entityIdx][baseline]; if (b.dtClassId == clsId && b.state != null) { return b; } } b = classBaselines[clsId]; if (b.state != null) { return b; } DTClass cls = dtClasses.forClassId(clsId); if (cls == null) { throw new ClarityException("DTClass for id %d not found.", clsId); } b.state = cls.getEmptyState(); ByteString raw = rawBaselines.get(clsId); if (raw == null) { throw new ClarityException("Baseline for class %s (%d) not found.", cls.getDtName(), clsId); } if (raw.size() > 0) { BitStream stream = BitStream.createBitStream(raw); fieldReader.readFields(stream, cls, b.state, null, false); } return b; } private Map<Integer, Entity> entityMap = new HashMap<>(); public Entity getByIndex(int index) { if (activeFrame == null || !activeFrame.isValid(index)) return null; int handle = currentFrame.getHandle(index); return entityMap.computeIfAbsent(handle, h -> new Entity(index, () -> activeFrame)); } public Entity getByHandle(int handle) { Entity e = getByIndex(engineType.indexForHandle(handle)); return e == null || e.getSerial() != engineType.serialForHandle(handle) ? null : e; } public Iterator<Entity> getAllByPredicate(final Predicate<Entity> predicate) { return new SimpleIterator<Entity>() { int i = -1; @Override public Entity readNext() { while (++i < entityCount) { Entity e = getByIndex(i); if (e != null && predicate.apply(e)) { return e; } } return null; } }; } public Entity getByPredicate(Predicate<Entity> predicate) { Iterator<Entity> iter = getAllByPredicate(predicate); return iter.hasNext() ? iter.next() : null; } public Iterator<Entity> getAllByDtName(final String dtClassName) { return getAllByPredicate( new Predicate<Entity>() { @Override public boolean apply(Entity e) { return dtClassName.equals(e.getDtClass().getDtName()); } }); } public Entity getByDtName(final String dtClassName) { Iterator<Entity> iter = getAllByDtName(dtClassName); return iter.hasNext() ? iter.next() : null; } }
package uk.ac.ebi.embl.template; import org.apache.commons.lang.StringUtils; import uk.ac.ebi.embl.api.entry.Entry; import uk.ac.ebi.embl.api.entry.Text; import uk.ac.ebi.embl.api.entry.XRef; import uk.ac.ebi.embl.api.entry.feature.SourceFeature; import uk.ac.ebi.embl.api.entry.sequence.Sequence; import uk.ac.ebi.embl.api.entry.sequence.SequenceFactory; import uk.ac.ebi.embl.api.service.SampleRetrievalService; import uk.ac.ebi.embl.api.service.SequenceToolsServices; import uk.ac.ebi.embl.api.validation.*; import uk.ac.ebi.embl.api.validation.dao.model.SampleEntity; import uk.ac.ebi.embl.api.validation.helper.SourceFeatureUtils; import uk.ac.ebi.embl.api.validation.helper.Utils; import uk.ac.ebi.embl.api.validation.helper.taxon.TaxonHelperImpl; import uk.ac.ebi.embl.api.validation.plan.EmblEntryValidationPlan; import uk.ac.ebi.embl.api.validation.plan.EmblEntryValidationPlanProperty; import uk.ac.ebi.embl.api.validation.plan.ValidationPlan; import uk.ac.ebi.embl.flatfile.reader.EntryReader; import uk.ac.ebi.embl.flatfile.reader.embl.EmblEntryReader; import uk.ac.ebi.embl.flatfile.writer.FlatFileWriter; import uk.ac.ebi.embl.flatfile.writer.WrapChar; import uk.ac.ebi.embl.flatfile.writer.WrapType; import uk.ac.ebi.embl.flatfile.writer.embl.CCWriter; import uk.ac.ebi.ena.webin.cli.validator.reference.Attribute; import uk.ac.ebi.ena.webin.cli.validator.reference.Sample; import java.io.BufferedReader; import java.io.StringReader; import java.io.StringWriter; import java.nio.ByteBuffer; import java.sql.Connection; import java.util.HashMap; import java.util.List; import java.util.Map; public class TemplateEntryProcessor { private StringBuilder template; private TemplateInfo templateInfo; private ValidationPlan validationPlan; private Connection connEra; private String molType; private HashMap<String, Sample> sampleCache = new HashMap<String,Sample>(); public TemplateEntryProcessor(Connection connEra) { this(ValidationScope.EMBL_TEMPLATE); this.connEra = connEra; } public TemplateEntryProcessor(ValidationScope validationScope) { EmblEntryValidationPlanProperty emblEntryValidationProperty = new EmblEntryValidationPlanProperty(); emblEntryValidationProperty.validationScope.set(validationScope); emblEntryValidationProperty.isDevMode.set(false); emblEntryValidationProperty.isFixMode.set(true); emblEntryValidationProperty.minGapLength.set(0); validationPlan = new EmblEntryValidationPlan(emblEntryValidationProperty); validationPlan.addMessageBundle(TemplateProcessorConstants.TEMPLATE_MESSAGES_BUNDLE); validationPlan.addMessageBundle(ValidationMessageManager.STANDARD_VALIDATION_BUNDLE); validationPlan.addMessageBundle(ValidationMessageManager.STANDARD_FIXER_BUNDLE); } public ValidationResult validateSequenceUploadEntry(Entry entry) throws Exception { return validationPlan.execute(entry); } protected TemplateProcessorResultSet processEntry(TemplateInfo templateInfo, String molType, TemplateVariables templateVariables, String projectId) throws Exception { this.templateInfo = templateInfo; this.molType = molType; TemplateProcessorResultSet templateProcessorResultSet = new TemplateProcessorResultSet(); if (!checkMandatoryFieldsArePresent(templateInfo, templateVariables, templateProcessorResultSet)) return templateProcessorResultSet; if (!checkSelectedHeadersHaveValuesAndAreSupported(templateVariables, templateProcessorResultSet)) return templateProcessorResultSet; template = new StringBuilder(this.templateInfo.getTemplateString()); replacePPOrganelleToken(templateVariables); replacePPNotes(templateVariables); replacePPGene(templateVariables); addSequenceLengthToken(templateVariables); replaceTokens(templateVariables); new SectionExtractor().removeSections(template, this.templateInfo.getSections(), templateVariables); StringBuilderUtils.removeUnmatchedTokenLines(template); validateSediment(templateProcessorResultSet, templateVariables); validateMarker(templateProcessorResultSet, templateVariables); if(!templateProcessorResultSet.getValidationResult().isValid()) { return templateProcessorResultSet; } BufferedReader stringReader = new BufferedReader(new StringReader(template.toString().trim().concat("\n EntryReader entryReader = new EmblEntryReader(stringReader); ValidationResult validationResult = entryReader.read(); if(!validationResult.isValid()) { templateProcessorResultSet.getValidationResult().append(validationResult); return templateProcessorResultSet; } Entry entry = entryReader.getEntry(); if(StringUtils.isNotEmpty(projectId)) { entry.addProjectAccession(new Text(projectId)); } entry.setSubmitterAccession(String.valueOf(templateVariables.getSequenceName())); addDataToEntry(entry, templateVariables); entry.setStatus(Entry.Status.PRIVATE); // Update SourceFeature using sample values. updateSourceFeatureUsingOrganismFieldValue(entry,templateVariables); List<Text> kewordsL = entry.getKeywords(); if (kewordsL != null && !kewordsL.isEmpty()) { switch (kewordsL.get(0).getText()) { case Entry.WGS_DATACLASS: entry.setDataClass(Entry.WGS_DATACLASS); break; case Entry.GSS_DATACLASS: entry.setDataClass(Entry.GSS_DATACLASS); break; case Entry.CON_DATACLASS: entry.setDataClass(Entry.CON_DATACLASS); break; case Entry.TPA_DATACLASS: entry.setDataClass(Entry.TPA_DATACLASS); break; case Entry.PRT_DATACLASS: entry.setDataClass(Entry.PRT_DATACLASS); break; case Entry.PAT_DATACLASS: entry.setDataClass(Entry.PAT_DATACLASS); break; case Entry.HTG_DATACLASS: entry.setDataClass(Entry.HTG_DATACLASS); break; case Entry.TSA_DATACLASS: entry.setDataClass(Entry.TSA_DATACLASS); break; case Entry.HTC_DATACLASS: entry.setDataClass(Entry.HTC_DATACLASS); break; case Entry.TPX_DATACLASS: entry.setDataClass(Entry.TPX_DATACLASS); break; case Entry.STS_DATACLASS: entry.setDataClass(Entry.STS_DATACLASS); break; case Entry.EST_DATACLASS: entry.setDataClass(Entry.EST_DATACLASS); break; case Entry.TLS_DATACLASS: entry.setDataClass(Entry.TLS_DATACLASS); break; default: entry.setDataClass(Entry.STD_DATACLASS); } } else entry.setDataClass(Entry.STD_DATACLASS); /* if (this.templateInfo.getAnalysisId() != null && !this.templateInfo.getAnalysisId().isEmpty()) { Reference reference = getReferences(); if (reference != null) entry.getReferences().add(reference); }*/ templateProcessorResultSet.getValidationResult().append((validationPlan.execute(entry))); if(entry.getPrimarySourceFeature().getTaxon() != null && entry.getDescription() != null ){ Long taxId = entry.getPrimarySourceFeature().getTaxon().getTaxId(); if(taxId != null && entry.getPrimarySourceFeature().getTaxon().getScientificName() != null) { String taxIdStr = String.valueOf(taxId); if(entry.getDescription().getText().trim().startsWith(taxIdStr)) { entry.getDescription().setText(entry.getDescription().getText().trim().replace(taxIdStr, entry.getPrimarySourceFeature().getTaxon().getScientificName())); } } } templateProcessorResultSet.setEntry(entry); return templateProcessorResultSet; } private boolean checkMandatoryFieldsArePresent(TemplateInfo templateInfo, TemplateVariables templateVariables, TemplateProcessorResultSet templateProcessorResultSet) throws Exception { List<String> mandatoryFieldsList = templateInfo.getMandatoryFields(); Map<String, String> fieldsMap = templateVariables.getVariables(); String missingfields = ""; for (String field: mandatoryFieldsList) { if (!fieldsMap.containsKey(field)) missingfields += field + ","; } if (!missingfields.isEmpty()) { ValidationMessage<Origin> message = new ValidationMessage<Origin>(Severity.ERROR, "MandatoryFieldsCheck", missingfields.substring(0, missingfields.length() - 1)); templateProcessorResultSet.getValidationResult().append(new ValidationResult().append(message)); return false; } return true; } private boolean checkSelectedHeadersHaveValuesAndAreSupported(TemplateVariables templateVariables, TemplateProcessorResultSet templateProcessorResultSet) throws Exception { Map<String, String> fieldsMap = templateVariables.getVariables(); String missingValue = ""; String unsupportedHeaders = ""; Map <String, TemplateTokenInfo> templateTokenMap = templateInfo.getTokensAsMap(); for (String header: fieldsMap.keySet()) { String value = fieldsMap.get(header); if(!templateTokenMap.containsKey(header)) unsupportedHeaders += header + ","; else if (value == null || value.isEmpty()) missingValue += "Header " + header + " has no value.\n"; } if (!unsupportedHeaders.isEmpty()) { ValidationMessage<Origin> message = new ValidationMessage<Origin>(Severity.ERROR, "HeadersSupportedCheck", unsupportedHeaders.substring(0, unsupportedHeaders.length() - 1)); templateProcessorResultSet.getValidationResult().append(new ValidationResult().append(message)); return false; } if (!missingValue.isEmpty()) { ValidationMessage<Origin> message = new ValidationMessage<Origin>(Severity.ERROR, "HeadersValuesCheck", missingValue.substring(0, missingValue.length() - 1)); templateProcessorResultSet.getValidationResult().append(new ValidationResult().append(message)); return false; } return true; } private void replacePPOrganelleToken(TemplateVariables templateVariables) throws Exception { if (!template.toString().contains(TemplateProcessorConstants.PP_ORGANELLE_TOKEN)) return; for (String tokenName: templateVariables.getTokenNames()) { String tokenValue = templateVariables.getTokenValue(tokenName); if (tokenValue == null || tokenValue.isEmpty()) continue; if (tokenName.toUpperCase().equals(TemplateProcessorConstants.ORGANELLE_TOKEN)) { template = new StringBuilder(template.toString().replace(TemplateProcessorConstants.PP_ORGANELLE_TOKEN , tokenValue)); return; } } template = new StringBuilder(template.toString().replace(TemplateProcessorConstants.PP_ORGANELLE_TOKEN, "")); } private void replacePPNotes(TemplateVariables templateVariables) throws Exception { if (!template.toString().contains(TemplateProcessorConstants.PP_NOTES_TOKEN)) return; ValidationResult validationResult = new ValidationResult(); String token18s = templateVariables.getTokenValue("18S"); String tokenITS1 = templateVariables.getTokenValue("ITS1"); String token5point8S = templateVariables.getTokenValue("5.8S"); String tokenITS2 = templateVariables.getTokenValue("ITS2"); String token28S = templateVariables.getTokenValue("28S"); boolean TOKEN_FOUND = false; StringBuilder builder = new StringBuilder(); if (token18s != null && !token18s.isEmpty() && token18s.equalsIgnoreCase(TemplateTokenInfo.YES_VALUE)) { builder.append("18S rRNA gene"); TOKEN_FOUND = true; } if (tokenITS1 != null && !tokenITS1.isEmpty() && tokenITS1.equalsIgnoreCase(TemplateTokenInfo.YES_VALUE)) { if (TOKEN_FOUND) builder.append(", "); builder.append("ITS1"); TOKEN_FOUND = true; } if (token5point8S != null && !token5point8S.isEmpty() && token5point8S.equalsIgnoreCase(TemplateTokenInfo.YES_VALUE)) { if (TOKEN_FOUND) builder.append(", "); builder.append("5.8S rRNA gene"); TOKEN_FOUND = true; } if (tokenITS2 != null && !tokenITS2.isEmpty() && tokenITS2.equalsIgnoreCase(TemplateTokenInfo.YES_VALUE)) { if (TOKEN_FOUND) builder.append(", "); builder.append("ITS2"); TOKEN_FOUND = true; } if (token28S != null && !token28S.isEmpty() && token28S.equalsIgnoreCase(TemplateTokenInfo.YES_VALUE)) { if (TOKEN_FOUND) builder.append(", "); builder.append("28S rRNA gene"); TOKEN_FOUND = true; } if (!builder.toString().isEmpty()) templateVariables.addToken("PP_NOTES", "sequence contains " + builder.toString()); } public void replacePPGene(TemplateVariables templateVariables) { if (!template.toString().contains(TemplateProcessorConstants.PP_GENE_TOKEN)) return; String marker = templateVariables.getTokenValue(TemplateProcessorConstants.MARKER_TOKEN); if (marker == null || marker.isEmpty()) return; for (TemplateProcessorConstants.MarkerE markerE : TemplateProcessorConstants.MarkerE.values()) { if (markerE.getMarker().equals(marker)) { template = new StringBuilder(template.toString().replace(TemplateProcessorConstants.PP_GENE_TOKEN, markerE.name())); return; } } for (TemplateProcessorConstants.MarkerE markerE : TemplateProcessorConstants.MarkerE.values()) { if (markerE.name().equals(marker)) { template = new StringBuilder(template.toString().replace(TemplateProcessorConstants.PP_GENE_TOKEN, markerE.name())); templateVariables.setTokenValue(TemplateProcessorConstants.MARKER_TOKEN, markerE.getMarker()); return; } } } private void addDataToEntry(Entry entry, TemplateVariables templateVariables) throws TemplateException { try { if (templateVariables == null) return; for (String tokenName: templateVariables.getTokenNames()) { String tokenValue = templateVariables.getTokenValue(tokenName); if (tokenValue == null || tokenValue.isEmpty()) continue; if (tokenName.toUpperCase().equals(TemplateProcessorConstants.moloculeTypeE.NCRMOLTYPE.name()) || tokenName.toUpperCase().equals(TemplateProcessorConstants.moloculeTypeE.VMOLTYPE.name())) { molType = tokenValue; break; } } Sequence.Topology topology = Sequence.Topology.LINEAR; for (String tokenName: templateVariables.getTokenNames()) { String tokenValue = templateVariables.getTokenValue(tokenName); if (tokenValue == null || tokenValue.isEmpty()) continue; if(tokenName.equals(TemplateProcessorConstants.TOPOLOGY_TOKEN)) { topology = SequenceEntryUtils.getTopology(tokenValue.trim()); } if (tokenName.equals(TemplateProcessorConstants.SEQUENCE_TOKEN)) { Sequence sequence = new SequenceFactory().createSequence(); sequence.setSequence(ByteBuffer.wrap(tokenValue.toLowerCase().getBytes())); sequence.setVersion(1); sequence.setTopology(topology == null ? Sequence.Topology.LINEAR: topology); sequence.setMoleculeType(molType); entry.setSequence(sequence); } else if (tokenName.equals(TemplateProcessorConstants.COMMENTS_TOKEN)) { StringWriter writer = new StringWriter(); entry.setComment(new Text(tokenValue)); FlatFileWriter ccwriter= new CCWriter(entry); ccwriter.setWrapType(WrapType.EMBL_WRAP); ccwriter.setWrapChar(WrapChar.WRAP_CHAR_SPACE); ccwriter.write(writer); entry.setComment(new Text(writer.toString().replace("CC ", ""))); } } } catch (Exception e) { throw new TemplateException(e); } } private void addSequenceLengthToken(TemplateVariables variables) { if (variables.containsToken(TemplateProcessorConstants.SEQUENCE_TOKEN)) { int sequenceLength = variables.getTokenValue(TemplateProcessorConstants.SEQUENCE_TOKEN).length(); variables.addToken(TemplateProcessorConstants.SEQUENCE_LENGTH_TOKEN, Integer.toString(sequenceLength)); } } private void replaceTokens(TemplateVariables tokens) throws TemplateException { try { if (tokens == null) return; for (String tokenName : tokens.getTokenNames()) { String token = tokens.getTokenValue(tokenName); if (token == null || token.isEmpty()) continue;//leave empty tokens as we will strip the unmatched token lines String delimitedKey = StringBuilderUtils.encloseToken(tokenName); if (tokenName.equals(TemplateProcessorConstants.SEQUENCE_TOKEN) || tokenName.equals(TemplateProcessorConstants.COMMENTS_TOKEN)) continue; doReplace(delimitedKey, token); } } catch (Exception e) { throw new TemplateException(e); } } private void doReplace(String stringToFind, String stringToReplace) { template = new StringBuilder(template.toString().replace(stringToFind, stringToReplace)); } private void validateSediment(TemplateProcessorResultSet templateProcessorResultSet, TemplateVariables templateVariables) { if (templateVariables.getVariables().containsKey(TemplateProcessorConstants.SEDIMENT_TOKEN)) { String sediment = templateVariables.getVariables().get(TemplateProcessorConstants.SEDIMENT_TOKEN); for (TemplateProcessorConstants.SedimentE sedimentE: TemplateProcessorConstants.SedimentE.values()) { if (sedimentE.getSediment().equals(sediment)) return; } String values = ""; for (TemplateProcessorConstants.SedimentE sedimentE: TemplateProcessorConstants.SedimentE.values()) values += sedimentE.getSediment() + ","; ValidationMessage<Origin> message = new ValidationMessage<Origin>(Severity.ERROR, "SedimentCheck", sediment, StringUtils.chompLast(values, ",")); templateProcessorResultSet.getValidationResult().append(new ValidationResult().append(message)); } } private void validateMarker(TemplateProcessorResultSet templateProcessorResultSet, TemplateVariables templateVariables) { if (templateVariables.getVariables().containsKey(TemplateProcessorConstants.MARKER_TOKEN)) { String marker = templateVariables.getVariables().get(TemplateProcessorConstants.MARKER_TOKEN); for (TemplateProcessorConstants.MarkerE markerE : TemplateProcessorConstants.MarkerE.values()) { if (markerE.getMarker().equals(marker)) return; } String values = ""; for (TemplateProcessorConstants.MarkerE markerE : TemplateProcessorConstants.MarkerE.values()) values += markerE.getMarker() + ","; ValidationMessage<Origin> message = new ValidationMessage<Origin>(Severity.ERROR, "MarkerCheck", marker, values); templateProcessorResultSet.getValidationResult().append(new ValidationResult().append(message)); } } /** * This method check if the ORGANISM_NAME field value is related to a sample and * updates the entry's sourceFeature using the sample values. * */ private void updateSourceFeatureUsingOrganismFieldValue(Entry entry, TemplateVariables templateVariables) throws Exception { // Validate and get samples Sample sample = validateAndGetSample(templateVariables); if (sample != null && entry.getPrimarySourceFeature() != null) { SourceFeature sourceFeature = entry.getPrimarySourceFeature(); SampleInfo sampleInfo = getSampleInfo(sample); SampleEntity sampleEntity = getSampleEntity(sample); updateSourceFeature(sourceFeature, sampleEntity, sampleInfo); entry.addXRef(new XRef("BioSample", sample.getBioSampleId())); } } /** * Returns sample if one could be found using the ORGANISM_NAME field of the TSV * file or NULL if the ORGANISM_NAME was a scientific name or tax id. */ public Sample validateAndGetSample(TemplateVariables templateVariables) throws Exception { Map<String, String> tsvFieldMap = templateVariables.getVariables(); Sample sample = null; // Iterate TSV header fields. for (String tsvHeader : tsvFieldMap.keySet()) { if (tsvHeader.equalsIgnoreCase(TemplateProcessorConstants.ORGANISM_TOKEN)) { // When TSV header cell value is ORGANISM_NAME if (Utils.isValidTaxId(tsvFieldMap.get(tsvHeader))) { // When field value is taxId pattern DO NOTHING break; } /** When tsv value do NOT match taxId pattern then retrieve sample assuming that the passed * value is sampleId, bioSampleId, or sample alias. * If no sample is returned then the value is organism name. */ String sampleValue = tsvFieldMap.get(tsvHeader); // Get sample from cache if exists. sample = sampleCache.get(sampleValue); if (sample == null) { try { // Get sample using server sample retrieval service. SampleRetrievalService sampleRetrievalService = SequenceToolsServices.sampleRetrievalService(); sample = sampleRetrievalService.getSample(sampleValue); sampleCache.put(sampleValue, sample); }catch (Exception serviceiException){ // DO NOTHING when there is no sample } } break; } } return sample; } private SampleEntity getSampleEntity(Sample sample){ SampleEntity sampleEntity = new SampleEntity(); Map<String,String> attributeMap=new HashMap(); for(Attribute attribute: sample.getAttributes()){ attributeMap.put(attribute.getName(),attribute.getValue()); } sampleEntity.setAttributes(attributeMap); return sampleEntity; } private SourceFeature updateSourceFeature(SourceFeature sourceFeature,SampleEntity sampleEntity,SampleInfo sampleInfo) throws Exception { return new SourceFeatureUtils().updateSourceFeature(sourceFeature, sampleEntity, new TaxonHelperImpl(), sampleInfo); } public SourceFeature createSourceFeature(SampleEntity sampleEntity,SampleInfo sampleInfo) throws Exception { return new SourceFeatureUtils().constructSourceFeature(sampleEntity, new TaxonHelperImpl(), sampleInfo); } private SampleInfo getSampleInfo(Sample sample){ SampleInfo sampleInfo=new SampleInfo(); sampleInfo.setScientificName(sample.getOrganism()); sampleInfo.setUniqueName(sample.getName()); if(sample.getTaxId()!=null) { sampleInfo.setTaxId(Long.valueOf(sample.getTaxId())); } return sampleInfo; } }
package uk.ac.ebi.phenotype.solr.indexer; import static uk.ac.ebi.phenotype.solr.indexer.utils.OntologyUtils.BATCH_SIZE; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import uk.ac.ebi.phenotype.service.ImageService; import uk.ac.ebi.phenotype.service.ObservationService; import uk.ac.ebi.phenotype.service.dto.ImageDTO; import uk.ac.ebi.phenotype.service.dto.ObservationDTO; import uk.ac.ebi.phenotype.service.dto.SangerImageDTO; import javax.annotation.Resource; import javax.sql.DataSource; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * class to load the image data into the solr core - use for impc data first * then we can do sanger images as well? * * @author jwarren * */ public class ImagesIndexer extends AbstractIndexer { private static final Logger logger = LoggerFactory.getLogger(ImagesIndexer.class); @Autowired @Qualifier("observationIndexing") private SolrServer observationService; @Autowired @Qualifier("impcImagesIndexing") SolrServer server; @Autowired @Qualifier("komp2DataSource") DataSource komp2DataSource; @Resource(name = "globalConfiguration") private Map<String, String> config; public ImagesIndexer() { super(); } public static void main(String[] args) throws IOException, SolrServerException { OptionParser parser = new OptionParser(); // parameter to indicate which spring context file to use parser.accepts("context").withRequiredArg().ofType(String.class); OptionSet options = parser.parse(args); String context = (String) options.valuesOf("context").get(0); logger.info("Using application context file {}", context); ApplicationContext applicationContext; try { // Try context as a file resource applicationContext = new FileSystemXmlApplicationContext("file:" + context); } catch (RuntimeException e) { logger.warn("An error occurred loading the app-config file: {}", e.getMessage()); // Try context as a class path resource applicationContext = new ClassPathXmlApplicationContext(context); logger.warn("Using classpath app-config file: {}", context); } // Wire up spring support for this application ImagesIndexer main = new ImagesIndexer(); applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(main, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); // System.out.println("solrUrl="+solrUrl); try { main.run(); } catch (IndexerException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.info("Process finished. Exiting."); } @Override public void run() throws IndexerException { String impcMediaBaseUrl = config.get("impcMediaBaseUrl"); System.out.println("omeroRootUrl=" + impcMediaBaseUrl); final String getExtraImageInfoSQL = "SELECT FULL_RESOLUTION_FILE_PATH, omero_id, " + ImageDTO.DOWNLOAD_FILE_PATH + ", " + ImageDTO.FULL_RESOLUTION_FILE_PATH + " FROM image_record_observation " + " WHERE " + ImageDTO.DOWNLOAD_FILE_PATH + " = ?"; try (PreparedStatement statement = komp2DataSource.getConnection().prepareStatement(getExtraImageInfoSQL)) { // TODO: Need to batch these up to do a set of images at a time // (currently works, but the number of images will grow beyond what // can be handled in a single query) SolrQuery query = ImageService.allImageRecordSolrQuery(); int pos = 0; long total = Integer.MAX_VALUE; query.setRows(BATCH_SIZE); while (pos < total) { query.setStart(pos); QueryResponse response = null; try { response = observationService.query(query); } catch (Exception e) { throw new IndexerException("Unable to query images core", e); } total = response.getResults().getNumFound(); List<ImageDTO> imageList = response.getBeans(ImageDTO.class); for (ImageDTO imageDTO : imageList) { String downloadFilePath = imageDTO.getDownloadFilePath(); // System.out.println("trying downloadfilePath="+downloadFilePath); statement.setString(1, downloadFilePath); ResultSet resultSet = statement.executeQuery(); // System.out.println("imageDTO="+imageDTO); while (resultSet.next()) { String fullResFilePath = resultSet.getString("FULL_RESOLUTION_FILE_PATH"); // System.out.println("fullResFilePath="+fullResFilePath); imageDTO.setFullResolutionFilePath(fullResFilePath); int omeroId = resultSet.getInt("omero_id"); imageDTO.setOmeroId(omeroId); // need to add a full path to image in omero as part of // api if (omeroId != 0 && downloadFilePath != null) { // System.out.println("setting downloadurl="+impcMediaBaseUrl+"/render_image/"+omeroId); // /webgateway/archived_files/download/ imageDTO.setDownloadUrl(impcMediaBaseUrl + "/archived_files/download/" + omeroId); imageDTO.setJpegUrl(impcMediaBaseUrl + "/render_image/" + omeroId); } else { System.out.println("omero id is null for " + downloadFilePath); } } pos += BATCH_SIZE; server.addBeans(imageList, 60000); if (pos % 10000 == 0) { System.out.println(" added ImageDTO" + pos + " beans"); } } } } catch (Exception e) { e.printStackTrace(); } try { server.commit(); } catch (SolrServerException | IOException e) { e.printStackTrace(); throw new IndexerException(e); } } public List<ImageDTO> getAllImageDTOs() throws SolrServerException { SolrQuery query = ImageService.allImageRecordSolrQuery(); return observationService.query(query).getBeans(ImageDTO.class); } @Override protected Logger getLogger() { return logger; } }
package yokohama.unit.translator; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor; import org.antlr.v4.runtime.tree.TerminalNode; import org.apache.commons.lang3.StringUtils; import yokohama.unit.ast.Abbreviation; import yokohama.unit.ast.AnchorExpr; import yokohama.unit.ast.AsExpr; import yokohama.unit.ast.Assertion; import yokohama.unit.ast.Binding; import yokohama.unit.ast.Bindings; import yokohama.unit.ast.BooleanExpr; import yokohama.unit.ast.Cell; import yokohama.unit.ast.CharExpr; import yokohama.unit.ast.ChoiceBinding; import yokohama.unit.ast.ClassType; import yokohama.unit.ast.Clause; import yokohama.unit.ast.CodeBlock; import yokohama.unit.ast.Definition; import yokohama.unit.ast.DoesNotMatchPredicate; import yokohama.unit.ast.EqualToMatcher; import yokohama.unit.ast.Execution; import yokohama.unit.ast.Expr; import yokohama.unit.ast.ExprCell; import yokohama.unit.ast.Fixture; import yokohama.unit.ast.FloatingPointExpr; import yokohama.unit.ast.FourPhaseTest; import yokohama.unit.ast.Group; import yokohama.unit.ast.Heading; import yokohama.unit.ast.Ident; import yokohama.unit.ast.InstanceOfMatcher; import yokohama.unit.ast.InstanceSuchThatMatcher; import yokohama.unit.ast.IntegerExpr; import yokohama.unit.ast.InvocationExpr; import yokohama.unit.ast.Invoke; import yokohama.unit.ast.IsNotPredicate; import yokohama.unit.ast.IsPredicate; import yokohama.unit.ast.LetStatement; import yokohama.unit.ast.MethodPattern; import yokohama.unit.ast.NonArrayType; import yokohama.unit.ast.Phase; import yokohama.unit.ast.PrimitiveType; import yokohama.unit.ast.Kind; import yokohama.unit.ast.Matcher; import yokohama.unit.ast.MatchesPredicate; import yokohama.unit.ast.NullValueMatcher; import yokohama.unit.ast.Pattern; import yokohama.unit.position.Position; import yokohama.unit.ast.Predicate; import yokohama.unit.ast.Proposition; import yokohama.unit.ast.QuotedExpr; import yokohama.unit.ast.RegExpPattern; import yokohama.unit.ast.ResourceExpr; import yokohama.unit.ast.Row; import yokohama.unit.ast.SingleBinding; import yokohama.unit.ast.Statement; import yokohama.unit.ast.StringExpr; import yokohama.unit.position.Span; import yokohama.unit.ast.StubBehavior; import yokohama.unit.ast.StubExpr; import yokohama.unit.ast.StubReturns; import yokohama.unit.ast.StubThrows; import yokohama.unit.ast.Table; import yokohama.unit.ast.TableBinding; import yokohama.unit.ast.TableRef; import yokohama.unit.ast.TableType; import yokohama.unit.ast.Test; import yokohama.unit.ast.ThrowsPredicate; import yokohama.unit.ast.Type; import yokohama.unit.ast.VerifyPhase; import yokohama.unit.grammar.YokohamaUnitParser; import yokohama.unit.grammar.YokohamaUnitParserVisitor; import yokohama.unit.util.Lists; import yokohama.unit.util.Pair; @AllArgsConstructor public class ParseTreeToAstVisitor extends AbstractParseTreeVisitor<Object> implements YokohamaUnitParserVisitor<Object> { private final Optional<Path> docyPath; public Span getSpan(ParserRuleContext ctx) { Token startToken = ctx.getStart(); Token stopToken = ctx.getStop(); Position startPosition = new Position(startToken.getLine(), startToken.getCharPositionInLine() + 1); Position endPosition = new Position(stopToken.getLine(), stopToken.getCharPositionInLine() + stopToken.getText().length() + 1); Span span = new Span(docyPath, startPosition, endPosition); return span; } public Span nodeSpan(TerminalNode terminalNode) { Token token = terminalNode.getSymbol(); Position startPosition = new Position(token.getLine(), token.getCharPositionInLine() + 1); Position endPosition = new Position(token.getLine(), token.getCharPositionInLine() + token.getText().length() + 1); Span span = new Span(docyPath, startPosition, endPosition); return span; } @Override public Group visitGroup(YokohamaUnitParser.GroupContext ctx) { List<Abbreviation> abbreviations = ctx.abbreviation().stream() .map(this::visitAbbreviation) .collect(Collectors.toList()); List<Definition>definitions = ctx.definition().stream() .map(this::visitDefinition) .collect(Collectors.toList()); return new Group(abbreviations, definitions, getSpan(ctx)); } @Override public Abbreviation visitAbbreviation(YokohamaUnitParser.AbbreviationContext ctx) { return new Abbreviation(ctx.ShortName().getText(), ctx.Line().getText(), getSpan(ctx)); } @Override public Definition visitDefinition(YokohamaUnitParser.DefinitionContext ctx) { return (Definition)visitChildren(ctx); } @Override public Test visitTest(YokohamaUnitParser.TestContext ctx) { String name = ctx.Line().getText(); List<Assertion> assertions = ctx.assertion().stream() .map(this::visitAssertion) .collect(Collectors.toList()); return new Test(name, assertions, getSpan(ctx)); } @Override public Assertion visitAssertion(YokohamaUnitParser.AssertionContext ctx) { List<Clause> clauses = visitClauses(ctx.clauses()); YokohamaUnitParser.ConditionContext conditionCtx = (ctx.condition()); Fixture fixture = conditionCtx == null ? Fixture.none() : visitCondition(ctx.condition()); return new Assertion(clauses, fixture, getSpan(ctx)); } @Override public List<Clause> visitClauses(YokohamaUnitParser.ClausesContext ctx) { return ctx.clause().stream() .map(this::visitClause) .collect(Collectors.toList()); } @Override public Clause visitClause(YokohamaUnitParser.ClauseContext ctx) { List<Proposition> propositions = ctx.proposition().stream() .map(this::visitProposition) .collect(Collectors.toList()); return new Clause(propositions, getSpan(ctx)); } @Override public Proposition visitProposition(YokohamaUnitParser.PropositionContext ctx) { Expr subject = visitSubject(ctx.subject()); Predicate predicate = visitPredicate(ctx.predicate()); return new Proposition(subject, predicate, getSpan(ctx)); } @Override public Expr visitSubject(YokohamaUnitParser.SubjectContext ctx) { return (Expr)visitChildren(ctx); } @Override public Predicate visitPredicate(YokohamaUnitParser.PredicateContext ctx) { return (Predicate)visitChildren(ctx); } @Override public IsPredicate visitIsPredicate(YokohamaUnitParser.IsPredicateContext ctx) { return new IsPredicate(visitMatcher(ctx.matcher()), getSpan(ctx)); } @Override public IsNotPredicate visitIsNotPredicate(YokohamaUnitParser.IsNotPredicateContext ctx) { return new IsNotPredicate(visitMatcher(ctx.matcher()), getSpan(ctx)); } @Override public ThrowsPredicate visitThrowsPredicate(YokohamaUnitParser.ThrowsPredicateContext ctx) { return new ThrowsPredicate(visitMatcher(ctx.matcher()), getSpan(ctx)); } @Override public MatchesPredicate visitMatchesPredicate( YokohamaUnitParser.MatchesPredicateContext ctx) { return new MatchesPredicate(visitPattern(ctx.pattern()), getSpan(ctx)); } @Override public DoesNotMatchPredicate visitDoesNotMatchPredicate( YokohamaUnitParser.DoesNotMatchPredicateContext ctx) { return new DoesNotMatchPredicate( visitPattern(ctx.pattern()), getSpan(ctx)); } @Override public Matcher visitMatcher(YokohamaUnitParser.MatcherContext ctx) { return (Matcher)visitChildren(ctx); } @Override public Matcher visitEqualTo(YokohamaUnitParser.EqualToContext ctx) { return new EqualToMatcher( visitArgumentExpr(ctx.argumentExpr()), getSpan(ctx)); } @Override public Matcher visitInstanceOf(YokohamaUnitParser.InstanceOfContext ctx) { return new InstanceOfMatcher(visitClassType(ctx.classType()), getSpan(ctx)); } @Override public Matcher visitInstanceSuchThat(YokohamaUnitParser.InstanceSuchThatContext ctx) { return new InstanceSuchThatMatcher( new Ident(ctx.Identifier().getText(), nodeSpan(ctx.Identifier())), visitClassType(ctx.classType()), ctx.proposition().stream().map(this::visitProposition).collect(Collectors.toList()), getSpan(ctx)); } @Override public Matcher visitNullValue(YokohamaUnitParser.NullValueContext ctx) { return new NullValueMatcher(getSpan(ctx)); } @Override public Pattern visitPattern(YokohamaUnitParser.PatternContext ctx) { return (Pattern)visitChildren(ctx); } @Override public RegExpPattern visitRegexp(YokohamaUnitParser.RegexpContext ctx) { return new RegExpPattern(ctx.Regexp().getText(), getSpan(ctx)); } @Override public Fixture visitCondition(YokohamaUnitParser.ConditionContext ctx) { return (Fixture)visitChildren(ctx); } @Override public TableRef visitForAll(YokohamaUnitParser.ForAllContext ctx) { List<Ident> idents = visitVars(ctx.vars()); Pair<TableType, String> typeAndName = visitTableRef(ctx.tableRef()); TableType tableType = typeAndName.getFirst(); String name = typeAndName.getSecond(); return new TableRef(idents, tableType, name, getSpan(ctx)); } @Override public List<Ident> visitVars(YokohamaUnitParser.VarsContext ctx) { return ctx.Identifier().stream() .map(ident -> new Ident(ident.getText(), nodeSpan(ident))) .collect(Collectors.toList()); } @Override public Pair<TableType, String> visitTableRef(YokohamaUnitParser.TableRefContext ctx) { if (ctx.UTABLE() != null) { String name = ctx.Anchor().getText(); return Pair.of(TableType.INLINE, name); } else if (ctx.CSV_SINGLE_QUOTE() != null) { String name = ctx.FileName().getText().replace("''", "'"); return Pair.of(TableType.CSV, name); } else if (ctx.TSV_SINGLE_QUOTE() != null) { String name = ctx.FileName().getText().replace("''", "'"); return Pair.of(TableType.TSV, name); } else if (ctx.EXCEL_SINGLE_QUOTE() != null) { String name = ctx.BookName().getText().replace("''", "'"); return Pair.of(TableType.EXCEL, name); } else { throw new IllegalArgumentException("'" + ctx.getText() + "' is not a table reference."); } } @Override public Bindings visitBindings(YokohamaUnitParser.BindingsContext ctx) { List<Binding> bindings = ctx.binding().stream() .map(this::visitBinding) .collect(Collectors.toList()); return new Bindings(bindings, getSpan(ctx)); } @Override public Binding visitBinding(YokohamaUnitParser.BindingContext ctx) { return (Binding)visitChildren(ctx); } @Override public SingleBinding visitSingleBinding(YokohamaUnitParser.SingleBindingContext ctx) { Ident ident = new Ident(ctx.Identifier().getText(), nodeSpan(ctx.Identifier())); Expr expr = visitExpr(ctx.expr()); return new SingleBinding(ident, expr, getSpan(ctx)); } @Override public ChoiceBinding visitChoiceBinding(YokohamaUnitParser.ChoiceBindingContext ctx) { Ident ident = new Ident(ctx.Identifier().getText(), nodeSpan(ctx.Identifier())); List<Expr> exprs = ctx.expr().stream().map(this::visitExpr).collect(Collectors.toList()); return new ChoiceBinding(ident, exprs, getSpan(ctx)); } @Override public TableBinding visitTableBinding(YokohamaUnitParser.TableBindingContext ctx) { List<Ident> names = ctx.Identifier().stream() .map(node -> new Ident(node.getText(), nodeSpan(node))) .collect(Collectors.toList()); Pair<TableType, String> tableRef = visitTableRef(ctx.tableRef()); return new TableBinding( names, tableRef.getFirst(), tableRef.getSecond(), getSpan(ctx)); } @Override public Table visitTableDef(YokohamaUnitParser.TableDefContext ctx) { String name = ctx.Anchor().getText(); List<Ident> header = visitHeader(ctx.header()); List<Row> rows = visitRows(ctx.rows()); return new Table(name, header, rows, getSpan(ctx)); } @Override public List<Ident> visitHeader(YokohamaUnitParser.HeaderContext ctx) { return ctx.Identifier().stream() .map(ident -> new Ident(ident.getText(), nodeSpan(ident))) .collect(Collectors.toList()); } @Override public List<Row> visitRows(YokohamaUnitParser.RowsContext ctx) { return ctx.row().stream() .map(this::visitRow) .collect(Collectors.toList()); } @Override public Row visitRow(YokohamaUnitParser.RowContext ctx) { List<Cell> cells = ctx.argumentExpr().stream() .map(expr -> new ExprCell( visitArgumentExpr(expr), getSpan(expr))) .collect(Collectors.toList()); return new Row(cells, getSpan(ctx)); } @Override public FourPhaseTest visitFourPhaseTest(YokohamaUnitParser.FourPhaseTestContext ctx) { String name = ctx.Line().getText(); Optional<Phase> setup = ctx.setup() == null ? Optional.empty() : Optional.of(visitSetup(ctx.setup())); Optional<Phase> exercise = ctx.exercise() == null ? Optional.empty() : Optional.of(visitExercise(ctx.exercise())); VerifyPhase verify = visitVerify(ctx.verify()); Optional<Phase> teardown = ctx.teardown() == null ? Optional.empty() : Optional.of(visitTeardown(ctx.teardown())); return new FourPhaseTest(name, setup, exercise, verify, teardown, getSpan(ctx)); } @Override public Phase visitSetup(YokohamaUnitParser.SetupContext ctx) { Optional<String> description = ctx.Line() == null ? Optional.empty() : Optional.of(ctx.Line().getText()); List<LetStatement> letStatements = ctx.letStatement().stream() .map(letStatement -> visitLetStatement(letStatement)) .collect(Collectors.toList()); List<Statement> statements = ctx.statement() .stream() .map(this::visitStatement) .collect(Collectors.toList()); return new Phase(description, letStatements, statements, getSpan(ctx)); } @Override public Phase visitExercise(YokohamaUnitParser.ExerciseContext ctx) { Optional<String> description = ctx.Line() == null ? Optional.empty() : Optional.of(ctx.Line().getText()); List<Statement> statements = ctx.statement() .stream() .map(this::visitStatement) .collect(Collectors.toList()); return new Phase(description, Collections.emptyList(), statements, getSpan(ctx)); } @Override public VerifyPhase visitVerify(YokohamaUnitParser.VerifyContext ctx) { Optional<String> description = ctx.Line() == null ? Optional.empty() : Optional.of(ctx.Line().getText()); List<Assertion> assertions = ctx.assertion() .stream() .map(this::visitAssertion) .collect(Collectors.toList()); return new VerifyPhase(description, assertions, getSpan(ctx)); } @Override public Phase visitTeardown(YokohamaUnitParser.TeardownContext ctx) { Optional<String> description = ctx.Line() == null ? Optional.empty() : Optional.of(ctx.Line().getText()); List<Statement> statements = ctx.statement() .stream() .map(this::visitStatement) .collect(Collectors.toList()); return new Phase(description, Collections.emptyList(), statements, getSpan(ctx)); } @Override public LetStatement visitLetStatement(YokohamaUnitParser.LetStatementContext ctx) { return new LetStatement( ctx.letBinding().stream() .map(this::visitLetBinding) .collect(Collectors.toList()), getSpan(ctx)); } @Override public Binding visitLetBinding(YokohamaUnitParser.LetBindingContext ctx) { return (Binding)visitChildren(ctx); } @Override public SingleBinding visitLetSingleBinding(YokohamaUnitParser.LetSingleBindingContext ctx) { return new SingleBinding( new Ident(ctx.Identifier().getText(), nodeSpan(ctx.Identifier())), visitExpr(ctx.expr()), getSpan(ctx)); } @Override public ChoiceBinding visitLetChoiceBinding(YokohamaUnitParser.LetChoiceBindingContext ctx) { Ident ident = new Ident(ctx.Identifier().getText(), nodeSpan(ctx.Identifier())); List<Expr> exprs = ctx.expr().stream().map(this::visitExpr).collect(Collectors.toList()); return new ChoiceBinding(ident, exprs, getSpan(ctx)); } @Override public Object visitLetTableBinding(YokohamaUnitParser.LetTableBindingContext ctx) { List<Ident> names = ctx.Identifier().stream() .map(node -> new Ident(node.getText(), nodeSpan(node))) .collect(Collectors.toList()); Pair<TableType, String> tableRef = visitTableRef(ctx.tableRef()); return new TableBinding( names, tableRef.getFirst(), tableRef.getSecond(), getSpan(ctx)); } @Override public Statement visitStatement(YokohamaUnitParser.StatementContext ctx) { return (Statement)visitChildren(ctx); } @Override public Execution visitExecution(YokohamaUnitParser.ExecutionContext ctx) { return new Execution( ctx.quotedExpr().stream() .map(quotedExpr -> visitQuotedExpr(quotedExpr)) .collect(Collectors.toList()), getSpan(ctx)); } @Override public Invoke visitInvoke(YokohamaUnitParser.InvokeContext ctx) { ClassType classType = visitClassType(ctx.classType()); MethodPattern methodPattern = visitMethodPattern(ctx.methodPattern()); Optional<Expr> receiver = Optional.ofNullable(ctx.quotedExpr()) .map(quotedExpr -> visitQuotedExpr(quotedExpr)); List<Expr> args = ctx.argumentExpr().stream() .map(this::visitArgumentExpr) .collect(Collectors.toList()); return new Invoke(classType, methodPattern, receiver, args, getSpan(ctx)); } @Override public Expr visitExpr(YokohamaUnitParser.ExprContext ctx) { return (Expr)visitChildren(ctx); } @Override public QuotedExpr visitQuotedExpr(YokohamaUnitParser.QuotedExprContext ctx) { return new QuotedExpr(ctx.Expr().getText(), nodeSpan(ctx.Expr())); } @Override public StubExpr visitStubExpr(YokohamaUnitParser.StubExprContext ctx) { ClassType classToStub = visitClassType(ctx.classType()); List<StubBehavior> behavior = ctx.stubBehavior().stream() .map(this::visitStubBehavior) .collect(Collectors.toList()); return new StubExpr(classToStub, behavior, getSpan(ctx)); } @Override public StubBehavior visitStubBehavior(YokohamaUnitParser.StubBehaviorContext ctx) { return (StubBehavior)visitChildren(ctx); } @Override public StubReturns visitStubReturns(YokohamaUnitParser.StubReturnsContext ctx) { MethodPattern methodPattern = visitMethodPattern(ctx.methodPattern()); Expr toBeReturned = visitExpr(ctx.expr()); return new StubReturns(methodPattern, toBeReturned, getSpan(ctx)); } @Override public StubThrows visitStubThrows(YokohamaUnitParser.StubThrowsContext ctx) { MethodPattern methodPattern = visitMethodPattern(ctx.methodPattern()); Expr exception = visitExpr(ctx.expr()); return new StubThrows(methodPattern, exception, getSpan(ctx)); } @Override public MethodPattern visitMethodPattern(YokohamaUnitParser.MethodPatternContext ctx) { String name = ctx.Identifier().getText(); List<Type> argumentTypes = ctx.type().stream().map(this::visitType).collect(Collectors.toList()); boolean varArg = ctx.THREEDOTS() != null; return new MethodPattern(name, argumentTypes, varArg, getSpan(ctx)); } @Override public Type visitType(YokohamaUnitParser.TypeContext ctx) { NonArrayType nonArrayType = visitNonArrayType(ctx.nonArrayType()); int dims = ctx.LBRACKET().size(); return new Type(nonArrayType, dims, getSpan(ctx)); } @Override public NonArrayType visitNonArrayType(YokohamaUnitParser.NonArrayTypeContext ctx) { return (NonArrayType)visitChildren(ctx); } @Override public PrimitiveType visitPrimitiveType(YokohamaUnitParser.PrimitiveTypeContext ctx) { if (ctx.BOOLEAN() != null) { return new PrimitiveType(Kind.BOOLEAN, getSpan(ctx)); } else if (ctx.BYTE() != null) { return new PrimitiveType(Kind.BYTE, getSpan(ctx)); } else if (ctx.SHORT() != null) { return new PrimitiveType(Kind.SHORT, getSpan(ctx)); } else if (ctx.INT() != null) { return new PrimitiveType(Kind.INT, getSpan(ctx)); } else if (ctx.LONG() != null) { return new PrimitiveType(Kind.LONG, getSpan(ctx)); } else if (ctx.CHAR() != null) { return new PrimitiveType(Kind.CHAR, getSpan(ctx)); } else if (ctx.FLOAT() != null) { return new PrimitiveType(Kind.FLOAT, getSpan(ctx)); } else if (ctx.DOUBLE() != null) { return new PrimitiveType(Kind.DOUBLE, getSpan(ctx)); } else { throw new RuntimeException("Shuld not reach here"); } } @Override public ClassType visitClassType(YokohamaUnitParser.ClassTypeContext ctx) { String name = String.join( ".", ctx.Identifier().stream() .map(TerminalNode::getText) .collect(Collectors.toList()) ); return new ClassType(name, getSpan(ctx)); } @Override public InvocationExpr visitInvokeExpr(YokohamaUnitParser.InvokeExprContext ctx) { ClassType classType = visitClassType(ctx.classType()); MethodPattern methodPattern = visitMethodPattern(ctx.methodPattern()); Optional<Expr> receiver = Optional.ofNullable(ctx.quotedExpr()) .map(quotedExpr -> visitQuotedExpr(quotedExpr)); List<Expr> args = ctx.argumentExpr().stream() .map(this::visitArgumentExpr) .collect(Collectors.toList()); return new InvocationExpr(classType, methodPattern, receiver, args, getSpan(ctx)); } @Override public Expr visitArgumentExpr(YokohamaUnitParser.ArgumentExprContext ctx) { return (Expr)visitChildren(ctx); } @Override public IntegerExpr visitIntegerExpr(YokohamaUnitParser.IntegerExprContext ctx) { boolean positive = ctx.MINUS() == null; String literal = ctx.Integer().getText(); return new IntegerExpr(positive, literal, getSpan(ctx)); } @Override public FloatingPointExpr visitFloatingPointExpr(YokohamaUnitParser.FloatingPointExprContext ctx) { boolean positive = ctx.MINUS() == null; String literal = ctx.FloatingPoint().getText(); return new FloatingPointExpr(positive, literal, getSpan(ctx)); } @Override public BooleanExpr visitBooleanExpr(YokohamaUnitParser.BooleanExprContext ctx) { return new BooleanExpr(ctx.FALSE() == null, getSpan(ctx)); } @Override public CharExpr visitCharExpr(YokohamaUnitParser.CharExprContext ctx) { return new CharExpr(ctx.Char().getText(), getSpan(ctx)); } @Override public StringExpr visitStringExpr(YokohamaUnitParser.StringExprContext ctx) { String literal = ctx.EMPTY_STRING() != null ? "" : ctx.Str().getText(); return new StringExpr(literal, getSpan(ctx)); } @Override public AnchorExpr visitAnchorExpr(YokohamaUnitParser.AnchorExprContext ctx) { return new AnchorExpr(ctx.Anchor().getText(), getSpan(ctx)); } @Override public AsExpr visitAsExpr(YokohamaUnitParser.AsExprContext ctx) { return new AsExpr( visitSourceExpr(ctx.sourceExpr()), visitClassType(ctx.classType()), getSpan(ctx)); } @Override public Expr visitSourceExpr(YokohamaUnitParser.SourceExprContext ctx) { return (Expr)visitChildren(ctx); } @Override public ResourceExpr visitResourceExpr(YokohamaUnitParser.ResourceExprContext ctx) { return new ResourceExpr( ctx.Str().getText(), Optional.ofNullable(ctx.classType()).map(this::visitClassType), getSpan(ctx)); } @Override public Heading visitHeading(YokohamaUnitParser.HeadingContext ctx) { return new Heading(ctx.Line().getText(), getSpan(ctx)); } @Override public CodeBlock visitCodeBlock(YokohamaUnitParser.CodeBlockContext ctx) { return new CodeBlock( visitHeading(ctx.heading()), visitAttributes(ctx.attributes()), Lists.map( ctx.CodeLine(), codeLine -> StringUtils.chomp(codeLine.getText())), getSpan(ctx)); } @Override public List<String> visitAttributes(YokohamaUnitParser.AttributesContext ctx) { return Arrays.asList(StringUtils.split(ctx.CodeLine().getText())); } }
package ${package}; import static org.junit.Assert.assertTrue; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.ociweb.gl.api.GreenRuntime; public class WebTest { static GreenRuntime runtime; static int port = 8050; static int telemetryPort = 8097; static String host = "127.0.0.1"; static int timeoutMS = 60_000; static boolean telemetry = false; static int cyclesPerTrack = 100; static boolean useTLS = true; static int parallelTracks = 2; @BeforeClass public static void startServer() { runtime = GreenRuntime.run(new ${mainClass}()); } @AfterClass public static void stopServer() { runtime.shutdownRuntime(); runtime = null; } // @Test // public void getExampleTest() { // StringBuilder results = LoadTester.runClient( // ()-> null, // return (HTTPContentTypeDefaults.PLAIN==r.contentType()) // && "beginning of text file\n".equals(r.structured().readPayload().readUTFFully()); // "/testPageB", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // @Test // public void postExampleTest() { // Writable testData = new Writable() { // @Override // public void write(ChannelWriter writer) { // writer.append("{\"person\":{\"name\":\"bob\",\"age\":42}}"); // StringBuilder results = LoadTester.runClient( // ()->testData, // String readUTFFully = r.structured().readPayload().readUTFFully(); // if (!isMatch) { // System.out.println("bad response: "+readUTFFully); // return isMatch && (HTTPContentTypeDefaults.JSON == r.contentType()); // "/testJSON", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); // @Test // public void jsonExampleTest() { // Person person = new Person("bob",42); // JSONRenderer<Person> renderer = new JSONRenderer<Person>() // .beginObject() // .beginObject("person") // .string("name", (o,t)->t.append(o.name)) // .integer("age", o->o.age) // .endObject() // .endObject(); // StringBuilder results = LoadTester.runClient( // renderer, // ()->person, // && (HTTPContentTypeDefaults.JSON == r.contentType()); // "/testJSON", // useTLS, telemetry, // parallelTracks, cyclesPerTrack, // host, port, timeoutMS); // assertTrue(results.toString(), results.indexOf("Responses invalid: 0 out of "+(cyclesPerTrack*parallelTracks))>=0); }
package VASSAL.counters; import VASSAL.build.GameModule; import VASSAL.build.module.documentation.HelpFile; import VASSAL.command.ChangeTracker; import VASSAL.command.Command; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.ColorConfigurer; import VASSAL.configure.FormattedStringConfigurer; import VASSAL.configure.IntConfigurer; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.configure.TranslatingStringEnumConfigurer; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatablePiece; import VASSAL.search.HTMLImageFinder; import VASSAL.tools.FormattedString; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.RecursionLimitException; import VASSAL.tools.RecursionLimiter; import VASSAL.tools.RecursionLimiter.Loopable; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.image.ImageUtils; import VASSAL.tools.image.LabelUtils; import VASSAL.tools.imageop.AbstractTileOpImpl; import VASSAL.tools.imageop.ImageOp; import VASSAL.tools.imageop.Op; import VASSAL.tools.imageop.ScaledImagePainter; import VASSAL.tools.swing.SwingUtils; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.DoubleConsumer; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.KeyStroke; import javax.swing.plaf.basic.BasicHTML; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * d/b/a "Text Label" * * Displays a text label, with content specified by the user at runtime. */ public class Labeler extends Decorator implements TranslatablePiece, Loopable { public static final String ID = "label;"; // NON-NLS protected Color textBg = Color.black; protected Color textFg = Color.white; private String label = ""; private String lastCachedLabel; private NamedKeyStroke labelKey; private String menuCommand = Resources.getString("Editor.TextLabel.change_label"); private Font font = new Font(Font.DIALOG, Font.PLAIN, 10); private KeyCommand[] commands; private final FormattedString nameFormat = new FormattedString("$" + PIECE_NAME + "$ ($" + LABEL + "$)"); private final FormattedString labelFormat = new FormattedString(""); private static final String PIECE_NAME = "pieceName"; // NON-NLS private static final String BAD_PIECE_NAME = "PieceName"; // NON-NLS private static final String LABEL = "label"; // NON-NLS private double lastZoom = -1.0; private ImageOp lastCachedOp; private ImageOp baseOp; @Deprecated(since = "2021-12-01", forRemoval = true) protected ScaledImagePainter imagePainter = new ScaledImagePainter(); private char verticalJust = 'b'; private char horizontalJust = 'c'; private char verticalPos = 't'; private char horizontalPos = 'c'; private int verticalOffset = 0; private int horizontalOffset = 0; protected int rotateDegrees; protected String propertyName; protected KeyCommand menuKeyCommand; protected String description = ""; private Point position = null; // Label position cache public Labeler() { this(ID, null); } public Labeler(String s, GamePiece d) { mySetType(s); setInner(d); } @Override public void mySetType(String type) { commands = null; final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';'); st.nextToken(); labelKey = st.nextNamedKeyStroke(null); menuCommand = st.nextToken(Resources.getString("Editor.TextLabel.change_label")); final int fontSize = st.nextInt(10); textBg = st.nextColor(null); textFg = st.nextColor(Color.black); verticalPos = st.nextChar('t'); verticalOffset = st.nextInt(0); horizontalPos = st.nextChar('c'); horizontalOffset = st.nextInt(0); verticalJust = st.nextChar('b'); horizontalJust = st.nextChar('c'); nameFormat.setFormat(clean(st.nextToken("$" + PIECE_NAME + "$ ($" + LABEL + "$)"))); final String fontFamily = st.nextToken(Font.DIALOG); final int fontStyle = st.nextInt(Font.PLAIN); font = new Font(fontFamily, fontStyle, fontSize); rotateDegrees = st.nextInt(0); propertyName = st.nextToken("TextLabel"); // NON-NLS description = st.nextToken(""); } /* * Clean up any property names that will cause an infinite loop when used in a label name */ protected String clean(String s) { // Cannot use $PieceName$ in a label format, must use $pieceName$ return s.replace("$" + BAD_PIECE_NAME + "$", "$" + PIECE_NAME + "$"); } @Override public Object getLocalizedProperty(Object key) { if (key.equals(propertyName)) { return getLocalizedLabel(); } else if (Properties.VISIBLE_STATE.equals(key)) { return getLocalizedLabel() + piece.getProperty(key); } else { return super.getLocalizedProperty(key); } } @Override public Object getProperty(Object key) { if (key.equals(propertyName)) { return getLabel(); } else if (Properties.VISIBLE_STATE.equals(key)) { return getLabel() + piece.getProperty(key); } else { return super.getProperty(key); } } @Override public String myGetType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(labelKey) .append(menuCommand) .append(font.getSize()) .append(textBg) .append(textFg) .append(verticalPos) .append(verticalOffset) .append(horizontalPos) .append(horizontalOffset) .append(verticalJust) .append(horizontalJust) .append(nameFormat.getFormat()) .append(font.getFamily()) .append(font.getStyle()) .append(rotateDegrees) .append(propertyName) .append(description); return ID + se.getValue(); } @Override public String myGetState() { return label; } @Override public void mySetState(String s) { setLabel(s.trim()); } @Override public String getName() { String result = ""; if (label.length() == 0) { result = piece.getName(); } else { nameFormat.setProperty(PIECE_NAME, piece.getName()); // Bug 9483 // Don't evaluate the label while reporting an infinite loop // Can cause further looping so that the infinite loop report // never finishes before a StackOverflow occurs if (!RecursionLimiter.isReportingInfiniteLoop()) { nameFormat.setProperty(LABEL, getLabel()); } try { RecursionLimiter.startExecution(this); result = nameFormat.getText(Decorator.getOutermost(this), this, "Editor.TextLabel.name_format"); } catch (RecursionLimitException e) { RecursionLimiter.infiniteLoop(e); } finally { RecursionLimiter.endExecution(); } } return result; } @Override public String getLocalizedName() { if (label.length() == 0) { return piece.getLocalizedName(); } else { final FormattedString f = new FormattedString(getTranslation(nameFormat.getFormat())); f.setProperty(PIECE_NAME, piece.getLocalizedName()); f.setProperty(LABEL, getLocalizedLabel()); return f.getLocalizedText(Decorator.getOutermost(this), this, "Editor.TextLabel.name_format"); } } public String getActualDescription() { return description; } private void updateCachedOpForZoomWindows(double zoom) { if (zoom == lastZoom && lastCachedOp != null) { return; } final float fsize = (float)(font.getSize() * zoom); // Windows renders some characters (e.g. "4") very poorly at 8pt. To // mitigate that, we upscale, render, then downscale when the font // would be 8pt. final boolean isHTML = BasicHTML.isHTMLString(lastCachedLabel); if (!isHTML && Math.round(fsize) == 8.0f) { final Font zfont = font.deriveFont(((float)(3 * font.getSize() * zoom))); lastCachedOp = Op.scale(new LabelOp(lastCachedLabel, zfont, textFg, textBg), 1.0 / 3.0); } else if (zoom == 1.0) { lastCachedOp = baseOp; } else if (isHTML) { lastCachedOp = Op.scale(baseOp, zoom); } else { final Font zfont = font.deriveFont(fsize); lastCachedOp = new LabelOp(lastCachedLabel, zfont, textFg, textBg); } lastZoom = zoom; } private void updateCachedOpForZoomNotWindows(double zoom) { if (zoom == lastZoom && lastCachedOp != null) { return; } if (zoom == 1.0) { lastCachedOp = baseOp; } else if (BasicHTML.isHTMLString(lastCachedLabel)) { lastCachedOp = Op.scale(baseOp, zoom); } else { final float fsize = (float)(font.getSize() * zoom); final Font zfont = font.deriveFont(fsize); lastCachedOp = new LabelOp(lastCachedLabel, zfont, textFg, textBg); } lastZoom = zoom; } private final DoubleConsumer updateCachedOpForZoom = SystemUtils.IS_OS_WINDOWS ? this::updateCachedOpForZoomWindows : this::updateCachedOpForZoomNotWindows; @Override public void draw(Graphics g, int x, int y, Component obs, double zoom) { piece.draw(g, x, y, obs, zoom); updateCachedImage(); if (lastCachedLabel == null) { return; } updateCachedOpForZoom.accept(zoom); final Point p = getLabelPosition(); final int labelX = x + (int) (zoom * p.x); final int labelY = y + (int) (zoom * p.y); AffineTransform saveXForm = null; final Graphics2D g2d = (Graphics2D) g; if (rotateDegrees != 0) { saveXForm = g2d.getTransform(); final AffineTransform newXForm = AffineTransform.getRotateInstance( Math.toRadians(rotateDegrees), x, y); g2d.transform(newXForm); } g.drawImage(lastCachedOp.getImage(), labelX, labelY, obs); if (rotateDegrees != 0) { g2d.setTransform(saveXForm); } } protected void updateCachedImage() { final String ll = getLocalizedLabel(); if (ll == null || ll.isEmpty()) { if (lastCachedLabel != null) { // label has changed to be empty position = null; lastCachedLabel = null; baseOp = lastCachedOp = null; } } else if (!ll.equals(lastCachedLabel)) { // label has changed, is non-empty position = null; lastCachedLabel = ll; if (BasicHTML.isHTMLString(lastCachedLabel)) { baseOp = new HTMLLabelOp(lastCachedLabel, font, textFg, textBg); } else { baseOp = new LabelOp(lastCachedLabel, font, textFg, textBg); } lastCachedOp = null; } } /** * Return the relative position of the upper-left corner of the label, * for a piece at position (0,0). Cache the position of the label once the label * image has been generated. */ private Point getLabelPosition() { if (position != null) { return position; } int x = horizontalOffset; int y = verticalOffset; updateCachedImage(); final Dimension lblSize = baseOp != null ? baseOp.getSize() : new Dimension(); final Rectangle selBnds = piece.getShape().getBounds(); switch (verticalPos) { case 't': y += selBnds.y; break; case 'b': y += selBnds.y + selBnds.height; } switch (horizontalPos) { case 'l': x += selBnds.x; break; case 'r': x += selBnds.x + selBnds.width; } switch (verticalJust) { case 'b': y -= lblSize.height; break; case 'c': y -= lblSize.height / 2; } switch (horizontalJust) { case 'c': x -= lblSize.width / 2; break; case 'r': x -= lblSize.width; } final Point result = new Point(x, y); // Cache the position once the label image has been generated if (lblSize.height > 0 && lblSize.width > 0) { position = result; } return result; } public void setLabel(String s) { if (s == null) s = ""; int index = s.indexOf("$" + propertyName + "$"); while (index >= 0) { s = s.substring(0, index) + s.substring(index + propertyName.length() + 2); index = s.indexOf("$" + propertyName + "$"); } label = s; // prevent recursive references from this label // to piece name (which may contain this label) labelFormat.setProperty(BasicPiece.PIECE_NAME, piece.getName()); labelFormat.setFormat(label); // clear cached values position = null; lastCachedLabel = null; baseOp = lastCachedOp = null; } public void setBackground(Color textBg) { this.textBg = textBg; } public void setForeground(Color textFg) { this.textFg = textFg; } protected static class LabelOp extends AbstractTileOpImpl { protected final String txt; protected final Font font; protected final Color fg; protected final Color bg; protected final int hash; public LabelOp(String txt, Font font, Color fg, Color bg) { this.txt = txt; this.font = font; this.fg = fg; this.bg = bg; hash = new HashCodeBuilder().append(txt) .append(font) .append(fg) .append(bg) .toHashCode(); } @Override public List<VASSAL.tools.opcache.Op<?>> getSources() { return Collections.emptyList(); } @Override public BufferedImage eval() throws Exception { // fix our size if (size == null) fixSize(); // draw nothing if our size is zero if (size.width <= 0 || size.height <= 0) return ImageUtils.NULL_IMAGE; // prepare the target image final BufferedImage im = ImageUtils.createCompatibleImage( size.width, size.height, bg == null || bg.getTransparency() != Color.OPAQUE ); final Graphics2D g = im.createGraphics(); g.addRenderingHints(SwingUtils.FONT_HINTS); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // paint the background if (bg != null) { g.setColor(bg); g.fillRect(0, 0, size.width, size.height); } // paint the foreground if (fg != null) { g.setColor(fg); g.setFont(font); final FontMetrics fm = g.getFontMetrics(font); g.drawString(txt, 0, size.height - fm.getDescent()); } g.dispose(); return im; } protected Dimension buildDimensions() { final Graphics2D g = ImageUtils.NULL_IMAGE.createGraphics(); final FontMetrics fm = g.getFontMetrics(font); final Dimension s = new Dimension(fm.stringWidth(txt), fm.getHeight()); g.dispose(); return s; } @Override protected void fixSize() { if ((size = getSizeFromCache()) == null) { final Dimension s = buildDimensions(); // ensure that our area is nonempty if (s.width <= 0 || s.height <= 0) { s.width = s.height = 1; } size = s; } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof LabelOp)) return false; final LabelOp lop = (LabelOp) o; return Objects.equals(txt, lop.txt) && Objects.equals(font, lop.font) && Objects.equals(fg, lop.fg) && Objects.equals(bg, lop.bg); } @Override public int hashCode() { return hash; } } protected static class HTMLLabelOp extends LabelOp { public HTMLLabelOp(String txt, Font font, Color fg, Color bg) { super(txt, font, fg, bg); } @Override public BufferedImage eval() throws Exception { // fix our size if (size == null) fixSize(); // draw nothing if our size is zero if (size.width <= 0 || size.height <= 0) return ImageUtils.NULL_IMAGE; // prepare the target image final BufferedImage im = ImageUtils.createCompatibleImage( size.width, size.height, bg == null || bg.getTransparency() != Color.OPAQUE ); final Graphics2D g = im.createGraphics(); g.addRenderingHints(SwingUtils.FONT_HINTS); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // paint the background if (bg != null) { g.setColor(bg); g.fillRect(0, 0, size.width, size.height); } // paint the foreground if (fg != null) { final JLabel l = makeLabel(); l.paint(g); } g.dispose(); return im; } protected JLabel makeLabel() { // Build a JLabel to render HTML final JLabel l = new JLabel(txt); l.setForeground(fg); l.setFont(font); l.setSize(l.getPreferredSize()); return l; } @Override protected Dimension buildDimensions() { return makeLabel().getSize(); } } public String getLabel() { return labelFormat.getText(Decorator.getOutermost(this), this, "Editor.TextLabel.label_text"); } public String getLocalizedLabel() { final FormattedString f = new FormattedString(getTranslation(labelFormat.getFormat())); return f.getLocalizedText(Decorator.getOutermost(this), this, "Editor.TextLabel.label_text"); } @Override public Rectangle boundingBox() { final Rectangle r = piece.boundingBox(); final Rectangle labelRect = new Rectangle( getLabelPosition(), baseOp != null ? baseOp.getSize() : new Dimension() ); Rectangle labelBounds; if (rotateDegrees != 0) { final AffineTransform tx = AffineTransform.getRotateInstance( Math.toRadians(rotateDegrees) ); labelBounds = tx.createTransformedShape(labelRect).getBounds(); } else { labelBounds = labelRect; } r.add(labelBounds); return r; } @Deprecated(since = "2021-03-14", forRemoval = true) protected Rectangle lastRect = null; @Deprecated(since = "2021-03-14", forRemoval = true) protected Area lastShape = null; /** * Return the Shape of the counter by adding the shape of this label to the shape of all inner traits. * Minimize generation of new Area objects. */ @Override public Shape getShape() { final Shape innerShape = piece.getShape(); // If the label has a Control key, then the image of the label is NOT // included in the selectable area of the counter if (!labelKey.isNull()) { return innerShape; } final Rectangle labelRect = new Rectangle( getLabelPosition(), baseOp != null ? baseOp.getSize() : new Dimension() ); Shape labelShape; Rectangle labelBounds; if (rotateDegrees != 0) { final AffineTransform tx = AffineTransform.getRotateInstance( Math.toRadians(rotateDegrees) ); labelShape = tx.createTransformedShape(labelRect); labelBounds = labelShape.getBounds(); } else { labelShape = labelBounds = labelRect; } // If the label is completely enclosed in the current counter shape, // then we can just return the current shape if (innerShape.contains(labelBounds)) { return innerShape; } final Area a = new Area(innerShape); a.add(AreaCache.get(labelShape)); return a; } @Override public KeyCommand[] myGetKeyCommands() { if (commands == null) { menuKeyCommand = new KeyCommand(menuCommand, labelKey, Decorator.getOutermost(this), this); if (labelKey == null || labelKey.isNull() || menuCommand == null || menuCommand.length() == 0) { commands = KeyCommand.NONE; } else { commands = new KeyCommand[]{menuKeyCommand}; } } return commands; } @Override public Command myKeyEvent(KeyStroke stroke) { myGetKeyCommands(); Command c = null; if (menuKeyCommand.matches(stroke)) { ChangeTracker tracker = new ChangeTracker(this); final String s = (String) JOptionPane.showInputDialog( getMap() == null ? GameModule.getGameModule().getPlayerWindow() : getMap().getView().getTopLevelAncestor(), menuKeyCommand.getName(), null, JOptionPane.QUESTION_MESSAGE, null, null, label ); if (s == null) { tracker = null; } else { setLabel(s); c = tracker.getChangeCommand(); } } return c; } @Override public String getDescription() { return buildDescription("Editor.TextLabel.trait_description", description, label); } @Override public String getBaseDescription() { return Resources.getString("Editor.TextLabel.trait_description"); } @Override public String getDescriptionField() { return description; } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("Label.html"); // NON-NLS } @Override public PieceEditor getEditor() { return new Ed(this); } @Override public boolean testEquals(Object o) { // Check Class if (! (o instanceof Labeler)) return false; final Labeler l = (Labeler) o; // Check Type if (! Objects.equals(labelKey, l.labelKey)) return false; if (! Objects.equals(menuCommand, l.menuCommand)) return false; if (! Objects.equals(font, l.font)) return false; if (! Objects.equals(textBg, l.textBg)) return false; if (! Objects.equals(textFg, l.textFg)) return false; if (! Objects.equals(verticalPos, l.verticalPos)) return false; if (! Objects.equals(verticalOffset, l.verticalOffset)) return false; if (! Objects.equals(horizontalPos, l.horizontalPos)) return false; if (! Objects.equals(horizontalOffset, l.horizontalOffset)) return false; if (! Objects.equals(verticalJust, l.verticalJust)) return false; if (! Objects.equals(horizontalJust, l.horizontalJust)) return false; if (! Objects.equals(nameFormat, l.nameFormat)) return false; if (! Objects.equals(rotateDegrees, l.rotateDegrees)) return false; if (! Objects.equals(propertyName, l.propertyName)) return false; if (! Objects.equals(description, l.description)) return false; // Check State return Objects.equals(label, l.label); } /** * Return Property names exposed by this trait */ @Override public List<String> getPropertyNames() { final ArrayList<String> l = new ArrayList<>(); if (propertyName.length() > 0) { l.add(propertyName); } return l; } private static class Ed implements PieceEditor { private final NamedHotKeyConfigurer labelKeyInput; private final TraitConfigPanel controls; private final StringConfigurer command; private final StringConfigurer initialValue; private final ColorConfigurer fg, bg; private final TranslatingStringEnumConfigurer vPos; private final TranslatingStringEnumConfigurer hPos; private final TranslatingStringEnumConfigurer vJust; private final TranslatingStringEnumConfigurer hJust; private final IntConfigurer hOff, vOff, fontSize; private final FormattedStringConfigurer format; private final TranslatingStringEnumConfigurer fontFamily; private final IntConfigurer rotate; private final BooleanConfigurer bold, italic; private final StringConfigurer propertyNameConfig; private final StringConfigurer descConfig; public Ed(Labeler l) { controls = new TraitConfigPanel(); descConfig = new StringConfigurer(l.description); descConfig.setHintKey("Editor.description_hint"); controls.add("Editor.description_label", descConfig); initialValue = new StringConfigurer(l.label); initialValue.setHintKey("Editor.TextLabel.label_text_hint"); controls.add("Editor.TextLabel.label_text", initialValue); format = new FormattedStringConfigurer(new String[]{PIECE_NAME, LABEL}); format.setValue(l.nameFormat.getFormat()); // NON-NLS format.setHintKey("Editor.TextLabel.name_format_hint"); controls.add("Editor.TextLabel.name_format", format); //NON-NLS command = new StringConfigurer(l.menuCommand); command.setHintKey("Editor.menu_command_hint"); controls.add("Editor.menu_command", command); labelKeyInput = new NamedHotKeyConfigurer(l.labelKey); controls.add("Editor.keyboard_command", labelKeyInput); fontFamily = new TranslatingStringEnumConfigurer( new String[]{Font.SERIF, Font.SANS_SERIF, Font.MONOSPACED, Font.DIALOG, Font.DIALOG_INPUT}, new String[] { "Editor.Font.serif", "Editor.Font.sans_serif", "Editor.Font.monospaced", "Editor.Font.dialog", "Editor.Font.dialog_input"}, l.font.getFamily()); JPanel p = new JPanel(new MigLayout("ins 0", "[]unrel[]rel[]unrel[]rel[]unrel[]rel[]")); // NON-NLS p.add(fontFamily.getControls()); p.add(new JLabel(Resources.getString("Editor.size_label"))); fontSize = new IntConfigurer(l.font.getSize()); p.add(fontSize.getControls()); p.add(new JLabel(Resources.getString("Editor.TextLabel.bold"))); final int fontStyle = l.font.getStyle(); bold = new BooleanConfigurer(Boolean.valueOf(fontStyle != Font.PLAIN && fontStyle != Font.ITALIC)); p.add(bold.getControls()); p.add(new JLabel(Resources.getString("Editor.TextLabel.italic"))); italic = new BooleanConfigurer(Boolean.valueOf(fontStyle != Font.PLAIN && fontStyle != Font.BOLD)); p.add(italic.getControls()); controls.add("Editor.TextLabel.label_font", p); fg = new ColorConfigurer(l.textFg); controls.add("Editor.TextLabel.text_color", fg); bg = new ColorConfigurer(l.textBg); controls.add("Editor.TextLabel.background_color", bg); vPos = new TranslatingStringEnumConfigurer( new String[] {"c", "t", "b"}, // NON-NLS new String[] { "Editor.center", "Editor.top", "Editor.bottom" }, l.verticalPos ); p = new JPanel(new MigLayout("ins 0", "[100]unrel[]rel[]")); // NON-NLS p.add(vPos.getControls()); p.add(new JLabel(Resources.getString("Editor.TextLabel.offset"))); vOff = new IntConfigurer(l.verticalOffset); p.add(vOff.getControls()); controls.add("Editor.TextLabel.vertical_position", p); hPos = new TranslatingStringEnumConfigurer( new String[] {"c", "l", "r"}, // NON-NLS new String[] { "Editor.center", "Editor.left", "Editor.right" }, l.horizontalPos ); p = new JPanel(new MigLayout("ins 0", "[100]unrel[]rel[]")); // NON-NLS p.add(hPos.getControls()); p.add(new JLabel(Resources.getString("Editor.TextLabel.offset"))); hOff = new IntConfigurer(l.horizontalOffset); p.add(hOff.getControls()); controls.add("Editor.TextLabel.horizontal_position", p); vJust = new TranslatingStringEnumConfigurer( new String[] {"c", "t", "b"}, // NON-NLS new String[] { "Editor.center", "Editor.top", "Editor.bottom" }, l.verticalJust ); controls.add("Editor.TextLabel.vertical_text_justification", vJust, "grow 0"); // NON-NLS hJust = new TranslatingStringEnumConfigurer( new String[] {"c", "l", "r"}, // NON-NLS new String[] { "Editor.center", "Editor.left", "Editor.right" }, l.horizontalJust ); controls.add("Editor.TextLabel.horizontal_text_justification", hJust, "grow 0"); // NON-NLS rotate = new IntConfigurer(l.rotateDegrees); controls.add("Editor.TextLabel.rotate_text_degrees", rotate); propertyNameConfig = new StringConfigurer(l.propertyName); propertyNameConfig.setHintKey("Editor.TextLabel.property_name_hint"); controls.add("Editor.property_name", propertyNameConfig); } @Override public String getState() { return initialValue.getValueString(); } @Override public String getType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(labelKeyInput.getValueString()) .append(command.getValueString()); Integer i = (Integer) fontSize.getValue(); if (i == null || i <= 0) { i = 10; } se.append(i.toString()) .append(bg.getValueString()) .append(fg.getValueString()) .append(vPos.getValueString()); i = (Integer) vOff.getValue(); if (i == null) i = 0; se.append(i.toString()) .append(hPos.getValueString()); i = (Integer) hOff.getValue(); if (i == null) i = 0; se.append(i.toString()) .append(vJust.getValueString()) .append(hJust.getValueString()) .append(format.getValueString()) .append(fontFamily.getValueString()); final int style = Font.PLAIN + (bold.booleanValue() ? Font.BOLD : 0) + (italic.booleanValue() ? Font.ITALIC : 0); se.append(style); i = (Integer) rotate.getValue(); if (i == null) i = 0; se.append(i.toString()) .append(propertyNameConfig.getValueString()) .append(descConfig.getValueString()); return ID + se.getValue(); } @Override public Component getControls() { return controls; } } @Override public PieceI18nData getI18nData() { return getI18nData( new String[] {labelFormat.getFormat(), nameFormat.getFormat(), menuCommand}, new String[] { Resources.getString("Editor.TextLabel.label_text"), Resources.getString("Editor.TextLabel.name_format"), Resources.getString("Editor.TextLabel.change_label_command") }); } /** @deprecated Use {@link VASSAL.tools.image.LabelUtils#drawLabel(Graphics, String, int, int, int, int, Color, Color)} instead. **/ @Deprecated(since = "2020-08-27", forRemoval = true) public static void drawLabel(Graphics g, String text, int x, int y, int hAlign, int vAlign, Color fgColor, Color bgColor) { LabelUtils.drawLabel(g, text, x, y, hAlign, vAlign, fgColor, bgColor); } /** @deprecated Use {@link VASSAL.tools.image.LabelUtils#drawLabel(Graphics, String, int, int, Font, int, int, Color, Color, Color)} instead. **/ @Deprecated(since = "2020-08-27", forRemoval = true) public static void drawLabel(Graphics g, String text, int x, int y, Font f, int hAlign, int vAlign, Color fgColor, Color bgColor, Color borderColor) { LabelUtils.drawLabel(g, text, x, y, f, hAlign, vAlign, fgColor, bgColor, borderColor); } /** * @return a list of any Property Names referenced in the Decorator, if any (for search) */ @Override public List<String> getPropertyList() { return List.of(propertyName); } /** * @return a list of any Named KeyStrokes referenced in the Decorator, if any (for search) */ @Override public List<NamedKeyStroke> getNamedKeyStrokeList() { return Arrays.asList(labelKey); } /** * @return a list of any Menu Text strings referenced in the Decorator, if any (for search) */ @Override public List<String> getMenuTextList() { return List.of(menuCommand); } /** * @return a list of any Message Format strings referenced in the Decorator, if any (for search) */ @Override public List<String> getFormattedStringList() { return List.of(label, nameFormat.getFormat(), labelFormat.getFormat()); } /** * In case our labels refer to any image files * @param s Collection to add image names to */ @Override public void addLocalImageNames(Collection<String> s) { final HTMLImageFinder h = new HTMLImageFinder(label); h.addImageNames(s); } }
package comcondrint.github.sleepdata; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import java.text.*; import java.util.Date; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends AppCompatActivity { public static SharedPreferences pref; public SharedPreferences.Editor dataEditor; EditText RateText; EditText WakeText; EditText SleepText; AlertDialog saveAlert; AlertDialog formatAlert; Integer currentValue; public float[] extractData() { //Get rating 1-5 to use as value for storage float Rating = Float.parseFloat(RateText.getText().toString()); //Extract difference between sleep/wake time to use as key for storage String WakeTime = WakeText.getText().toString(); String SleepTime = SleepText.getText().toString(); SimpleDateFormat format = new SimpleDateFormat("HH:mm"); float[] pair = new float [2]; try { Date date1 = format.parse(WakeTime); Date date2 = format.parse(SleepTime); float difference = Math.abs((date2.getTime() - date1.getTime()) / 3600000); pair[0] = difference; pair[1] = Rating; } catch (ParseException e){ ; //should never get here because I check the format before calling extractdata() }; return pair; } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); dataEditor = pref.edit(); dataEditor.clear(); //for testing dataEditor.apply(); SleepText = (EditText)findViewById(R.id.SleepText); WakeText = (EditText)findViewById(R.id.WakeText); RateText = (EditText)findViewById(R.id.RateText); saveAlert = new AlertDialog.Builder(MainActivity.this).create(); formatAlert = new AlertDialog.Builder(MainActivity.this).create(); formatAlert.setMessage("Wrong input format"); Map <String,?> prefs = pref.getAll(); Integer max = -1; for (String key : prefs.keySet()) { if (Integer.parseInt(key) > max) { max = Integer.parseInt(key); } } currentValue = max + 1; } public void goToRatings(View view) { Intent intent = new Intent(MainActivity.this, RatingChart.class); startActivity(intent); } public void goToData(View view) { Intent intent = new Intent(MainActivity.this, SleepDataActivity.class); startActivity(intent); } public void SaveData(View view) { //amt of sleep is key, rating of ease of waking is value if (checkFormat(view)) { float[] pair = extractData(); String amtSleep = Float.toString(pair[0]); dataEditor.putString(Integer.toString(currentValue), amtSleep + " / " + Integer.toString(Math.round(pair[1]))); dataEditor.apply(); RateText.setText(""); WakeText.setText(""); SleepText.setText(""); saveAlert.setMessage("Data saved" + ": " + amtSleep + " Hours / " + Integer.toString((Math.round(pair[1])))); saveAlert.show(); } else{ //wrong format formatAlert.show(); } } public boolean checkFormat(View view) { //check if inputs are empty before proceeding boolean notEmpty = (!WakeText.getText().toString().isEmpty()) && (!SleepText.getText().toString().isEmpty()) && (!RateText.getText().toString().isEmpty()); if (notEmpty){ //check 1-5 for rating, and 24 hr formatted times for sleep/wake int Rating = Integer.parseInt(RateText.getText().toString()); boolean ratingFormat = (Rating >= 1 && Rating <= 5); //check 24hr format Pattern pattern; pattern = Pattern.compile("([01]?[0-9]|2[0-3]):[0-5][0-9]"); String WakeTime = WakeText.getText().toString(); String SleepTime = SleepText.getText().toString(); return ratingFormat && pattern.matcher(WakeTime).matches() && pattern.matcher(SleepTime).matches(); } else { return false; } } }
package javamm.compiler; import javamm.controlflow.JavammBranchingStatementDetector; import javamm.javamm.JavammArrayAccess; import javamm.javamm.JavammArrayAccessExpression; import javamm.javamm.JavammArrayConstructorCall; import javamm.javamm.JavammArrayLiteral; import javamm.javamm.JavammBranchingStatement; import javamm.javamm.JavammBreakStatement; import javamm.javamm.JavammCharLiteral; import javamm.javamm.JavammContinueStatement; import javamm.javamm.JavammPrefixOperation; import javamm.javamm.JavammXVariableDeclaration; import javamm.util.JavammModelUtil; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.xtext.common.types.JvmField; import org.eclipse.xtext.common.types.JvmIdentifiableElement; import org.eclipse.xtext.common.types.JvmOperation; import org.eclipse.xtext.generator.trace.ILocationData; import org.eclipse.xtext.util.Strings; import org.eclipse.xtext.xbase.XAbstractFeatureCall; import org.eclipse.xtext.xbase.XAssignment; import org.eclipse.xtext.xbase.XBasicForLoopExpression; import org.eclipse.xtext.xbase.XCasePart; import org.eclipse.xtext.xbase.XExpression; import org.eclipse.xtext.xbase.XSwitchExpression; import org.eclipse.xtext.xbase.XVariableDeclaration; import org.eclipse.xtext.xbase.XbasePackage; import org.eclipse.xtext.xbase.compiler.XbaseCompiler; import org.eclipse.xtext.xbase.compiler.output.ITreeAppendable; import org.eclipse.xtext.xbase.lib.IterableExtensions; import org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference; import com.google.inject.Inject; /** * @author Lorenzo Bettini * */ public class JavammXbaseCompiler extends XbaseCompiler { private static final String ASSIGNED_TRUE = " = true;"; @Inject private JavammModelUtil modelUtil; @Inject private JavammBranchingStatementDetector branchingStatementDetector; @Override protected void doInternalToJavaStatement(XExpression obj, ITreeAppendable appendable, boolean isReferenced) { if (obj instanceof JavammArrayConstructorCall) { _toJavaStatement((JavammArrayConstructorCall) obj, appendable, isReferenced); } else if (obj instanceof JavammArrayAccessExpression) { _toJavaStatement((JavammArrayAccessExpression) obj, appendable, isReferenced); } else if (obj instanceof JavammContinueStatement) { _toJavaStatement((JavammContinueStatement) obj, appendable, isReferenced); } else if (obj instanceof JavammBreakStatement) { _toJavaStatement((JavammBreakStatement) obj, appendable, isReferenced); } else { super.doInternalToJavaStatement(obj, appendable, isReferenced); } } public void _toJavaStatement(JavammArrayConstructorCall call, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } public void _toJavaStatement(JavammArrayAccessExpression access, ITreeAppendable b, boolean isReferenced) { // compile it only as expression } public void _toJavaStatement(JavammContinueStatement st, ITreeAppendable b, boolean isReferenced) { XBasicForLoopExpression basicForLoop = modelUtil.getContainingForLoop(st); if (basicForLoop != null && !canCompileToJavaBasicForStatement(basicForLoop, b)) { // the for loop is translated into a while statement, so, before // the continue; we must perform the update expressions and then // check the while condition. EList<XExpression> updateExpressions = basicForLoop.getUpdateExpressions(); for (XExpression updateExpression : updateExpressions) { internalToJavaStatement(updateExpression, b, false); } final String varName = b.getName(basicForLoop); XExpression expression = basicForLoop.getExpression(); if (expression != null) { internalToJavaStatement(expression, b, true); b.newLine().append(varName).append(" = "); internalToJavaExpression(expression, b); b.append(";"); } else { b.newLine().append(varName).append(ASSIGNED_TRUE); } } compileBranchingStatement(st, b); } public void _toJavaStatement(JavammBreakStatement st, ITreeAppendable b, boolean isReferenced) { compileBranchingStatement(st, b); } private void compileBranchingStatement(JavammBranchingStatement st, ITreeAppendable b) { b.newLine().append(st.getInstruction()).append(";"); } @Override protected void internalToConvertedExpression(XExpression obj, ITreeAppendable appendable) { if (obj instanceof JavammArrayConstructorCall) { _toJavaExpression((JavammArrayConstructorCall) obj, appendable); } else if (obj instanceof JavammArrayAccessExpression) { _toJavaExpression((JavammArrayAccessExpression) obj, appendable); } else if (obj instanceof JavammCharLiteral) { _toJavaExpression((JavammCharLiteral) obj, appendable); } else { super.internalToConvertedExpression(obj, appendable); } } public void _toJavaExpression(JavammArrayConstructorCall call, ITreeAppendable b) { if (call.getArrayLiteral() == null) { // otherwise we simply compile the array literal // assuming that no dimension expression has been specified // (checked by the validator) b.append("new "); b.append(call.getType()); } compileArrayAccess(call, b); } public void _toJavaExpression(JavammArrayAccessExpression arrayAccess, ITreeAppendable b) { internalToConvertedExpression(arrayAccess.getArray(), b); compileArrayAccess(arrayAccess, b); } /** * Always compile into a char literal (we've already type checked that, and we * can assign it also to numeric variables as in Java). * * @param literal * @param appendable */ public void _toJavaExpression(JavammCharLiteral literal, ITreeAppendable appendable) { String javaString = Strings.convertToJavaString(literal.getValue(), true); appendable.append("'").append(javaString).append("'"); } @Override protected void assignmentToJavaExpression(XAssignment expr, ITreeAppendable b, boolean isExpressionContext) { final JvmIdentifiableElement feature = expr.getFeature(); if (feature instanceof JvmOperation) { boolean appendReceiver = appendReceiver(expr, b, isExpressionContext); if (appendReceiver) b.append("."); appendFeatureCall(expr, b); } else { boolean isArgument = expr.eContainer() instanceof XAbstractFeatureCall; if (isArgument) { EStructuralFeature containingFeature = expr.eContainingFeature(); if (containingFeature == XbasePackage.Literals.XFEATURE_CALL__FEATURE_CALL_ARGUMENTS || containingFeature == XbasePackage.Literals.XMEMBER_FEATURE_CALL__MEMBER_CALL_ARGUMENTS) { isArgument = false; } else { b.append("("); } } if (feature instanceof JvmField) { boolean appendReceiver = appendReceiver(expr, b, isExpressionContext); if (appendReceiver) b.append("."); appendFeatureCall(expr, b); } else { String name = b.getName(expr.getFeature()); b.append(name); } // custom implementation starts here compileArrayAccess(expr, b); // custom implementation ends here b.append(" = "); internalToJavaExpression(expr.getValue(), b); if (isArgument) { b.append(")"); } } } /** * Overridden to deal with several variable declarations. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#toJavaBasicForStatement(org.eclipse.xtext.xbase.XBasicForLoopExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void toJavaBasicForStatement(XBasicForLoopExpression expr, ITreeAppendable b, boolean isReferenced) { ITreeAppendable loopAppendable = b.trace(expr); loopAppendable.openPseudoScope(); loopAppendable.newLine().append("for ("); EList<XExpression> initExpressions = expr.getInitExpressions(); XExpression firstInitExpression = IterableExtensions.head(initExpressions); if (firstInitExpression instanceof JavammXVariableDeclaration) { JavammXVariableDeclaration variableDeclaration = (JavammXVariableDeclaration) firstInitExpression; LightweightTypeReference type = appendVariableTypeAndName(variableDeclaration, loopAppendable); loopAppendable.append(" = "); if (variableDeclaration.getRight() != null) { compileAsJavaExpression(variableDeclaration.getRight(), loopAppendable, type); } else { appendDefaultLiteral(loopAppendable, type); } // custom implementation since possible additional declarations are contained (i.e., parsed) // in JavamXVariableDeclaration EList<XVariableDeclaration> additionalVariables = variableDeclaration.getAdditionalVariables(); for (int i = 0; i < additionalVariables.size(); i++) { loopAppendable.append(", "); XVariableDeclaration initExpression = additionalVariables.get(i); loopAppendable.append(loopAppendable.declareVariable(initExpression, makeJavaIdentifier(initExpression.getName()))); loopAppendable.append(" = "); if (initExpression.getRight() != null) { compileAsJavaExpression(initExpression.getRight(), loopAppendable, type); } else { appendDefaultLiteral(loopAppendable, type); } } } else { for (int i = 0; i < initExpressions.size(); i++) { if (i != 0) { loopAppendable.append(", "); } XExpression initExpression = initExpressions.get(i); compileAsJavaExpression(initExpression, loopAppendable, getLightweightType(initExpression)); } } loopAppendable.append(";"); XExpression expression = expr.getExpression(); if (expression != null) { loopAppendable.append(" "); internalToJavaExpression(expression, loopAppendable); } loopAppendable.append(";"); EList<XExpression> updateExpressions = expr.getUpdateExpressions(); for (int i = 0; i < updateExpressions.size(); i++) { if (i != 0) { loopAppendable.append(","); } loopAppendable.append(" "); XExpression updateExpression = updateExpressions.get(i); internalToJavaExpression(updateExpression, loopAppendable); } loopAppendable.append(") {").increaseIndentation(); XExpression eachExpression = expr.getEachExpression(); internalToJavaStatement(eachExpression, loopAppendable, false); loopAppendable.decreaseIndentation().newLine().append("}"); loopAppendable.closeScope(); } /** * Overridden to deal with branching instructions. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#toJavaWhileStatement(org.eclipse.xtext.xbase.XBasicForLoopExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void toJavaWhileStatement(XBasicForLoopExpression expr, ITreeAppendable b, boolean isReferenced) { ITreeAppendable loopAppendable = b.trace(expr); boolean needBraces = !bracesAreAddedByOuterStructure(expr); if (needBraces) { loopAppendable.newLine().increaseIndentation().append("{"); loopAppendable.openPseudoScope(); } EList<XExpression> initExpressions = expr.getInitExpressions(); for (int i = 0; i < initExpressions.size(); i++) { XExpression initExpression = initExpressions.get(i); // custom implementation // since a for statement cannot be used as expression we don't need // any special treatment for the last expression internalToJavaStatement(initExpression, loopAppendable, false); } final String varName = loopAppendable.declareSyntheticVariable(expr, "_while"); XExpression expression = expr.getExpression(); if (expression != null) { internalToJavaStatement(expression, loopAppendable, true); loopAppendable.newLine().append("boolean ").append(varName).append(" = "); internalToJavaExpression(expression, loopAppendable); loopAppendable.append(";"); } else { loopAppendable.newLine().append("boolean ").append(varName).append(ASSIGNED_TRUE); } loopAppendable.newLine(); loopAppendable.append("while ("); loopAppendable.append(varName); loopAppendable.append(") {").increaseIndentation(); loopAppendable.openPseudoScope(); XExpression eachExpression = expr.getEachExpression(); internalToJavaStatement(eachExpression, loopAppendable, false); // custom implementation: // if the each expression contains sure branching statements then // we must not generate the update expression and the check expression if (!branchingStatementDetector.isSureBranchStatement(eachExpression) && !isEarlyExit(eachExpression)) { EList<XExpression> updateExpressions = expr.getUpdateExpressions(); for (XExpression updateExpression : updateExpressions) { internalToJavaStatement(updateExpression, loopAppendable, false); } if (expression != null) { internalToJavaStatement(expression, loopAppendable, true); loopAppendable.newLine().append(varName).append(" = "); internalToJavaExpression(expression, loopAppendable); loopAppendable.append(";"); } else { loopAppendable.newLine().append(varName).append(ASSIGNED_TRUE); } } loopAppendable.closeScope(); loopAppendable.decreaseIndentation().newLine().append("}"); if (needBraces) { loopAppendable.closeScope(); loopAppendable.decreaseIndentation().newLine().append("}"); } } /** * In our Javamm switch statement we can always compile into Java switch. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#_toJavaStatement(org.eclipse.xtext.xbase.XSwitchExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void _toJavaStatement(XSwitchExpression expr, ITreeAppendable b, boolean isReferenced) { _toJavaSwitchStatement(expr, b, isReferenced); } /** * Since we want Java switch statement, the compilation is simpler and does * not append break automatically. * * @see org.eclipse.xtext.xbase.compiler.XbaseCompiler#_toJavaSwitchStatement(org.eclipse.xtext.xbase.XSwitchExpression, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void _toJavaSwitchStatement(XSwitchExpression expr, ITreeAppendable b, boolean isReferenced) { final String switchResultName = declareSwitchResultVariable(expr, b, isReferenced); internalToJavaStatement(expr.getSwitch(), b, true); final String variableName = declareLocalVariable(expr, b); b.newLine().append("switch (").append(variableName).append(") {").increaseIndentation(); for (XCasePart casePart : expr.getCases()) { ITreeAppendable caseAppendable = b.trace(casePart, true); caseAppendable.newLine().increaseIndentation().append("case "); ITreeAppendable conditionAppendable = caseAppendable.trace(casePart.getCase(), true); internalToJavaExpression(casePart.getCase(), conditionAppendable); caseAppendable.append(":"); XExpression then = casePart.getThen(); if (then != null) { executeThenPart(expr, switchResultName, then, caseAppendable, isReferenced); } caseAppendable.decreaseIndentation(); } if (expr.getDefault() != null) { ILocationData location = getLocationOfDefault(expr); ITreeAppendable defaultAppendable = location != null ? b.trace(location) : b; defaultAppendable.newLine().increaseIndentation().append("default:"); if (expr.getDefault() != null) { defaultAppendable.openPseudoScope(); executeThenPart(expr, switchResultName, expr.getDefault(), defaultAppendable, isReferenced); defaultAppendable.closeScope(); } defaultAppendable.decreaseIndentation(); } b.decreaseIndentation().newLine().append("}"); } @Override protected void _toJavaStatement(XVariableDeclaration varDeclaration, ITreeAppendable b, boolean isReferenced) { super._toJavaStatement(varDeclaration, b, isReferenced); if (varDeclaration instanceof JavammXVariableDeclaration) { JavammXVariableDeclaration customVar = (JavammXVariableDeclaration) varDeclaration; for (XVariableDeclaration additional : customVar.getAdditionalVariables()) { _toJavaStatement(additional, b, isReferenced); } } } /** * Specialized for prefix operator * * @see org.eclipse.xtext.xbase.compiler.FeatureCallCompiler#featureCalltoJavaExpression(org.eclipse.xtext.xbase.XAbstractFeatureCall, org.eclipse.xtext.xbase.compiler.output.ITreeAppendable, boolean) */ @Override protected void featureCalltoJavaExpression(XAbstractFeatureCall call, ITreeAppendable b, boolean isExpressionContext) { if (call instanceof JavammPrefixOperation) { // we can't simply retrieve the inline annotations as it is done // for postfix operations, since postfix operations are already mapped to // postfix methods operator_plusPlus and operator_minusMinus JvmIdentifiableElement feature = call.getFeature(); if (feature.getSimpleName().endsWith("plusPlus")) { b.append("++"); } else { // the only other possibility is minus minus b.append(" } appendArgument(((JavammPrefixOperation) call).getOperand(), b); return; } super.featureCalltoJavaExpression(call, b, isExpressionContext); } private void compileArrayAccess(XExpression expr, ITreeAppendable b) { if (expr instanceof JavammArrayAccess) { JavammArrayAccess access = (JavammArrayAccess) expr; for (XExpression index : access.getIndexes()) { if (index != null) { b.append("["); internalToJavaExpression(index, b); b.append("]"); } } } } /** * Specialization for {@link JavammArrayConstructorCall} since it can * have dimensions without dimension expression (index). * * @param cons * @param b */ private void compileArrayAccess(JavammArrayConstructorCall cons, ITreeAppendable b) { JavammArrayLiteral arrayLiteral = cons.getArrayLiteral(); if (arrayLiteral != null) { internalToJavaExpression(arrayLiteral, b); } else { Iterable<XExpression> dimensionsAndIndexes = modelUtil.arrayDimensionIndexAssociations(cons); for (XExpression e : dimensionsAndIndexes) { b.append("["); if (e != null) { internalToJavaExpression(e, b); } b.append("]"); } } } }
package org.ccnx.ccn.test.impl; import java.util.ArrayList; import java.util.TreeSet; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.ccnx.ccn.CCNContentHandler; import org.ccnx.ccn.CCNInterestHandler; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.CCNNetworkManager.NetworkProtocol; import org.ccnx.ccn.io.CCNWriter; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.test.CCNTestBase; import org.ccnx.ccn.test.CCNTestHelper; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * Test CCNNetworkManager. * * Note - this test requires ccnd to be running * */ public class NetworkTest extends CCNTestBase { protected static final int WAIT_MILLIS = 8000; protected static final int FLOOD_ITERATIONS = 1000; protected static final int TEST_TIMEOUT = SystemConfiguration.MEDIUM_TIMEOUT; private Semaphore sema = new Semaphore(0); private Semaphore filterSema = new Semaphore(0); private boolean gotData = false; private boolean gotInterest = false; Interest testInterest = null; // Fix test so it doesn't use static names. static CCNTestHelper testHelper = new CCNTestHelper(NetworkTest.class); static ContentName testPrefix = testHelper.getClassChildName("networkTest"); @BeforeClass public static void setUpBeforeClass() throws Exception { CCNTestBase.setUpBeforeClass(); } @AfterClass public static void tearDownAfterClass() throws Exception { CCNTestBase.tearDownAfterClass(); } @Before public void setUp() throws Exception { } /** * Partially test prefix registration/deregistration * @throws Exception */ @Test public void testRegisteredPrefix() throws Exception { TestInterestHandler tfl = new TestInterestHandler(); TestContentHandler tl = new TestContentHandler(); ContentName testName1 = ContentName.fromNative(testPrefix, "foo"); Interest interest1 = new Interest(testName1); ContentName testName2 = ContentName.fromNative(testName1, "bar"); // /foo/bar Interest interest2 = new Interest(testName2); ContentName testName3 = ContentName.fromNative(testName2, "blaz"); // /foo/bar/blaz ContentName testName4 = ContentName.fromNative(testName2, "xxx"); // /foo/bar/xxx Interest interest4 = new Interest(testName4); ContentName testName5 = ContentName.fromNative(testPrefix, "zoo"); // /zoo ContentName testName6 = ContentName.fromNative(testName1, "zoo"); // /foo/zoo ContentName testName7 = ContentName.fromNative(testName2, "spaz"); // /foo/bar/spaz Interest interest6 = new Interest(testName6); // Test that we don't receive interests above what we registered gotInterest = false; putHandle.registerFilter(testName2, tfl); getHandle.expressInterest(interest1, tl); getHandle.checkError(TEST_TIMEOUT); Assert.assertFalse(gotInterest); getHandle.cancelInterest(interest1, tl); getHandle.expressInterest(interest2, tl); filterSema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); getHandle.checkError(TEST_TIMEOUT); Assert.assertTrue(gotInterest); getHandle.cancelInterest(interest2, tl); // Test that an "in-between" prefix gets registered properly gotInterest = false; putHandle.getNetworkManager().cancelInterestFilter(this, testName2, tfl); putHandle.registerFilter(testName3, tfl); putHandle.registerFilter(testName4, tfl); putHandle.registerFilter(testName5, tfl); putHandle.registerFilter(testName2, tfl); putHandle.registerFilter(testName1, tfl); gotInterest = false; filterSema.drainPermits(); getHandle.expressInterest(interest6, tl); filterSema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); getHandle.checkError(TEST_TIMEOUT); Assert.assertTrue(gotInterest); getHandle.cancelInterest(interest6, tl); // Make sure that a filter that is a prefix of a registered filter // doesn't get registered separately. gotInterest = false; filterSema.drainPermits(); putHandle.registerFilter(testName7, tfl); ArrayList<ContentName> prefixes = putHandle.getNetworkManager().getRegisteredPrefixes(); Assert.assertFalse(prefixes.contains(testName7)); getHandle.expressInterest(interest4, tl); filterSema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); getHandle.checkError(TEST_TIMEOUT); Assert.assertTrue(gotInterest); getHandle.cancelInterest(interest4, tl); gotInterest = false; filterSema.drainPermits(); getHandle.expressInterest(interest6, tl); filterSema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); getHandle.checkError(TEST_TIMEOUT); Assert.assertTrue(gotInterest); getHandle.cancelInterest(interest6, tl); putHandle.unregisterFilter(testName1, tfl); putHandle.unregisterFilter(testName2, tfl); putHandle.unregisterFilter(testName3, tfl); putHandle.unregisterFilter(testName5, tfl); putHandle.unregisterFilter(testName7, tfl); // Make sure nothing is registered after a / ContentName slashName = ContentName.fromNative("/"); putHandle.registerFilter(testName1, tfl); putHandle.registerFilter(slashName, tfl); putHandle.registerFilter(testName5, tfl); prefixes = putHandle.getNetworkManager().getRegisteredPrefixes(); Assert.assertFalse(prefixes.contains(testName5)); putHandle.unregisterFilter(testName1, tfl); putHandle.unregisterFilter(slashName, tfl); putHandle.unregisterFilter(testName5, tfl); } @Test public void testNetworkManager() throws Exception { /* * Test re-expression of interest */ CCNWriter writer = new CCNWriter(testPrefix, putHandle); ContentName testName = ContentName.fromNative(testPrefix, "aaa"); testInterest = new Interest(testName); TestContentHandler tl = new TestContentHandler(); getHandle.expressInterest(testInterest, tl); Thread.sleep(80); writer.put(testName, "aaa"); sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); Assert.assertTrue(gotData); writer.close(); } @Test public void testNetworkManagerFixedPrefix() throws Exception { CCNWriter writer = new CCNWriter(putHandle); ContentName testName = ContentName.fromNative(testPrefix, "ddd"); testInterest = new Interest(testName); TestContentHandler tl = new TestContentHandler(); getHandle.expressInterest(testInterest, tl); Thread.sleep(80); writer.put(testName, "ddd"); sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); Assert.assertTrue(gotData); writer.close(); } @Test public void testNetworkManagerBackwards() throws Exception { CCNWriter writer = new CCNWriter(testPrefix, putHandle); // Shouldn't have to do this -- need to refactor test. Had to add it after // fixing CCNWriter to do proper flow control. writer.disableFlowControl(); ContentName testName = ContentName.fromNative(testPrefix, "bbb"); testInterest = new Interest(testName); TestContentHandler tl = new TestContentHandler(); writer.put(testName, "bbb"); Thread.sleep(80); getHandle.expressInterest(testInterest, tl); sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); Assert.assertTrue(gotData); writer.close(); } @Test public void testFreshnessSeconds() throws Exception { CCNWriter writer = new CCNWriter(testPrefix, putHandle); writer.disableFlowControl(); ContentName testName = ContentName.fromNative(testPrefix, "freshnessTest"); writer.put(testName, "freshnessTest", 3); Thread.sleep(80); ContentObject co = getHandle.get(testName, 1000); Assert.assertFalse(co == null); Thread.sleep(WAIT_MILLIS); co = getHandle.get(testName, 1000); Assert.assertTrue(co == null); writer.close(); } @Test public void testInterestReexpression() throws Exception { /* * Test re-expression of interest */ CCNWriter writer = new CCNWriter(testPrefix, putHandle); ContentName testName = ContentName.fromNative(testPrefix, "ccc"); testInterest = new Interest(testName); TestContentHandler tl = new TestContentHandler(); getHandle.expressInterest(testInterest, tl); // Sleep long enough that the interest must be re-expressed Thread.sleep(WAIT_MILLIS); writer.put(testName, "ccc"); sema.tryAcquire(WAIT_MILLIS, TimeUnit.MILLISECONDS); Assert.assertTrue(gotData); writer.close(); } /** * Test flooding the system with a bunch of content. Only works for TCP * @throws Exception */ @Test public void testFlood() throws Exception { if (getHandle.getNetworkManager().getProtocol() == NetworkProtocol.TCP) { System.out.println("Testing TCP flooding"); TreeSet<ContentObject> cos = new TreeSet<ContentObject>(); for (int i = 0; i < FLOOD_ITERATIONS; i++) { ContentName name = ContentName.fromNative(testPrefix, (new Integer(i)).toString()); cos.add(ContentObject.buildContentObject(name, new byte[]{(byte)i})); } for (ContentObject co : cos) putHandle.put(co); for (int i = 0; i < FLOOD_ITERATIONS; i++) { ContentObject co = getHandle.get(ContentName.fromNative(testPrefix, new Integer(i).toString()), 2000); Assert.assertNotNull("Failed in flood after " + i + " iterations", co); } } } class TestInterestHandler implements CCNInterestHandler { public boolean handleInterest(Interest interest) { gotInterest = true; filterSema.release(); return true; } } class TestContentHandler implements CCNContentHandler { public Interest handleContent(ContentObject co, Interest interest) { Assert.assertFalse(co == null); gotData = true; sema.release(); /* * Test call of cancel in handler doesn't hang */ getHandle.cancelInterest(interest, this); return null; } } }
package engine; import saladConstants.SaladConstants; import stage.Game; import stage.Scene; import stage.Transition; import stage.Transition.StateType; import util.SaladUtil; import jgame.JGColor; import jgame.platform.StdGame; import objects.GameObject; import objects.Gravity; import objects.NonPlayer; import objects.Player; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class GameEngine extends StdGame{ // public static final Dimension SIZE = new Dimension(800, 600); // public static final String TITLE = "Platformer Game Editor"; public static final int FRAMES_PER_SECOND = 70; public static final int MAX_FRAMES_TO_SKIP = 2; public static final int JGPOINT_X = 800; public static final int JGPOINT_Y = 600; protected Game myGame; protected int myCurrentLevelID; protected int myCurrentSceneID; protected Scene myCurrentScene; protected Player myPlayer; protected int myMouseX; protected int myMouseY; protected int myMouseButton; protected int myClickedID; protected boolean myViewOffsetPlayer = true; protected int myViewOffsetRate = 1; protected int myTileX; protected int myTileY; protected int myTileCid; protected String myTileImgFile; protected boolean isEditingMode; public GameEngine(boolean editing){ initEngineComponent(JGPOINT_X, JGPOINT_Y); isEditingMode = editing; } @Override public void initCanvas () { setCanvasSettings(40, // width of the canvas in tiles 30, // height of the canvas in tiles 20, // width of one tile 20, // height of one tile null,// foreground colour -> use default colour white null,// background colour -> use default colour black null); // standard font -> use default font } @Override public void initGame () { setFrameRate(FRAMES_PER_SECOND, MAX_FRAMES_TO_SKIP); createTiles(0, "null", 0, 0, 0, 0);//why? //setTileSettings(" //setPFWrap(false,true,0,0); if(isEditingMode){ setGameState("Edit"); } } public boolean checkGoal(){ if(myCurrentScene == null) return false; String winBehavior = myGame.getLevel(myCurrentLevelID).getWinBehavior(); List<Object> winParameters = myGame.getLevel(myCurrentLevelID).getWinParameters(); ResourceBundle behaviors = ResourceBundle.getBundle(SaladConstants.DEFAULT_ENGINE_RESOURCE_PACKAGE + SaladConstants.DEFAULT_BEHAVIOR); Object answer = SaladUtil.behaviorReflection(behaviors, winBehavior, winParameters, "checkGoal", this); return (Boolean) answer; } public void startEdit(){ removeObjects(null,0);//remove? } //drag;move->gravity->collision->setViewOffset public void doFrameEdit(){ timer++; if (myCurrentScene == null) return; boolean viewOffset = false; if(drag()) myViewOffsetPlayer = false; else{ moveObjects(); Gravity g = myGame.getGravity(); g.applyGravity(myPlayer); for(GameObject go: myCurrentScene.getGameObjects()){ g.applyGravity(go); } for (int[] pair: myGame.getCollisionPair()){ checkCollision(pair[0], pair[1]); } for (int[] pair: myGame.getTileCollisionPair()){ checkBGCollision(pair[0], pair[1]); } viewOffset = setViewOffsetEdit(); if(!viewOffset) setViewOffsetPlayer(); else myViewOffsetPlayer = false; } if(!viewOffset) setViewOffsetEdit(); } private void setViewOffsetPlayer() { if (myPlayer != null){ if(myViewOffsetRate > 1) myViewOffsetRate -= 1; if(isEditingMode && !myViewOffsetPlayer) myViewOffsetRate = 35; myViewOffsetPlayer = true; int desired_viewXOfs = (int) myPlayer.x+myPlayer.getXSize()/2-viewWidth()/2; int desired_viewYOfs = (int) myPlayer.y+myPlayer.getYSize()/2-viewHeight()/2; setViewOffset((desired_viewXOfs-viewXOfs())/myViewOffsetRate+viewXOfs(),(desired_viewYOfs-viewYOfs())/myViewOffsetRate+viewYOfs(),false); } } private boolean setViewOffsetEdit() { int speed = 10; double margin = 0.1; if (!isEditingMode) return false; int XOfs = 0; int YOfs = 0; double x_ratio = 1.0*getMouseX()/viewWidth(); double y_ratio = 1.0*getMouseY()/viewHeight(); if (0 <= x_ratio && x_ratio <= margin){ XOfs -= speed*(1-x_ratio/margin); } if ((1-margin) <= x_ratio && x_ratio <= 1){ XOfs += speed*(1-(1-x_ratio)/margin); } if (0 <= y_ratio && y_ratio <= margin){ YOfs -= speed*(1-y_ratio/margin); } if ((1-margin) <= y_ratio && y_ratio <= 1){ YOfs += speed*(1-(1-y_ratio)/margin); } setViewOffset(viewXOfs()+XOfs,viewYOfs()+YOfs,false); return XOfs != 0 || YOfs != 0; } public void paintFrameEdit(){ drawString("You are in Editing Mode right now. This is a test message.",pfWidth()/2,pfHeight()/2,0,true); if (myPlayer != null){ drawRect(myPlayer.x+myPlayer.getXSize()/2,myPlayer.y-myPlayer.getYSize()/5,myPlayer.getXSize(),10,true,true,true); drawString("lol help!",myPlayer.x+myPlayer.getXSize()/2,myPlayer.y-myPlayer.getYSize()/2,0,true); } // drawRect(getMouseX()+viewXOfs(),getMouseY()+viewYOfs(),20,20,false,true,true); if(checkGoal()){ drawString("Win!!!!!!!!!!!!!!!! ", viewWidth()/2,viewHeight()/2+100,0,true); } if(myMouseButton!=0 && myClickedID == -1){ int tileX = myMouseX/20; int tileY = myMouseY/20; if(myMouseButton==3) setColor(JGColor.red);//should only be applied to the last line drawRect((double)Math.min(myTileX,tileX)*20,(double)Math.min(myTileY,tileY)*20,(double)(Math.abs(myTileX-tileX)+1)*20,(double)(Math.abs(myTileY-tileY)+1)*20,false,false); } } public void defineLevel(){ level += 1;//shouldn't be here setCurrentScene(level, 0); //restore the player ? depending on playing mode } public void initNewLife(){ //restore the player } /** * (non-Javadoc) * @see jgame.platform.StdGame#doFrame() * For inGame States */ @Override public void doFrame(){ if(!isEditingMode){ super.doFrame(); } //else } /** * (non-Javadoc) * @see jgame.platform.StdGame#paintFrame() * For inGame states */ @Override public void paintFrame(){ if(!isEditingMode){ super.paintFrame(); } //else } public void StartTitle(){ setTransition(StateType.Title); } public void StartStartGame(){ setTransition(StateType.StartGame); } public void StartStartLevel(){ setTransition(StateType.StartLevel); } public void StartLevelDone(){ setTransition(StateType.LevelDone); } public void StartLifeLost(){ setTransition(StateType.LifeLost); } public void StartGameOver(){ setTransition(StateType.GameOver); } // @Override // public void paintFrameTitle(){ // @Override // public void paintFrameStartGame(){ // @Override // public void paintFrameStartLevel(){ // @Override // public void paintFrameLevelDone(){ // @Override // public void paintFrameLifeLost(){ // @Override // public void paintFrameGameOver(){ // @Override // public void paintFrameEnterHighscore(){ // @Override // public void paintFrameHighscores(){ // @Override // public void paintFramePaused(){ //unfinished public void createTiles(int cid, String imgfile, int top, int left, int width, int height){ if (cid > 9) return; defineImage(((Integer) cid).toString(),((Integer) cid).toString(),cid,imgfile,"-"); String temp = ""; for(int i=0;i<width;i++){ temp += cid; } String[] array = new String[height]; for(int j=0;j<height;j++){ array[j] = temp; } setTiles(top,left,array); } public int getClickedID(){ List<GameObject> list = new ArrayList<GameObject>(); if (getMouseButton(1)){ int MouseX = getMouseX()+viewXOfs(); int MouseY = getMouseY()+viewYOfs(); if (myPlayer != null && myPlayer.x < MouseX && MouseX < myPlayer.x + myPlayer.getXSize() && myPlayer.y < MouseY && MouseY < myPlayer.y + myPlayer.getYSize()){ list.add(myPlayer); } for(GameObject go: myCurrentScene.getGameObjects()){ if (go.isAlive() && go.x < MouseX && MouseX < go.x + go.getXSize() && go.y < MouseY && MouseY < go.y + go.getYSize()){ list.add(go); } } } if (list.isEmpty()){ return -1; } return list.get(0).getID(); } public boolean drag(){ boolean drag = false; boolean currentMouse1 = getMouseButton(1); boolean currentMouse3 = getMouseButton(3); int MouseX = getMouseX()+viewXOfs(); int MouseY = getMouseY()+viewYOfs(); int tileX = MouseX/20; int tileY = MouseY/20; if (myMouseButton!=1 && currentMouse1){ myClickedID = getClickedID(); myTileX = tileX; myTileY = tileY; } if (myMouseButton==1 && !currentMouse1){ if (myClickedID == -1){ createTiles(myTileCid, myTileImgFile, Math.min(myTileX,tileX), Math.min(myTileY,tileY), Math.abs(myTileX-tileX)+1, Math.abs(myTileY-tileY)+1); } myClickedID = -1; } if (myMouseButton==1 && currentMouse1){ if (myClickedID > 0){ NonPlayer actor = myCurrentScene.getNonPlayer(myClickedID); actor.x+=MouseX-myMouseX; actor.y+=MouseY-myMouseY; } if (myClickedID == 0){ myPlayer.x+=MouseX-myMouseX; myPlayer.y+=MouseY-myMouseY; } drag = myClickedID > -1; } if (myMouseButton!=3 && currentMouse3){ myTileX = tileX; myTileY = tileY; } if (myMouseButton==3 && !currentMouse3){ createTiles(0, "null", Math.min(myTileX,tileX), Math.min(myTileY,tileY), Math.abs(myTileX-tileX)+1, Math.abs(myTileY-tileY)+1); } myMouseButton = 0; if(currentMouse1) myMouseButton = 1; if(currentMouse3) myMouseButton = 3; myMouseX = MouseX; myMouseY = MouseY; return drag; } public void setDefaultTiles(int cid, String imgfile){ myTileCid = cid; myTileImgFile = imgfile; } // public void createTiles(){ // boolean currentMouseClicked = getMouseButton(1); // if (!myMouseClicked && currentMouseClicked){ // myTileX = getMouseX()/20; // myTileY = getMouseY()/20; // if (myMouseClicked && !currentMouseClicked){ // int tileX = getMouseX()/20; // int tileY = getMouseY()/20; // createTiles(Math.min(myTileX,tileX), Math.min(myTileY,tileY), Math.abs(myTileX-tileX)+1, Math.abs(myTileY-tileY)+1, myTileCid, myTileImgFile); // if (myMouseClicked && currentMouseClicked){ // myMouseClicked = currentMouseClicked; //unfinished public void loadImage(String path){ //scaling might be done here; dimension parameters needed if (path == null) return; defineImage(path, "-", 0, path, "-"); } //unfinished private void setTransition(StateType type){ //setSequences(startgame_ingame, 0, leveldone_ingame, 0, lifelost_ingame, 0, gameover_ingame, 0); Transition trans = myGame.getNonLevelScene(type); String url = trans.getBackground(); if(url != null){ loadImage(url); setBGImage(url); } //something else to do ? } public void setCurrentScene (int currentLevelID, int currentSceneID) { if(myCurrentScene != null){ for(GameObject go: myCurrentScene.getGameObjects()){ go.suspend(); } } myCurrentLevelID = currentLevelID; myCurrentSceneID = currentSceneID; myCurrentScene = myGame.getScene(myCurrentLevelID, myCurrentSceneID); String url = myCurrentScene.getBackgroundImage(); if(url != null){ loadImage(url); setBGImage(url); } for(GameObject go: myCurrentScene.getGameObjects()){ go.resume(); } } public void setBackground(String url){ myCurrentScene.setBackgroundImage(url); loadImage(url); setBGImage(url); } public void setGame (Game mygame) { myGame = mygame; } public Game getGame(){ return myGame; } public int getCurrentLevelID(){ return myCurrentLevelID; } public int getCurrentSceneID(){ return myCurrentSceneID; } /** * Should be called by the GameFactory to createPlayer * Return a created GameObject */ public Player createPlayer(int unique_id, String url, int xsize, int ysize, double xpos, double ypos, String name, int colid, int lives){ loadImage(url); Player object = new Player(unique_id, url, xsize, ysize, xpos, ypos, name, colid, lives); myGame.setPlayer(object); myPlayer = object; if(!isEditingMode){ object.suspend();//not sure how things are created for playing the game } return object; } public NonPlayer createActor(int unique_id, String url, int xsize, int ysize, double xpos, double ypos, String name, int colid, int lives){ loadImage(url); NonPlayer object = new NonPlayer(unique_id, url, xsize, ysize, xpos, ypos, name, colid, lives); if(unique_id != SaladConstants.NULL_UNIQUE_ID){ myCurrentScene.addNonPlayer(object); } if(!isEditingMode){ object.suspend();//not sure how things are created for playing the game } return object; } }
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Connection; import java.sql.Statement; import java.util.Properties; import com.sun.rowset.CachedRowSetImpl; public class Bank { private Properties properties = new Properties(); private static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; private String host, username, password; public Bank(){ String configFile = "config.properties"; try { properties.load(new FileInputStream(configFile)); } catch (FileNotFoundException ex) { ex.printStackTrace(); return; } catch (IOException ex) { ex.printStackTrace(); return; } catch (Exception ex) { ex.printStackTrace(); return; } host = properties.getProperty("host", "jdbc:mysql: username = properties.getProperty("username"); password = properties.getProperty("password", ""); if(username == null || username.isEmpty()){ //user ]w System.out.println("user passwd not set"); } if(password.isEmpty()){ System.out.println("database passwd not set"); } // dataBaseSearch(host,username,password,""); } private ResultSet dbSearch(String sql){ Connection dbConn = null; Statement stmt = null; ResultSet rs1 = null; CachedRowSetImpl crs = null; //ResultSetCached try { Class.forName(DBDRIVER); dbConn = DriverManager.getConnection(host,username,password); System.out.println(dbConn); //Check Point if(!sql.equals("")){ stmt = dbConn.createStatement(); rs1 = stmt.executeQuery(sql); crs = new CachedRowSetImpl(); crs.populate(rs1); } rs1.close(); stmt.close(); dbConn.close(); System.out.println("<dbConn.close>"); //<<<<<checkpoint } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } System.out.println("<return rs checkpoint>"); //<<<<checkpoint return crs; } private boolean dbUpdate(String sql){ Connection dbConn = null; Statement stmt = null; try { Class.forName(DBDRIVER); dbConn = DriverManager.getConnection(host,username,password); System.out.println(dbConn); //<<<Check Point stmt = dbConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); System.out.println("stmt.close val checkpoint"); //<<<<checkpoint dbConn.close(); System.out.println("<dbConn.close>"); //<<<<<checkpoint return true; } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } catch (SQLException e) { e.printStackTrace(); return false; } } private boolean accIsExist(String aID){ try { ResultSet rs1 = dbSearch("SELECT AccID FROM tAccount WHERE AccID = "+aID); int count = 0; while(rs1.next()) count++; return (count == 1) ? true:false; } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean validate(String aID, String aPIN){ ResultSet rs = null; String sql = ("SELECT * FROM tAccount WHERE AccID = '" +aID+ "' AND PIN = '"+ aPIN +"'"); //SELECT * FROM tAccount WHERE AccID = "A10546" AND PIN = "458712"; boolean loginFlag = false; System.out.println(sql); try { rs = this.dbSearch(sql); System.out.println("<SQL>-getRS-"); //<<<<<checkpoint int count = 0; while(rs.next()) count++; loginFlag = (count == 1) ? true:false; } catch (SQLException e) { e.printStackTrace(); } return loginFlag; } public String getAccName(String aID, String aPIN){ ResultSet rs = null; String name; String sql = ("SELECT Name FROM tCustomer JOIN tAccount " + "ON tAccount.CustomerID = tCustomer.CustomerID " + "WHERE AccID = \"" +aID+ "\""); try { rs = this.dbSearch(sql); rs.next(); name = rs.getString("Name"); System.out.println("<SQL>-getName-"); //<<<<<checkpoint return name; } catch (SQLException e) { e.printStackTrace(); return null; } } public String[] checkMoney(String aID, String aPIN){ String[] data = new String[2]; ResultSet rs = null; String sql = ("SELECT tBankAccount.BankAccID,Balance FROM tBankAccount JOIN tAccount " + "ON tBankAccount.BankAccID = tAccount.BankAccID " + "WHERE AccID = '" +aID+ "' AND PIN = '"+ aPIN +"'"); System.out.println(sql); try{ rs = this.dbSearch(sql); rs.next(); data[0] = rs.getString("BankAccID"); data[1] = rs.getString("Balance"); rs.close(); System.out.println("<dbConn.close>"); //<<<<<checkpoint }catch (SQLException e) { e.printStackTrace(); data[0] = "Error"; data[1] = "Error"; } return data; } public boolean pickUpMoney(String aID, String aPIN, double money){ boolean flag = false; String sql = ("UPDATE tBankAccount" +" SET Balance = Balance - " + money +" WHERE BankAccID = ( SELECT * FROM tAccount WHERE AccID = \"" +aID+ "\" AND PIN = \""+ aPIN +"\""); flag = this.dbUpdate(sql); return flag; } public boolean saveMoney(String aID, String aPIN, double money){ return this.pickUpMoney(aID, aPIN, -money); } }
/** * $$\\ToureNPlaner\\$$ */ package graphrep; import java.io.Serializable; /** * Class GraphRep */ public class GraphRep implements Serializable { private static final long serialVersionUID = 13L; private static class Sorter { private static void sort(GraphRep graphRep) { heapify(graphRep); int endI = graphRep.dest.length - 1; while (endI > 0) { swap(graphRep, endI, 0); siftDown(graphRep, 0, endI - 1); endI } } private static void swap(GraphRep graphRep, int i, int j) { int temp = graphRep.mapping_InToOut[i]; graphRep.mapping_InToOut[i] = graphRep.mapping_InToOut[j]; graphRep.mapping_InToOut[j] = temp; } /** * * @param graphRep * @param i * @param j * @return */ private static boolean less(GraphRep graphRep, int i, int j) { int edgeI, edgeJ; int targetI, targetJ; int sourceRankI, sourceRankJ; edgeI = graphRep.mapping_InToOut[i]; edgeJ = graphRep.mapping_InToOut[j]; targetI = graphRep.dest[edgeI]; targetJ = graphRep.dest[edgeJ]; sourceRankI = graphRep.getRank(graphRep.src[edgeI]); sourceRankJ = graphRep.getRank(graphRep.src[edgeJ]); return targetI < targetJ || (targetI == targetJ && sourceRankI > sourceRankJ); } private static void heapify(GraphRep graphRep) { int pos = graphRep.dest.length - 1; while (pos >= 0) { siftDown(graphRep, pos, graphRep.dest.length - 1); pos } } private static void siftDown(GraphRep graphRep, int topI, int endI) { int cLI; int cMI; int cRI; int cMaxI; while (((topI * 3) + 1) <= endI) { cLI = (topI * 3) + 1; cMI = cLI + 1; cRI = cLI + 2; cMaxI = topI; if (less(graphRep, cMaxI, cLI)) { cMaxI = cLI; } if ((cMI <= endI) && less(graphRep, cMaxI, cMI)) { cMaxI = cMI; } if ((cRI <= endI) && less(graphRep, cMaxI, cRI)) { cMaxI = cRI; } if (cMaxI != topI) { swap(graphRep, cMaxI, topI); topI = cMaxI; } else { return; } } } } protected NNSearcher searcher; private final int nodeCount; private final int edgeCount; // note: edgeNum refers to the relative number of an outgoing edge // from a node: // (first outgoing edge = 0, second outgoing edge = 1, ...) // nodes // In degrees*10^7 protected final int[] lat; protected final int[] lon; protected final int[] height; protected final int[] rank; // edges protected final int[] src; protected final int[] dest; protected final int[] dist; protected final int[] euclidianDist; protected final int[] shortedEdge1; protected final int[] shortedEdge2; protected final int[] offsetOut; protected final int[] offsetIn; /** * Index = "virtual" id for in edges * * content = position in the edge array */ protected final int[] mapping_InToOut; /** * A graphrep is the representation of a graph used to perform several * algorithms on. All its protected fields must be be set from the outside * (which is not nice) */ public GraphRep(int nodeCount, int edgeCount) { this.nodeCount = nodeCount; this.edgeCount = edgeCount; this.lat = new int[nodeCount]; this.lon = new int[nodeCount]; this.height = new int[nodeCount]; this.rank = new int[nodeCount]; this.offsetOut = new int[nodeCount + 1]; this.offsetIn = new int[nodeCount + 1]; this.src = new int[edgeCount]; this.dest = new int[edgeCount]; this.dist = new int[edgeCount]; this.euclidianDist = new int[edgeCount]; this.shortedEdge1 = new int[edgeCount]; this.shortedEdge2 = new int[edgeCount]; this.mapping_InToOut = new int[edgeCount]; } /** * Sets the data fields of the node given by it's id * * @param id * @param lat * in degrees*10^7 * @param lon * in degrees*10^7 * @param height */ protected final void setNodeData(int id, int lat, int lon, int height) { this.lat[id] = lat; this.lon[id] = lon; this.height[id] = height; this.rank[id] = Integer.MAX_VALUE; } /** * Sets the rank of the node given by it's id * * @param id * @param rank */ protected final void setNodeRank(int id, int rank) { this.rank[id] = rank; } /** * Set the data filed of the edge given by it's id * * @param index * @param src * @param dest * @param dist * @param multipliedDist */ protected final void setEdgeData(int index, int src, int dest, int dist, int euclidianDist) { this.mapping_InToOut[index] = index; this.src[index] = src; this.dest[index] = dest; this.dist[index] = dist; this.euclidianDist[index] = euclidianDist; this.shortedEdge1[index] = -1; this.shortedEdge1[index] = -1; } /** * Sets the shortcut fields of the edge given by it's id * * @param id * @param shortedID * @param outEdgeSourceNum * @param outEdgeShortedNum */ protected final void setShortcutData(int id, int shortedEdge1, int shortedEdge2) { this.shortedEdge1[id] = shortedEdge1; this.shortedEdge2[id] = shortedEdge2; } /** * Regenerates the offset arrays from the current edge arrays */ protected final void generateOffsets() { int currentSource; int prevSource = -1; for (int i = 0; i < edgeCount; i++) { currentSource = src[i]; if (currentSource != prevSource) { for (int j = currentSource; j > prevSource; j offsetOut[j] = i; } prevSource = currentSource; } } offsetOut[nodeCount] = edgeCount; // assuming we have at least one edge for (int cnt = nodeCount - 1; offsetOut[cnt] == 0; cnt offsetOut[cnt] = offsetOut[cnt + 1]; } Sorter.sort(this); int currentDest; int prevDest = -1; for (int i = 0; i < edgeCount; i++) { currentDest = dest[mapping_InToOut[i]]; if (currentDest != prevDest) { for (int j = currentDest; j > prevDest; j offsetIn[j] = i; } prevDest = currentDest; } } offsetIn[nodeCount] = edgeCount; // assuming we have at least one edge for (int cnt = nodeCount - 1; offsetIn[cnt] == 0; cnt offsetIn[cnt] = offsetIn[cnt + 1]; } } /** * Gets the distance in the shortest path format that is multiplied for travel time * of the the edge given by it's edgeId * (that's not an edgeNum but a unique Id for each edge) get the Id with * GetOutEdgeID() and GetInEdgeID() * * @return int * @param edgeID * @param edgeNum */ public final int getDist(int edgeID) { return dist[edgeID]; } /** * Gets the distance (in meters) of the the edge given by it's edgeId * (that's not an edgeNum but a unique Id for each edge) get the Id with * GetOutEdgeID() and GetInEdgeID() * * @return int * @param edgeID * @param edgeNum */ public final int getEuclidianDist(int edgeID) { return euclidianDist[edgeID]; } /** * Gets the number of edges in the graph * * @return int */ public final int getEdgeCount() { return edgeCount; } /** * Gets the edgeId of the first shortcutted edge * * @param edgeId * @return */ public final int getFirstShortcuttedEdge(int edgeId) { return shortedEdge1[edgeId]; } /** * Gets the edgeId of the second shortcutted edge * * @param edgeId * @return */ public final int getSecondShortcuttedEdge(int edgeId) { return shortedEdge2[edgeId]; } /** * Gets the node id of the node nearest to the given coordinates * * @param srclat * @param srclon * @return */ public final int getIDForCoordinates(int srclat, int srclon) { return searcher.getIDForCoordinates(srclat, srclon); } /** * Gets the distance in shortest path form that is multiplied for travel time * of the in going edge identified by it's * target node and edgeNum the edgeNum is between 0 and * getInEdgeCount(nodeId)-1 * * @return int * @param nodeID * @param edgeNum */ public final int getInDist(int nodeID, int edgeNum) { // return dist_in[offsetIn[nodeID] + edgeNum]; return dist[mapping_InToOut[offsetIn[nodeID] + edgeNum]]; } /** * Gets the euclidian distance (in meters) of the in going edge identified by it's * target node and edgeNum the edgeNum is between 0 and * getInEdgeCount(nodeId)-1 * * @return int * @param nodeID * @param edgeNum */ public final int getInEuclidianDist(int nodeID, int edgeNum) { // return dist_in[offsetIn[nodeID] + edgeNum]; return euclidianDist[mapping_InToOut[offsetIn[nodeID] + edgeNum]]; } /** * Gets the number of in going edges of the given node * * @return int * @param nodeID */ public final int getInEdgeCount(int nodeID) { return offsetIn[nodeID + 1] - offsetIn[nodeID]; } /** * gets the edgeId of the in going edge identified by it's target node and * edgeNum * * @param nodeID * @param edgeNum * @return */ public final int getInEdgeID(int nodeID, int edgeNum) { return mapping_InToOut[offsetIn[nodeID] + edgeNum]; } /** * Gets the source of the in going edge identified by it's target node and * edgeNum the edgeNum is between 0 and getInEdgeCount(nodeId)-1 * * @return int * @param nodeID */ public final int getInSource(int nodeID, int edgeNum) { // return src_in[offsetIn[nodeID] + edgeNum]; return src[mapping_InToOut[offsetIn[nodeID] + edgeNum]]; } /** * Gets the edgeId of the first shortcutted edge of the given ingoing edge * * @param nodeID * @param edgeNum * @return */ public final int getInFirstShortcuttedEdge(int nodeID, int edgeNum) { return shortedEdge1[mapping_InToOut[offsetOut[nodeID] + edgeNum]]; } /** * Gets the edgeId of the second shortcutted edge of the given ingoing edge * * @param nodeID * @param edgeNum * @return */ public final int getInSecondShortcuttedEdge(int nodeID, int edgeNum) { return shortedEdge2[mapping_InToOut[offsetOut[nodeID] + edgeNum]]; } /** * Gets the number of nodes in the graph * * @return int */ public final int getNodeCount() { return nodeCount; } /** * Gets the height of the given node in meters * * @return float * @param nodeID */ public final float getNodeHeight(int nodeID) { return height[nodeID]; } /** * Gets the latitude of the node with the given nodeId * * @return int (degrees*10^7) * @param nodeID */ public final int getNodeLat(int nodeID) { return lat[nodeID]; } /** * Gets the longitude of the node with the given nodeId * * @return int (degrees*10^7) * @param nodeID */ public final int getNodeLon(int nodeID) { return lon[nodeID]; } /** * Gets the distance (in meters) of the out going edge identified by it's * source node and edgeNum the edgeNum is between 0 and * getOutEdgeCount(nodeId)-1 * * @return int * @param nodeID * @param edgeNum */ public final int getOutDist(int nodeID, int edgeNum) { return dist[offsetOut[nodeID] + edgeNum]; } /** * Gets the number of out going edges of the given node * * @param nodeID */ public final int getOutEdgeCount(int nodeID) { return offsetOut[nodeID + 1] - offsetOut[nodeID]; } /** * Gets the edgeId of the out going edge identified by it's source node and * edgeNum * * @param nodeID * @param edgeNum * @return */ public final int getOutEdgeID(int nodeID, int edgeNum) { return offsetOut[nodeID] + edgeNum; } /** * Gets the edgeId of the first shortcutted edge of the given outgoing edge * * @param nodeID * @param edgeNum * @return */ public final int getOutFirstShortcuttedEdge(int nodeID, int edgeNum) { return shortedEdge1[offsetOut[nodeID] + edgeNum]; } /** * Gets the edgeId of the second shortcutted edge of the given outgoing edge * * @param nodeID * @param edgeNum * @return */ public final int getOutSecondShortcuttedEdge(int nodeID, int edgeNum) { return shortedEdge2[offsetOut[nodeID] + edgeNum]; } /** * Gets the target of the out going edge identified by it's source node and * edgeNum the edgeNum is between 0 and getOutEdgeCount(nodeId)-1 * * @return int * @param nodeID * @param edgeNum */ public final int getOutTarget(int nodeID, int edgeNum) { return dest[offsetOut[nodeID] + edgeNum]; } /** * Gets the CH rank in the graph, can be MAX_INT if the node hasn't been * contracted at all CH property is getRank(nodeA)<=getRank(nodeB) * * @param nodeID * @return */ public final int getRank(int nodeID) { return rank[nodeID]; } /** * Gets the source of the the edge given by it's edgeId (that's not an * edgeNum but a unique Id for each edge) get the Id with GetOutEdgeID() and * GetInEdgeID() * * @return int * @param edgeID */ public final int getSource(int edgeID) { return src[edgeID]; } /** * Gets the target of the the edge given by it's edgeId (that's not an * edgeNum but a unique Id for each edge) get the Id with GetOutEdgeID() and * GetInEdgeID() * * @return int * @param edgeID */ public final int getTarget(int edgeID) { return dest[edgeID]; } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.script.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class Game { public String _name; // The name of the game. public int _x; // The current x coordinate of the player public int _y; // The current y coordinate of the player public String _in; // Used to hold user's input and modify it (everything is toLower()'d) public String _out; // Used to create and edit the output public Room[][] _rooms; // HUGE variable; contains all of the rooms public KeyCombo[] _globalkeys; public String[] _itemnames; public int[] _itemquantities; public Scanner scanner = new Scanner(System.in); // The scanner! I'm surprised I didn't name it scanly; I usually name my scanners scanly ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine js_engine = mgr.getEngineByName("js"); Bindings js_binding = js_engine.getBindings(ScriptContext.ENGINE_SCOPE); Object score; public Game() // Default constructor! Never used! { } // Constructor. Very simple one at that. // This function just passes through to buildGameFromFile(), // because that function needs to be able to rebuild the game if given the loadGame utopiaScript command public Game(String filename) { buildGameFromFile(filename); } private void buildGameFromFile(String filename) { /** BEGIN TEMPORARY VARIABLES **/ String name; String progress = ""; String s_x; String s_y; String s_width; String s_height; int x; int y; int width; int height; /** END TEMPORARY VARIABLES **/ try { File fXmlFile = new File(filename); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); Element gameNode = (Element)doc.getDocumentElement(); if(!gameNode.getNodeName().equalsIgnoreCase("game")) { throw new LoadGameException("Game node is not first node in file."); } name = gameNode.getAttribute("name"); s_x = gameNode.getAttribute("x"); s_y = gameNode.getAttribute("y"); s_width = gameNode.getAttribute("width"); s_height = gameNode.getAttribute("height"); if(name.equals("")) { throw new LoadGameException("Name of game is not specified, or empty string."); } try { progress = "x"; if(s_x.equals("")) { _x = 0; } else { _x = Integer.parseInt(s_x); } progress = "y"; if(s_y.equals("")) { _y = 0; } else { _y = Integer.parseInt(s_y); } progress = "width"; if(s_width.equals("")) { throw new LoadGameException("Parameter width on Game node is not specified."); } width = Integer.parseInt(s_width); progress = "height"; if(s_height.equals("")) { throw new LoadGameException("Parameter height on Game node is not specified."); } height = Integer.parseInt(s_height); if(_x > width || _y > height) { throw new LoadGameException("Starting coordinates are outside game boundaries."); } } catch(NumberFormatException e) { throw new LoadGameException("Parameter \"" + progress + "\" on Game node is unparsable as Integer."); } /** <COMMANDS> PARSING **/ this.buildGameCommands(gameNode.getElementsByTagName("commands").item(0)); /** <ITEMS> PARSING **/ this.buildGameItems(gameNode.getElementsByTagName("items").item(0)); /** <ROOMS> PARSING **/ this.buildGameRooms(gameNode.getElementsByTagName("rooms").item(0), width, height); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Builds the game's _globalkeys array from the <commands> node parsed from the XML * @param commandsNode the <commands> node from the game XML * @return Void; directly modifies the object's _globalkeys member */ private void buildGameCommands(Node commandsNode) { Element commands = (Element)commandsNode; Node helpNode = commands.getElementsByTagName("help").item(0); NodeList directionNodes = commands.getElementsByTagName("direction"); NodeList globalKeys = ((Element)commands.getElementsByTagName("globalkeys").item(0)).getChildNodes(); // N, E, S, and W. int direction_list_length = 4; for(int i = 0;i < directionNodes.getLength();i++) { if(!stringIn(((Element)directionNodes.item(i)).getAttribute("direction"), new String[]{"n", "e", "s", "w"}, false)) { direction_list_length++; } } _globalkeys = new KeyCombo[6+direction_list_length+globalKeys.getLength()]; _globalkeys[0] = new KeyCombo("", ""); _globalkeys[1] = new KeyCombo("inv(entory)?", "<utopiascript>inventory;</utopiascript>"); if(helpNode == null) { _globalkeys[2] = new KeyCombo("^help$", "<utopiascript>print To move between rooms, type MOVE or GO and a cardinal direction. To look at your inventory, type INV or INVENTORY. To get a description of the room you're in, type DESC or DESCRIPTION. To quit, type EXIT or QUIT. To save or load, type SAVE or LOAD.;</utopiascript>"); } else { _globalkeys[2] = new KeyCombo(helpNode); } _globalkeys[3] = new KeyCombo("(move )?n(orth)?", "<utopiascript>go +0/+1;</utopiascript>"); _globalkeys[4] = new KeyCombo("(move )?e(ast)?", "<utopiascript>go +1/+0;</utopiascript>"); _globalkeys[5] = new KeyCombo("(move )?s(outh)?", "<utopiascript>go -0/-1;</utopiascript>"); _globalkeys[6] = new KeyCombo("(move )?w(est)?", "<utopiascript>go -1/-0;</utopiascript>"); int global_key_index = 7; for(int i = 0; i < directionNodes.getLength(); i++) { Element directionCommand = (Element)directionNodes.item(i); String direction = directionCommand.getAttribute("direction"); if(direction.equals("n")) { _globalkeys[3] = new KeyCombo(directionCommand); } else if(direction.equals("e")) { _globalkeys[4] = new KeyCombo(directionCommand); } else if(direction.equals("s")) { _globalkeys[5] = new KeyCombo(directionCommand); } else if(direction.equals("w")) { _globalkeys[6] = new KeyCombo(directionCommand); } else if(!direction.equals("")) { _globalkeys[global_key_index] = new KeyCombo(directionCommand); global_key_index++; } else { throw new LoadGameException("Direction found without a direction name"); } } for(int i = 0; i < globalKeys.getLength(); i++) { _globalkeys[global_key_index] = new KeyCombo(globalKeys.item(i)); global_key_index++; } } /** * Builds the game's _itemnames and _itemquantities arrays from the <items> node * @param itemsNode the <items> node in the game XML * @return Void; directly modifies the _itemnames and _itemquantities members */ private void buildGameItems(Node itemsNode) { String item_quantity; // temporary variable NodeList itemNodes = itemsNode.getChildNodes(); _itemnames = new String[itemNodes.getLength()]; _itemquantities = new int[itemNodes.getLength()]; for(int i = 0;i < itemNodes.getLength(); i++) { Node itemNode = itemNodes.item(i); item_quantity = ((Element)itemNode).getAttribute("quantity"); _itemnames[i] = itemNode.getTextContent().trim(); try { if(item_quantity.equals("")) { _itemquantities[i] = 0; } else { _itemquantities[i] = Integer.parseInt(item_quantity); } } catch(NumberFormatException e) { throw new LoadGameException("Parameter \"quantity\" on item node " + i + " is unparsable as Integer."); } } } /** * Builds the game's _rooms array from the <rooms> node * @param roomsNode the <rooms> node parsed from the XML * @param width the width attribute from the <game> node * @param height the height attribute from the <game> node * @return Void; directly modifies the _rooms member */ private void buildGameRooms(Node roomsNode, int width, int height) { int x; // temporary variable int y; // temporary variable _rooms = new Room[width][height]; // Instantiate each room with default constructor, to ensure that they are initialized for(int i = 0;i < width;i++) { for(int j = 0;j < height;j++) { _rooms[i][j] = new Room(); } } NodeList roomNodes = roomsNode.getChildNodes(); int i = 0; int j = 0; for(int index = 0; index < roomNodes.getLength(); index++) { Node nRoom = roomNodes.item(index); if(!nRoom.getNodeName().equalsIgnoreCase("room")) { throw new LoadGameException("Non-room node found in the rooms node"); } Element eRoom = (Element)nRoom; // x and y are unspecified on the room node; place it in the first available space. if(eRoom.getAttribute("x").equals("") && eRoom.getAttribute("y").equals("")) { // Find the next open slot in the rooms array. while(_rooms[i][j].canTravel()) { i++; if(i > width) { i = 0; j++; } } _rooms[i][j] = new Room(nRoom); // Continue through the _rooms array i++; if(i > width) { i = 0; j++; } } // x and y are BOTH specified on the room node. else if(!eRoom.getAttribute("x").equals("") && eRoom.getAttribute("y").equals("")) { try { x = Integer.parseInt(eRoom.getAttribute("x")); y = Integer.parseInt(eRoom.getAttribute("y")); } catch(NumberFormatException e) { throw new LoadGameException("Coordinates on room node " + index + " are unparsable as Integer."); } // Check to see if the coordinate specified already has a room in it. if(_rooms[x][y].canTravel()) { throw new LoadGameException("Two rooms specified for the same position: (" + x + "," + y + ")"); } } else { throw new LoadGameException("Either x or y is unspecified on room node " + index + ". Specify either both or neither."); } } } // Main function of the Game class. // The run function will continue to loop until the player hits an endgame or quits. public void run() { System.out.print("\nWelcome to " + this._name + "!"); // Welcomes the user to the game. do // do-while loops usually aren't my thing, but it's a huge code block { while (true) // Probably not a good idea to use a while(true) with a break... { System.out.print("\n\nYou may play a New Game, Load Game, Delete Game, or Quit.\n\n> "); _in = scanner.nextLine().toLowerCase(); // toLowerCase() is very important, because EVERY key is lowercase. // A much better way to handle this is to use equalsIgnoreCase() when comparing strings. while ((!_in.equals("new game")) && (!_in.equals("new")) && (!_in.equals("load game")) && (!_in.equals("load")) && (!_in.equals("quit game")) && (!_in.equals("quit")) && (!_in.equals("delete game")) && (!_in.equals("delete"))) { System.out.print("\nInvalid response. New Game, Load Game, or Quit?\n\n> "); _in = scanner.nextLine().toLowerCase(); } // If the player wants to load their game, then load it. if ((_in.equals("load game")) || (_in.equals("load"))) { System.out.print("\n"); _endgame = 50000; if (!loadState()) // If there's no game to load, go back to the in-game menu. { _endgame = 2147483646; } } else if ((_in.equals("delete game")) || (_in.equals("delete"))) { System.out.print("\n"); deleteGame(); _endgame = 2147483646; // If they delete their game, go back to the in-game menu. } else if ((_in.equals("quit game")) || (_in.equals("quit"))) { _endgame = 2147483647; // If they quit, go back to the in-game menu, at which point the game will close. } else { _endgame = 0; } if (_endgame < 10000) // First time in the game, game will output the intro { System.out.print("\n"); for (int i = 0; i < _intro.length; i++) { System.out.print(_intro[i]); pause(); } } if (_endgame < 100000) // Then initialize the rooms { for (int i = 0; i < _rooms.length; i++) { for (int j = 0; j < _rooms[i].length; j++) { this._rooms[i][j].setRoomstate(0); this._rooms[i][j]._seen = false; } } _invHave = _invHaveBackup; System.out.print(_rooms[_x][_y].description() + "\n\n> "); } while (_endgame < 100000) // MAIN GAME LOOP. { // THIS LOOP WILL CONTINUE UNTIL THE PLAYER ENDS IT _in = scanner.nextLine().toLowerCase(); // BY HITTING AN ENDGAME OR BY QUITTING System.out.print("\n"); _endgame = iterate(_in); if ((_endgame > 99999) && (_endgame != 2147483647)) { _endgame -= 100000; break; } if (_endgame == 2147483647) continue; System.out.print("\n\n> "); } if ((_endgame == 2147483647) || (_endgame == 2147483646)) break; System.out.print("\n\n"); for (int i = 0; i < _endgames[_endgame].length; i++) { if (_endgames[_endgame][i].equals("")) continue; System.out.print(_endgames[_endgame][i]); pause(); } } } while ((_endgame == 2147483646) || (_endgame != 2147483647)); System.out.print("\n"); } public static int iterate(String in) // This function represents a single time through the game loop. { if (_in.equals("help")) { System.out.print(_helpMessage); } else if ((_in.equals("quit")) || (_in.equals("exit"))) // if the player specifies they want to quit { System.out.print("Are you sure? Y/N\n\n> "); // Make sure it was purposeful _in = scanner.nextLine().toLowerCase(); while ((!_in.equals("y")) && (!_in.equals("yes"))) { if ((_in.equals("n")) || (_in.equals("no"))) { _in = "nvm"; System.out.print("\n" + _rooms[_x][_y].description()); break; } System.out.print("\nYes or no, please. If you're feeling lazy, you can shorten it to Y or N.\n\n> "); _in = scanner.nextLine().toLowerCase(); } if (!_in.equals("nvm")) { return 2147483647; // If they're sure, quick. } } else if ((_in.equals("inv")) || (_in.equals("inventory"))) // If the player wants to see their inventory, { outputInv(); // display the inventory } else if ((_in.equals("north")) || (_in.equals("move north")) || (_in.equals("n")) || (_in.equals("go north"))) // If move north, { moveNorth(); // move north! } else if ((_in.equals("east")) || (_in.equals("move east")) || (_in.equals("e")) || (_in.equals("go east"))) // So on { moveEast(); // And so forth } else if ((_in.equals("south")) || (_in.equals("move south")) || (_in.equals("s")) || (_in.equals("go south"))) // For each { moveSouth(); // of the } else if ((_in.equals("west")) || (_in.equals("move west")) || (_in.equals("w")) || (_in.equals("go west"))) // cardinal { moveWest(); // directions } else if (_in.equals("move")) // "move" is not super helpful { System.out.print("Move which way?"); } else if (_in.equals("go")) // same with "go" { System.out.print("Go which way?"); } else if ((_in.equals("desc")) || (_in.equals("describe")) || (_in.equals("description")) || (_in.equals("see")) || (_in.equals("inspect"))) { System.out.print(_rooms[_x][_y].description(false)); // Used to output the description of the current room } else if (_in.equals("save")) { saveState(); // Save's player's game state } else if (_in.equals("load")) // Load's the player's game state, then outputs the description { loadState(); System.out.print(_rooms[_x][_y].description()); } else // If none of the special commands are met, then do the normal comparison: { int key = _rooms[_x][_y].getKey(_in); // Check to see if the input matches a key if (key >= 0) // If it does, { int roomstate = _rooms[_x][_y].getRoomstate(); // get the roomstate of the room if (checkInventory(roomstate, key) == true) // Check to see if any inventorycheck conditions are met. If so, { System.out.print(_rooms[_x][_y].getEvent(roomstate, key)); // Print the corresponding event. updateInventory(roomstate, key); // Update the inventory (if applicable) int roomstatefactor = _rooms[_x][_y].getRoomstateFactor(roomstate, key); // update the roomstate _rooms[_x][_y].changeRoomstate(roomstatefactor); return roomstatefactor; // return a random integer! } System.out.print("You don't have the right item(s) to do that."); return -2147483648; } System.out.print("You can't do that."); } return -2147483648; } // Calculates how many items the player has in their inventory static int howMany() { int howmany = 0; for (int i = 0; i < _invHave.length; i++) { if (_invHave[i] != true) continue; howmany++; } return howmany; } // Outputs the player's inventory public static void outputInv() { String finished = "You have in your inventory:\n\n"; int count = 1; for (int i = 0; i < _invHave.length; i++) { if ((_invHave[i] == true) && (count < howMany())) { finished = finished + _invNames[i] + "\n"; count++; } else { if (_invHave[i] != true) continue; finished = finished + _invNames[i]; count++; } } if (finished.equals("You have in your inventory:\n\n")) { finished = "You don't have anything!"; } System.out.print(finished); } // Makes sure the player has any items required for the given key // Removes items if so public static boolean checkInventory(int roomstate, int key) { InventoryCheck check = _rooms[_x][_y].getInventoryCheck(roomstate, key); check.checkNext(); while (check.checkNext() == true) { int item = check.getNext(); if (_invHave[item] == false) { return false; } } return true; } // Updates player's inventory to have any items given by the associated key public static void updateInventory(int roomstate, int key) { InventoryUpdate update = _rooms[_x][_y].getInventoryUpdate(roomstate, key); while (update.checkNext() == true) { int item = update.getNext(); if (_invHave[item] != false) { _invHave[item] = false; continue; } _invHave[item] = true; } } // Moves the player north! // Uses a silly bit of modulus arithmetic to determine where the player is going public static void moveNorth() { int x = _rooms[_x][_y].checkNorth(); if (x < 10000) { int y = x % 100; x = (x - x % 100) / 100; moveLocation(x, y); System.out.print(_rooms[_x][_y].description()); } else if (x == 10200) { if (_y == 0) { System.out.print("You can't go that way."); } else { moveTranslate(0, -1); System.out.print(_rooms[_x][_y].description()); } } else if (x == 10403) { System.out.print("You can't go that way."); } } // Moves the player east! // Uses a silly bit of modulus arithmetic to determine where the player is going public static void moveEast() { int y = _rooms[_x][_y].checkEast(); if (y < 10000) { int x = (y - y % 100) / 100; y %= 100; moveLocation(x, y); System.out.print(_rooms[_x][_y].description()); } else if (y == 10200) { if (_x == _rooms.length - 1) { System.out.print("You can't go that way."); } else { moveTranslate(1, 0); System.out.print(_rooms[_x][_y].description()); } } else if (y == 10403) { System.out.print("You can't go that way."); } } // Moves the player south! // Uses a silly bit of modulus arithmetic to determine where the player is going public static void moveSouth() { int x = _rooms[_x][_y].checkSouth(); if (x < 10000) { int y = x % 100; x = (x - x % 100) / 100; moveLocation(x, y); System.out.print(_rooms[_x][_y].description()); } else if (x == 10200) { if (_y == _rooms[_x].length - 1) { System.out.print("You can't go that way."); } else { moveTranslate(0, 1); System.out.print(_rooms[_x][_y].description()); } } else if (x == 10403) { System.out.print("You can't go that way."); } } // Moves the player west! // Uses a silly bit of modulus arithmetic to determine where the player is going public static void moveWest() { int y = _rooms[_x][_y].checkWest(); if (y < 10000) { int x = (y - y % 100) / 100; y %= 100; moveLocation(x, y); System.out.print(_rooms[_x][_y].description()); } else if (y == 10200) { if (_x == 0) { System.out.print("You can't go that way."); } else { moveTranslate(-1, 0); System.out.print(_rooms[_x][_y].description()); } } else if (y == 10403) { System.out.print("You can't go that way."); } } // Saves the state of the game. public static void saveState() { System.out.print(getSaveData() + "Which savestate would you like to save over? Type \"cancel\" to cancel.\n\n> "); _in = scanner.nextLine(); _in = _in.toLowerCase(); while ((!_in.equals("1")) && (!_in.equals("2")) && (!_in.equals("3")) && (!_in.equals("state 1")) && (!_in.equals("state 2")) && (!_in.equals("state 3")) && (!_in.equals("cancel"))) { System.out.print("\nInvalid input. Please try again.\n\n> "); _in = scanner.nextLine(); } if (!_in.equals("cancel")) { if (!_in.equals(_in.split(" ")[0])) { _in = _in.split(" ")[1]; } try { File file = new File("..\\" + _name + ".ug" + _in); FileWriter fileWriter = new FileWriter("..\\" + _name + ".ug" + _in); String savefile = ""; System.out.print("\nPlease enter an identifying name for this savestate.\n\n> "); _in = scanner.nextLine(); savefile = savefile + _in.toUpperCase(); savefile = savefile + "QLNK"; savefile = savefile + _x + "<" + _y + "QLNK"; for (int i = 0; i < _invHave.length; i++) { if (_invHave[i] == true) { savefile = savefile + "76ANQ<"; } else { savefile = savefile + "QNA67<"; } } savefile = savefile.substring(0, savefile.length() - 1); savefile = savefile + "QLNK"; for (int i = 0; i < _rooms.length; i++) { for (int j = 0; j < _rooms[i].length; j++) { savefile = savefile + _rooms[i][j].getRoomstate(); savefile = savefile + "<"; } savefile = savefile.substring(0, savefile.length() - 1); savefile = savefile + ">"; } savefile = savefile.substring(0, savefile.length() - 1); fileWriter.write(savefile); fileWriter.close(); System.out.print("\nGame successfully saved."); } catch (Exception e) { System.out.println("HERE System.out.println(e.getMessage()); // Not really robust, because I haven't had the opportunity to test on various platforms System.out.println(e.getStackTrace()); } } else { System.out.print("\nSave cancelled."); } } // Load's the player's state from a state file public static boolean loadState() { System.out.print(getSaveData() + "Which savestate would you like to load? Type \"cancel\" to cancel.\n\n> "); _in = scanner.nextLine(); _in = _in.toLowerCase(); while ((!_in.equals("1")) && (!_in.equals("2")) && (!_in.equals("3")) && (!_in.equals("state 1")) && (!_in.equals("state 2")) && (!_in.equals("state 3")) && (!_in.equals("cancel"))) { System.out.print("\nInvalid input. Please try again.\n\n> "); _in = scanner.nextLine(); } if (!_in.equals("cancel")) { if (!_in.equals(_in.split(" ")[0])) { _in = _in.split(" ")[1]; } try { FileReader fr = new FileReader("..\\" + _name + ".ug" + _in); BufferedReader fileReader = new BufferedReader(fr); String[] savestate = { "", "", "", "" }; String[] coordinates = { "", "" }; String[] itemsHave = { "", "" }; String[][] roomstates = { { "", "" }, { "", "" } }; boolean[] invHave = new boolean[_invHave.length]; int[][] rooms = new int[_rooms.length][_rooms[0].length]; savestate[0] = fileReader.readLine(); savestate = savestate[0].split("QLNK"); try { savestate[3].equals(savestate[3]); } catch (Exception e) { throw new Exception("loadfail"); } coordinates = savestate[1].split("<"); int x = Integer.parseInt(coordinates[0]); int y = Integer.parseInt(coordinates[1]); itemsHave = savestate[2].split("<"); for (int i = 0; i < itemsHave.length; i++) { if (itemsHave[i].equals("76ANQ")) { invHave[i] = true; } else if (itemsHave[i].equals("QNA67")) { invHave[i] = false; } else { throw new Exception("loadfail"); } } int k = savestate[3].split(">").length; for (int i = 0; i < k; i++) { roomstates[i] = savestate[3].split(">")[i].split("<"); } for (int i = 0; i < roomstates.length; i++) { for (int j = 0; j < roomstates[i].length; j++) { rooms[i][j] = Integer.parseInt(roomstates[i][j]); } } _x = x; _y = y; _invHave = invHave; for (int i = 0; i < _rooms.length; i++) { for (int j = 0; j < _rooms[i].length; j++) { _rooms[i][j].setRoomstate(rooms[i][j]); } } System.out.print("\nLoad State successful.\n\n"); return true; } catch (Exception e) { System.out.print("\nLoad State failed."); return false; } } System.out.print("\nLoad cancelled."); return false; } // Deletes a savestate public static void deleteGame() { System.out.print(getSaveData() + "Which savestate would you like to delete? Type \"cancel\" to cancel.\n\n> "); _in = scanner.nextLine(); _in = _in.toLowerCase(); while ((!_in.equals("1")) && (!_in.equals("2")) && (!_in.equals("3")) && (!_in.equals("state 1")) && (!_in.equals("state 2")) && (!_in.equals("state 3")) && (!_in.equals("cancel"))) { System.out.print("\nInvalid input. Please try again.\n\n> "); _in = scanner.nextLine(); } if (!_in.equals("cancel")) { if (!_in.equals(_in.split(" ")[0])) { _in = _in.split(" ")[1]; } try { File file = new File("..\\" + _name + ".ug" + _in); if (!file.exists()) { throw new Exception(""); } FileWriter fileWriter = new FileWriter(file); fileWriter.write(""); fileWriter.close(); System.out.print("\nState deleted."); } catch (Exception e) { System.out.print("\nState deletion failed."); } } } // Gets a list of available savestates public static String getSaveData() { String listOfGames = ""; String[] savestate = { "", "", "", "" }; for (int i = 1; i < 4; i++) { listOfGames = listOfGames + "State " + i + ": "; File f = new File("..\\" + _name + ".ug" + i); if (f.exists()) { try { FileReader fr = new FileReader("..\\" + _name + ".ug" + i); BufferedReader fileReader = new BufferedReader(fr); savestate[0] = fileReader.readLine(); savestate = savestate[0].split("QLNK"); if (savestate[0].equals(savestate[0])) { listOfGames = listOfGames + savestate[0]; listOfGames = listOfGames + "\n"; } } catch (Exception e) { listOfGames = listOfGames + "Blank\n"; } } else { listOfGames = listOfGames + "Blank\n"; } } listOfGames = listOfGames + "\n"; return listOfGames; } // Moves a specified number of rooms in each direction. public static void moveTranslate(int horiz, int vert) { _x += horiz; _y += vert; } // Moves to a given coordinate public static void moveLocation(int x, int y) { _x = x; _y = y; } // Pauses, waiting for the player to press enter public static void pause() { System.out.print("\n\nPress enter..."); scanner.nextLine(); System.out.println(); return; } public static void pause(String prompt) { if(prompt.length() == 0) { pause(); } else { System.out.print("\n\n" + prompt); scanner.nextLine(); System.out.println(); } } /** * Runs the event gotten from a key. * @String event, the combination JavaScript and UtopiaScript corresponding to the matched event. */ public void runEvent(String key, String event) { js_engine.put("key", key); String[] events = event.split("((?<=<utopiaScript>)|(?=<utopiaScript>)|(?<=</utopiaScript>)|(?=</utopiaScript>))"); int command_count = 0; for(int i = 0;i < events.length;i++) { if(!stringIn(events[i], new String[]{"<utopiascript>", "</utopiascript>"}, false)) { command_count++; } } String[] commands = new String[command_count]; boolean[] uscript = new boolean[command_count]; int x = 0; boolean uscript_flag = false; for(int i = 0;i < events.length;i++) { if(!stringIn(events[i], new String[]{"<utopiascript>", "</utopiascript>"}, false)) { commands[x] = events[i]; uscript[x] = uscript_flag; x++; } else if(events[i].equalsIgnoreCase("<utopiascript>")) { uscript_flag = true; } else { uscript_flag = false; } } // Runs all of the commands in a loop. Placed in a function to allow premature ending if one of the commands fails. try { runCommands(commands, uscript); updateScore(); } catch(ScriptException e) { // TODO: Better exception-handling System.out.println(e.getMessage()); System.out.println(e.getStackTrace()); } catch(UtopiaException e) { // TODO: Better exception-handling System.out.println(e.getMessage()); System.out.println(e.getStackTrace()); } } private void runCommands(String[] commands, boolean[] uscript) throws ScriptException, UtopiaException { for(int i = 0;i < commands.length;i++) { if(uscript[i]) { List<String> uscript_array = new ArrayList<String>(); try { Pattern regex = Pattern.compile("(?:\\\\.|[^;\\\\]++)*"); Matcher regexMatcher = regex.matcher(commands[i]); while (regexMatcher.find()) { uscript_array.add(regexMatcher.group()); } } catch(Exception e) { } for(int j = 0;j < uscript_array.size();j++) { if(!utopiaCommand(uscript_array.get(j).trim())) { return; } } } else { js_engine.eval(commands[i]); } } } private void updateScore() throws ScriptException { Double score = (Double) js_engine.eval("UtopiaScore;");//js_binding.get("UtopiaScore"); try { System.out.printf("%.0f\n", Double.parseDouble(score.toString())); } catch(Exception e) { throw new GameEndException("FATAL ERROR: Unable to parse the UtopiaScore variable from JavaScript as a number. Value: `" + score + "`"); } } private boolean utopiaCommand(String command) throws UtopiaException { String arr[] = command.trim().split("[ ]+", 2); String function = arr[0].toLowerCase().trim(); String args = (arr.length > 1 ? arr[1] : ""); switch(function) { case "requireitem": return usRequireItem(args); case "additem": return usAddItem(args); case "takeitem": return usTakeItem(args); case "roomstate": return usRoomstate(args); case "go": return usGo(args); case "goto": return usGoto(args); case "loadgame": return usLoadGame(args); case "pause": return usPause(args); case "print": return usPrint(args); case "println": return usPrintln(args); case "description": return usDescription(args); case "score": return usScore(args); case "quitgame": return usQuitGame(args); case "inventory": return usInventory(args); default: throw new UtopiaException(function + ": Command not found."); } } public boolean usRequireItem(String args) { return true; } public boolean usAddItem(String args) { return true; } public boolean usTakeItem(String args) { return true; } public boolean usRoomstate(String args) { return true; } public boolean usGo(String args) { // TODO: Make the player move. return usDescription(""); } public boolean usGoto(String args) { // TODO: Make the player move. return usDescription(""); } public boolean usLoadGame(String args) { buildGameFromFile(args); return true; } public boolean usPause(String args) { pause(args); return true; } // All system output will be done through these two functions. Thus, it will be easy to change them if need be. private boolean usPrint(String args) { System.out.print(args.replace("\\;", ";")); return true; } private boolean usPrintln(String args) { System.out.println(args.replace("\\;", ";")); return true; } private boolean usDescription(String args) { boolean longDesc = true; if(args.equalsIgnoreCase("short")) { longDesc = false; } return usPrintln(this._rooms[this._x][this._y].description(longDesc)); } private boolean usScore(String args) { return true; } private boolean usQuitGame(String args) { return true; } private boolean usInventory(String args) { for(int i = 0;i < this._itemnames.length; i++) { if(this._itemquantities[i] > 0) { usPrintln(String.format("%-50sx%s", this._itemnames[i], this._itemquantities[i])); } } return usPrintln(""); } public boolean stringIn(String needle, String haystack[], boolean caseSensitive) { for(int i = 0;i < haystack.length;i++) { if(caseSensitive) { if(needle.equals(haystack[i])) return true; } else { if(needle.equalsIgnoreCase(haystack[i])) return true; } } return false; } }
package org.rakam.util; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import org.apache.avro.Schema; import org.apache.avro.generic.FilteredRecordWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.QuoteMode; import org.glassfish.jersey.internal.util.Base64; import org.rakam.collection.FieldType; import org.rakam.collection.SchemaField; import org.rakam.report.QueryResult; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class ExportUtil { public static byte[] exportAsCSV(QueryResult result) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final CSVPrinter csvPrinter; try { final CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC); csvPrinter = new CSVPrinter(new PrintWriter(out), format); csvPrinter.printRecord(result.getMetadata().stream().map(SchemaField::getName) .collect(Collectors.toList())); csvPrinter.printRecords(Iterables.transform(result.getResult(), input -> Iterables.transform(input, input1 -> { if(input1 instanceof List || input1 instanceof Map) { return JsonHelper.encode(input1); } if(input1 instanceof byte[]) { return Base64.encode((byte[]) input1); } return input1; }))); csvPrinter.flush(); } catch (IOException e) { throw Throwables.propagate(e); } return out.toByteArray(); } public static byte[] exportAsAvro(QueryResult result) { Schema avroSchema = AvroUtil.convertAvroSchema(result.getMetadata()); ByteArrayOutputStream out = new ByteArrayOutputStream(); DatumWriter writer = new FilteredRecordWriter(avroSchema, GenericData.get()); BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(out, null); GenericData.Record record = new GenericData.Record(avroSchema); for (List<Object> row : result.getResult()) { List<SchemaField> metadata = result.getMetadata(); for (int i = 0; i < row.size(); i++) { record.put(i, getAvroValue(row.get(i), metadata.get(i).getType())); } try { writer.write(record, encoder); } catch (Exception e) { throw new RuntimeException("Couldn't serialize event", e); } } return out.toByteArray(); } private static Object getAvroValue(Object value, FieldType type) { if(value == null) { return null; } switch (type) { case STRING: return (String) value; case INTEGER: return value instanceof Integer ? value : ((Number) value).intValue(); case LONG: return value instanceof Long ? value : ((Number) value).longValue(); case BOOLEAN: return (Boolean) value; case DOUBLE: return value instanceof Double ? value : ((Number) value).doubleValue(); case DATE: return ((LocalDate) value).toEpochDay(); case TIMESTAMP: return ((Instant) value).toEpochMilli(); case TIME: return ((LocalTime) value).toSecondOfDay(); case BINARY: return (byte[]) value; default: if(type.isArray()) { return ((List) value).stream().map(e -> getAvroValue(e, type.getArrayElementType())) .collect(Collectors.toList()); } if(type.isMap()) { return ((Map) value).entrySet().stream() .collect(Collectors.toMap(new Function<Map.Entry, String>() { @Override public String apply(Map.Entry entry) { return (String) entry.getKey(); } }, e -> getAvroValue(e, type.getMapValueType()))); } throw new IllegalStateException("unsupported type"); } } }
package net.kencochrane.raven; import net.kencochrane.raven.exception.InvalidDsnException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.NoInitialContextException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Data Source name allowing a direct connection to a Sentry server. */ public class Dsn { /** * Name of the environment or system variable containing the DSN. */ public static final String DSN_VARIABLE = "SENTRY_DSN"; /** * Option specific to raven-java, allowing to disable the compression of requests to the Sentry Server. */ public static final String NOCOMPRESSION_OPTION = "raven.nocompression"; /** * Option specific to raven-java, allowing to set a timeout (in ms) for a request to the Sentry server. */ public static final String TIMEOUT_OPTION = "raven.timeout"; /** * Option to send events asynchronously. */ public static final String ASYNC_OPTION = "raven.async"; /** * Option to set the charset for strings sent to sentry. */ public static final String CHARSET_OPTION = "raven.charset"; /** * Protocol setting to disable security checks over an SSL connection. */ public static final String NAIVE_PROTOCOL = "naive"; private static final Logger logger = Logger.getLogger(Raven.class.getCanonicalName()); private String secretKey; private String publicKey; private String projectId; private String protocol; private String host; private int port; private String path; private Set<String> protocolSettings; private Map<String, String> options; private URI uri; /** * Creates a DSN based on the {@link #dsnLookup()} result. */ public Dsn() { this(dsnLookup()); } /** * Creates a DSN based on a String. * * @param dsn dsn in a string form. * @throws InvalidDsnException the given DSN isn't usable. */ public Dsn(String dsn) { if (dsn == null) throw new InvalidDsnException("The sentry DSN must be provided and not be null"); options = new HashMap<String, String>(); protocolSettings = new HashSet<String>(); URI dsnUri = URI.create(dsn); extractProtocolInfo(dsnUri); extractUserKeys(dsnUri); extractHostInfo(dsnUri); extractPathInfo(dsnUri); extractOptions(dsnUri); makeOptionsImmutable(); validate(); try { uri = new URI(protocol, null, host, port, path, null, null); } catch (URISyntaxException e) { throw new InvalidDsnException("Impossible to determine Sentry's URI from the DSN '" + dsn + "'", e); } } /** * Looks for a DSN configuration within JNDI, the System environment or Java properties. * * @return a DSN configuration or null if nothing could be found. */ public static String dsnLookup() { String dsn = null; // Try to obtain the DSN from JNDI try { Context c = new InitialContext(); dsn = (String) c.lookup("java:comp/env/sentry/dsn"); } catch (NoInitialContextException e) { logger.log(Level.INFO, "JNDI not configured for sentry (NoInitialContextEx)"); } catch (NamingException e) { logger.log(Level.INFO, "No /sentry/dsn in JNDI"); } catch (RuntimeException ex) { logger.log(Level.INFO, "Odd RuntimeException while testing for JNDI: " + ex.getMessage()); } // Try to obtain the DSN from a System Environment Variable if (dsn == null) dsn = System.getenv(Dsn.DSN_VARIABLE); // Try to obtain the DSN from a Java System Property if (dsn == null) dsn = System.getProperty(Dsn.DSN_VARIABLE); return dsn; } /** * Extracts the path and the project ID from the DSN provided as an {@code URI}. * * @param dsnUri DSN as an URI. */ private void extractPathInfo(URI dsnUri) { String uriPath = dsnUri.getPath(); if (uriPath == null) return; int projectIdStart = uriPath.lastIndexOf("/") + 1; path = uriPath.substring(0, projectIdStart); projectId = uriPath.substring(projectIdStart); } /** * Extracts the hostname and port of the Sentry server from the DSN provided as an {@code URI}. * * @param dsnUri DSN as an URI. */ private void extractHostInfo(URI dsnUri) { host = dsnUri.getHost(); port = dsnUri.getPort(); } /** * Extracts the scheme and additional protocol options from the DSN provided as an {@code URI}. * * @param dsnUri DSN as an URI. */ private void extractProtocolInfo(URI dsnUri) { String scheme = dsnUri.getScheme(); if (scheme == null) return; String[] schemeDetails = scheme.split("\\+"); protocolSettings.addAll(Arrays.asList(schemeDetails).subList(0, schemeDetails.length - 1)); protocol = schemeDetails[schemeDetails.length - 1]; } /** * Extracts the public and secret keys from the DSN provided as an {@code URI}. * * @param dsnUri DSN as an URI. */ private void extractUserKeys(URI dsnUri) { String userInfo = dsnUri.getUserInfo(); if (userInfo == null) return; String[] userDetails = userInfo.split(":"); publicKey = userDetails[0]; if (userDetails.length > 1) secretKey = userDetails[1]; } /** * Extracts the DSN options from the DSN provided as an {@code URI}. * * @param dsnUri DSN as an URI. */ private void extractOptions(URI dsnUri) { String query = dsnUri.getQuery(); if (query == null) return; String[] optionPairs = query.split("&"); for (String optionPair : optionPairs) { String[] pairDetails = optionPair.split("="); options.put(pairDetails[0], (pairDetails.length > 1) ? pairDetails[1] : ""); } } /** * Makes protocol and dsn options immutable to allow an external usage. */ private void makeOptionsImmutable() { // Make the options immutable options = Collections.unmodifiableMap(options); protocolSettings = Collections.unmodifiableSet(protocolSettings); } /** * Validates internally the DSN, and check for mandatory elements. * <p> * Mandatory elements are the {@link #host}, {@link #publicKey}, {@link #secretKey} and {@link #projectId}. * </p> */ private void validate() { List<String> missingElements = new LinkedList<String>(); if (host == null) missingElements.add("host"); if (publicKey == null) missingElements.add("public key"); if (secretKey == null) missingElements.add("secret key"); if (projectId == null || projectId.isEmpty()) missingElements.add("project ID"); if (!missingElements.isEmpty()) throw new InvalidDsnException("Invalid DSN, the following properties aren't set '" + missingElements + "'"); } public String getSecretKey() { return secretKey; } public String getPublicKey() { return publicKey; } public String getProjectId() { return projectId; } public String getProtocol() { return protocol; } public String getHost() { return host; } public int getPort() { return port; } public String getPath() { return path; } public Set<String> getProtocolSettings() { return protocolSettings; } public Map<String, String> getOptions() { return options; } /** * Creates the URI of the sentry server. * * @return the URI of the sentry server. */ public URI getUri() { return uri; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Dsn dsn = (Dsn) o; if (port != dsn.port) return false; if (!host.equals(dsn.host)) return false; if (!options.equals(dsn.options)) return false; if (!path.equals(dsn.path)) return false; if (!projectId.equals(dsn.projectId)) return false; if (protocol != null ? !protocol.equals(dsn.protocol) : dsn.protocol != null) return false; if (!protocolSettings.equals(dsn.protocolSettings)) return false; if (!publicKey.equals(dsn.publicKey)) return false; if (!secretKey.equals(dsn.secretKey)) return false; return true; } @Override public int hashCode() { int result = publicKey.hashCode(); result = 31 * result + projectId.hashCode(); result = 31 * result + host.hashCode(); result = 31 * result + port; result = 31 * result + path.hashCode(); return result; } @Override public String toString() { return getUri().toString(); } }
package gx.realtime; import gx.util.RandomUtils; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * Data model for the document. Contains an object graph that can be referenced * via the root node. */ public class Model extends EventTarget { private Document document; private boolean initialized; private boolean readOnly; private CollaborativeMap<CollaborativeObject> root; private LinkedList<BaseModelEvent> undoableMutations; private LinkedList<BaseModelEvent> redoableMutations; /** * Keep track of all the nodes in the data model, indexed * by their ID. */ private Map<String, Object> nodes = new HashMap<>(); /** * Constructor. Should not be called directly, a model can be * retrieved via the document. * @param document */ protected Model(Document document) { this.document = document; initialized = false; readOnly = false; root = new CollaborativeMap<CollaborativeObject>("root", this); undoableMutations = new LinkedList<BaseModelEvent>(); redoableMutations = new LinkedList<BaseModelEvent>(); } public void beginCompoundOperation(String opt_name){ //TODO: make sure that changes that occur are sent in the same batch to the browser channel } public void beginCompoundOperation(){ //TODO: make sure that changes that occur are sent in the same batch to the browser channel } public <T extends CollaborativeObject> T create(Class<T> collabType) { return create(RandomUtils.getRandomAlphaNumeric(), collabType); } private <T extends CollaborativeObject> T create(String id, Class<T> collabType) { T collabObj; try { collabObj = collabType.getConstructor(String.class, Model.class).newInstance(id, this); } catch (InstantiationException e) { e.printStackTrace(); return null; } catch (IllegalAccessException e) { e.printStackTrace(); return null; } catch (NoSuchMethodException e) { e.printStackTrace(); return null; } catch (InvocationTargetException e) { e.printStackTrace(); return null; } return collabObj; } public <E> CollaborativeList<E> createList(){ return new CollaborativeList<E>(RandomUtils.getRandomAlphaNumeric(), this); } public <E> CollaborativeList<E> createList(E[] opt_initialValue){ CollaborativeList<E> result = createList(); result.pushAll(opt_initialValue); return result; } public <E> CollaborativeMap<E> createMap(){ return new CollaborativeMap<E>(RandomUtils.getRandomAlphaNumeric(), this); } public <E> CollaborativeMap<E> createMap(Map<String, E> opt_initialValue){ CollaborativeMap<E> result = createMap(); Set<Entry<String, E>> entries = opt_initialValue.entrySet(); for(Entry<String, E> entry : entries){ result.set(entry.getKey(), entry.getValue()); } return result; } public CollaborativeString createString(){ return new CollaborativeString(RandomUtils.getRandomAlphaNumeric(), this); } public CollaborativeString createString(String opt_initialValue){ CollaborativeString result = createString(); result.setText(opt_initialValue); return result; } public void endCompoundOperation(){ //TODO } public CollaborativeMap<CollaborativeObject> getRoot(){ //TODO: make sure that the documents in this root element are updated return root; } public boolean isInitialized(){ return initialized; } //TODO: maybe make this public in order to call it from the node that was actually mutated? private void registerMutation(BaseModelEvent e){ undoableMutations.push(e); } public void redo(){ //TODO: redo last action of redoableMutation stack. } public void undo(){ //TODO: undo last action of undoableMutation stack. } private BaseModelEvent constructRevertEvent(BaseModelEvent event){ BaseModelEvent result = null; switch (event.getType()) { case TEXT_INSERTED: TextInsertedEvent tiEvent = (TextInsertedEvent) event; result = new TextDeletedEvent((CollaborativeString) tiEvent.getTarget(), tiEvent.getSessionId(), tiEvent.getUserId(), tiEvent.isLocal(), tiEvent.getIndex(), tiEvent.getText()); break; case TEXT_DELETED: //TEXT_INSERTED TextDeletedEvent tdEvent = (TextDeletedEvent) event; result = new TextInsertedEvent((CollaborativeString) tdEvent.getTarget(), tdEvent.getSessionId(), tdEvent.getUserId(), tdEvent.isLocal(), tdEvent.getIndex(), tdEvent.getText()); break; case COLLABORATOR_JOINED: //COLLABORATOR_LEFT break; case COLLABORATOR_LEFT: //COLLABORATOR_JOINED break; case DOCUMENT_SAVE_STATE_CHANGED: //DOCUMENT_SAVE_STATE_CHANGED? break; case OBJECT_ADDED: //OBJECT_CHANGED? break; case OBJECT_CHANGED: //OBJECT_CHANGED break; case REFERENCE_SHIFTED: //REFERENCE_SHIFTED? break; case VALUES_ADDED: //VALUES_REMOVED break; case VALUES_REMOVED: //VALUES_ADDED break; case VALUES_SET: //VALUE_SET? break; case VALUE_CHANGED: //VALUE_CHANGED? break; } return result; } public boolean canRedo(){ return redoableMutations.size() > 0; } public boolean canUndo(){ return undoableMutations.size() > 0; } public boolean isReadOnly(){ return readOnly; } private EventHandler<ObjectAddedEvent> getObjectAddedBuilder() { return (event) -> { //TODO: need to retrieve the class of the object to create somehow (currently limit to CollaborativeMap) CollaborativeObject collabObject = create(event.getTargetId(), CollaborativeMap.class); nodes.put(event.getTargetId(), collabObject); System.out.println("OBJECT_ADDED: " + event.getTargetId()); }; } private EventHandler<ValuesAddedEvent> getValuesAddedBuilder() { return (event) -> { System.out.println("VALUES_ADDED"); }; } private EventHandler<ValueChangedEvent> getValueChangedBuilder() { return (event) -> { System.out.println("VALUE_CHANGED"); }; } private EventHandler<ValuesSetEvent> getValuesSetBuilder() { return (event) -> { System.out.println("VALUES_SET"); }; } private EventHandler<ValuesRemovedEvent> getValuesRemovedBuilder() { return (event) -> { System.out.println("VALUES_REMOVED"); }; } /** * Build our local data model based on the given remote event. * @param event */ private void buildLocalModel(BaseModelEvent event) { switch (event.getType()) { case OBJECT_ADDED: getObjectAddedBuilder().handleEvent((ObjectAddedEvent)event); break; case VALUES_ADDED: getValuesAddedBuilder().handleEvent((ValuesAddedEvent)event); break; case VALUE_CHANGED: getValueChangedBuilder().handleEvent((ValueChangedEvent)event); break; case VALUES_SET: getValuesSetBuilder().handleEvent((ValuesSetEvent)event); break; case VALUES_REMOVED: getValuesRemovedBuilder().handleEvent((ValuesRemovedEvent)event); break; } } public void handleRemoteEvent(BaseModelEvent event) { //TODO: registerMutation. Only if event has actually changed an object? //TODO: clear redoable stack? //TODO: fire UndoRedoStateChangedEvent when canRedo or canUndo state changes. // https://developers.google.com/drive/realtime/handle-events#undo_and_redo_state_events buildLocalModel(event); String targetId = event.getTargetId(); Object node = getNode(targetId); if (node == null) { // Unknown target ID, so ignore //TODO: logging return; } if (!(node instanceof EventTarget)) { // Not an event target, so ignore return; } EventTarget targetNode = (EventTarget)node; // Currently, the event may just contain the target ID (because it need // not have exited in our local model yet), so set it event.setTarget(targetNode); targetNode.fireEvent(event); } protected Document getDocument() { return document; } private Object getNode(String id) { return nodes.get(id); } }
package net.dlogic.kryonet.server.event.handler; import java.util.Iterator; import net.dlogic.kryonet.common.entity.Room; import net.dlogic.kryonet.common.entity.User; import net.dlogic.kryonet.common.manager.RoomManagerInstance; import net.dlogic.kryonet.common.response.ErrorResponse; import net.dlogic.kryonet.common.response.GetRoomsResponse; import net.dlogic.kryonet.common.response.JoinRoomFailureResponse; import net.dlogic.kryonet.common.response.JoinRoomSuccessResponse; import net.dlogic.kryonet.common.response.LeaveRoomResponse; import net.dlogic.kryonet.common.response.LoginFailureResponse; import net.dlogic.kryonet.common.response.LoginSuccessResponse; import net.dlogic.kryonet.common.response.LogoutResponse; import net.dlogic.kryonet.common.response.PrivateMessageResponse; import net.dlogic.kryonet.common.response.PublicMessageResponse; import net.dlogic.kryonet.server.KryonetServerException; import net.dlogic.kryonet.server.KryonetServerInstance; import com.esotericsoftware.kryonet.Server; import com.esotericsoftware.minlog.Log; public abstract class BaseEventHandler { public Server endpoint; public User sender; public BaseEventHandler() { try { endpoint = KryonetServerInstance.getInstance().endpoint; } catch (KryonetServerException e) { e.printStackTrace(); } } public void sendErrorResponse(String errorMessage) { ErrorResponse response = new ErrorResponse(); response.errorMessage = errorMessage; endpoint.sendToTCP(sender.id, response); } public void sendGetRoomsResponse(Room[] rooms) { GetRoomsResponse response = new GetRoomsResponse(); response.rooms = rooms; endpoint.sendToTCP(sender.id, response); } public void sendJoinRoomSuccessResponse(User joinedUser, Room joinedRoom) { Iterator<User> it = joinedRoom.users.values().iterator(); while (it.hasNext()) { JoinRoomSuccessResponse response = new JoinRoomSuccessResponse(); response.userJoined = joinedUser; response.roomJoined = joinedRoom; endpoint.sendToTCP(it.next().id, response); } } public void sendJoinRoomFailureResponse(String errorMessage) { JoinRoomFailureResponse response = new JoinRoomFailureResponse(); response.errorMessage = errorMessage; endpoint.sendToTCP(sender.id, response); } public void sendLeaveRoomResponse() { Iterator<Room> it = RoomManagerInstance.manager.map.values().iterator(); while (it.hasNext()) { Room room = it.next(); if (room.users.containsKey(sender.id)) { sendLeaveRoomResponse(room); } } } public void sendLeaveRoomResponse(Room roomToLeave) { Iterator<User> it = roomToLeave.users.values().iterator(); while (it.hasNext()) { LeaveRoomResponse response = new LeaveRoomResponse(); response.userLeft = sender; response.roomLeft = roomToLeave; endpoint.sendToTCP(it.next().id, response); } LeaveRoomResponse response = new LeaveRoomResponse(); response.userLeft = sender; response.roomLeft = roomToLeave; endpoint.sendToTCP(sender.id, response); } public final void sendLoginSuccessResponse() { Log.info("BaseEventHandler.sendLoginSuccessResponse()"); LoginSuccessResponse response = new LoginSuccessResponse(); response.myself = sender; endpoint.sendToTCP(sender.id, response); } public final void sendLoginFailureResponse(String errorMessage) { LoginFailureResponse response = new LoginFailureResponse(); response.errorMessage = errorMessage; endpoint.sendToTCP(sender.id, response); } public void sendLogoutResponse() { LogoutResponse response = new LogoutResponse(); endpoint.sendToTCP(sender.id, response); } public void sendPrivateMessageResponse(User targetUser, String message) { PrivateMessageResponse response = new PrivateMessageResponse(); response.sender = sender; response.message = message; endpoint.sendToTCP(targetUser.id, response); } public void sendPublicMessageResponse(Room targetRoom, String message) { Iterator<User> it = targetRoom.users.values().iterator(); while (it.hasNext()) { PublicMessageResponse response = new PublicMessageResponse(); response.sender = sender; response.message = message; User user = it.next(); if (sender.id != user.id) { endpoint.sendToTCP(user.id, response); } } } }
package net.littlebigisland.droidibus.activity; /** * Base Dashboard Fragment - Controls base functions * and drops in the child fragments * @author Ted <tass2001@gmail.com> * @package net.littlebigisland.droidibus.activity */ import net.littlebigisland.droidibus.R; import net.littlebigisland.droidibus.ibus.IBusCallbackReceiver; import net.littlebigisland.droidibus.ibus.IBusCommandsEnum; import net.littlebigisland.droidibus.ibus.IBusMessageService; import android.app.FragmentTransaction; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; public class DashboardFragment extends BaseFragment{ protected Handler mHandler = new Handler(); protected SharedPreferences mSettings = null; protected PowerManager mPowerManager = null; protected WakeLock mScreenWakeLock; protected boolean mScreenOn = false; protected boolean mPopulatedFragments = false; private IBusCallbackReceiver mIBusCallbacks = new IBusCallbackReceiver(){ /** Callback to handle Ignition State Updates * @param int State of Ignition (0, 1, 2) */ @Override public void onUpdateIgnitionSate(final int state){ boolean carState = (state > 0) ? true : false; changeScreenState(carState); } }; // Service connection class for IBus private IBusServiceConnection mIBusConnection = new IBusServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service){ super.onServiceConnected(name, service); registerIBusCallback(mIBusCallbacks, mHandler); // Emulate BoardMonitor Bootup on connect Log.d(TAG, CTAG + "BoardMonitor Bootup Performed"); sendIBusCommand(IBusCommandsEnum.BMToIKEGetIgnitionStatus); sendIBusCommand(IBusCommandsEnum.BMToLCMGetDimmerStatus); sendIBusCommand(IBusCommandsEnum.BMToGMGetDoorStatus); } }; /** * Acquire a screen wake lock to either turn the screen on or off * @param screenState if true, turn the screen on, else turn it off */ @SuppressWarnings("deprecation") private void changeScreenState(boolean screenState){ if(mPowerManager == null){ mPowerManager = (PowerManager) getActivity( ).getSystemService(Context.POWER_SERVICE); } boolean modeChange = false; Window window = getActivity().getWindow(); WindowManager.LayoutParams layoutP = window.getAttributes(); if(screenState && !mScreenOn){ Log.d(TAG, CTAG + "Acquiring WakeLock"); modeChange = true; mScreenOn = true; layoutP.screenBrightness = -1; mScreenWakeLock = mPowerManager.newWakeLock( PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "screenWakeLock" ); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); mScreenWakeLock.acquire(); } if(!screenState && mScreenOn){ Log.d(TAG, CTAG + "Shutting the screen off"); modeChange = true; mScreenOn = false; layoutP.screenBrightness = 0; releaseWakelock(); } if(modeChange){ window.setAttributes(layoutP); } } private void releaseWakelock(){ if(mScreenWakeLock != null){ if(mScreenWakeLock.isHeld()){ Log.d(TAG, CTAG + "Releasing system wakelock"); mScreenWakeLock.release(); } } } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ){ final View v = inflater.inflate(R.layout.dashboard, container, false); Log.d(TAG, CTAG + "onCreateView()"); if(!mPopulatedFragments){ FragmentTransaction tx = getChildFragmentManager( ).beginTransaction(); tx.add(R.id.music_fragment, new DashboardMusicFragment()); tx.add(R.id.stats_fragment, new DashboardStatsFragment()); tx.commit(); mPopulatedFragments = true; } // Keep a wake lock changeScreenState(true); return v; } @Override public void onActivityCreated (Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); CTAG = "DashboardFragment: "; Log.d(TAG, CTAG + "onActivityCreated()"); // Bind required background services last since the callback // functions depend on the view items being initialized if(!mIBusConnected){ serviceStarter(IBusMessageService.class, mIBusConnection); } } @Override public void onPause(){ super.onPause(); Log.d(TAG, CTAG + "onPause()"); releaseWakelock(); } @Override public void onResume(){ super.onResume(); Log.d(TAG, CTAG + "onResume()"); // Keep a wake lock changeScreenState(true); } @Override public void onDestroy(){ super.onDestroy(); Log.d(TAG, CTAG + "onDestroy()"); releaseWakelock(); if(mIBusConnected){ mIBusService.unregisterCallback(mIBusCallbacks); serviceStopper(IBusMessageService.class, mIBusConnection); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.maizegenetics.gbs.pipeline; import java.awt.Frame; import java.io.BufferedWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.ImageIcon; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.pal.alignment.AlignmentUtils; import net.maizegenetics.pal.alignment.BitAlignment; import net.maizegenetics.pal.alignment.BitAlignmentHDF5; import net.maizegenetics.pal.alignment.ExportUtils; import net.maizegenetics.pal.alignment.FilterAlignment; import net.maizegenetics.pal.alignment.GeneticMap; import net.maizegenetics.pal.alignment.ImportUtils; import net.maizegenetics.pal.alignment.Locus; import net.maizegenetics.pal.alignment.MutableNucleotideAlignment; import net.maizegenetics.pal.alignment.MutableNucleotideAlignmentHDF5; import net.maizegenetics.pal.alignment.NucleotideAlignmentConstants; import net.maizegenetics.pal.distance.IBSDistanceMatrix; import net.maizegenetics.pal.ids.IdGroup; import net.maizegenetics.pal.ids.Identifier; import net.maizegenetics.pal.ids.SimpleIdGroup; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.util.ArgsEngine; import net.maizegenetics.util.BitSet; import net.maizegenetics.util.BitUtil; import net.maizegenetics.util.ExceptionUtils; import net.maizegenetics.util.OpenBitSet; import net.maizegenetics.util.ProgressListener; import net.maizegenetics.util.Utils; import org.apache.log4j.Logger; /** * Creates haplotypes by finding large IBS regions within GBS data. Starts with the * highest coverage taxa and looks within windows of near perfect matches. Combines * all matches together into one haplotype. The haplotype is named for the highest coverage * sample. * * TODO: * 1. plus add short inbred segments not present full ones * 2. Cluster and choose haplotypes by cluster and number of new minor alleles (or information) * 3. Set max het frequency as a setting * * @author edbuckler */ public class FindMergeHaplotypesPlugin extends AbstractPlugin { private int startChr, endChr; private String hmpFile; private String outFileBase; private String errFile=null; private double minJointGapProb=0.01; private boolean callGaps=false; private double maxDistFromFounder=0.01; private int appoxSitesPerHaplotype=8192; private int minSitesPresentPerHap=500; private double maximumMissing=0.4; private int maxHaplotypes=100; private int minSitesForSectionComp=50; private double maxHetFreq=0.01; private double maxErrorInCreatingConsensus=0.05; private int minTaxaInGroup=2; private double[] propMissing; private int[] siteErrors, siteCallCnt; private BitSet badMask=null; private static ArgsEngine engine = new ArgsEngine(); private static final Logger myLogger = Logger.getLogger(MinorWindowViterbiImputationPlugin.class); public FindMergeHaplotypesPlugin() { super(null, false); } public FindMergeHaplotypesPlugin(Frame parentFrame) { super(parentFrame, false); } /** * Produces donor haplotypes that can be used for imputation. * @param inFile Input DNA sequence alignment file name in either HapMap or HDF5 * @param exportFile * @param errorExportFile * @param maxDistance maximum distance between founder haplotype and other haplotype * @param minSites * @param appoxSitesPerHaplotype */ public void runFindMergeHaplotypes(String inFile, String exportFile, String errorExportFile, double maxDistance, int minSites, int appoxSitesPerHaplotype) { Alignment baseAlign=null; System.out.println("Reading: "+inFile); if(inFile.contains(".h5")) { if(MutableNucleotideAlignmentHDF5.isMutableNucleotideAlignmentHDF5(inFile)) { baseAlign=MutableNucleotideAlignmentHDF5.getInstance(inFile);} else { baseAlign=BitAlignmentHDF5.getInstance(inFile); } } else { baseAlign=ImportUtils.readFromHapmap(inFile, false, (ProgressListener)null); } int[][] divisions=divideChromosome(baseAlign, appoxSitesPerHaplotype); System.out.printf("In taxa:%d sites:%d %n",baseAlign.getSequenceCount(),baseAlign.getSiteCount()); siteErrors=new int[baseAlign.getSiteCount()]; siteCallCnt=new int[baseAlign.getSiteCount()]; for (int i = 0; i < divisions.length; i++) { MutableNucleotideAlignment mna=createHaplotypeAlignment(divisions[i][0], divisions[i][1], baseAlign, minSites, maxDistance); String newExport=exportFile.replace("sX.hmp", "s"+i+".hmp"); newExport=newExport.replace("gX", "gc"+mna.getLocusName(0)+"s"+i); ExportUtils.writeToHapmap(mna, false, newExport, '\t', null); if(errorExportFile!=null) exportBadSites(baseAlign, errorExportFile, 0.01); } } private MutableNucleotideAlignment createHaplotypeAlignment(int startSite, int endSite, Alignment baseAlign, int minSites, double maxDistance) { Alignment fa=FilterAlignment.getInstance(baseAlign, startSite, endSite); Alignment inAlign=BitAlignment.getInstance(fa, false); //load for Taxa inAlign.optimizeForTaxa(null); int sites=inAlign.getSiteCount(); System.out.printf("SubInAlign Locus:%s StartPos:%d taxa:%d sites:%d %n",inAlign.getLocus(0), inAlign.getPositionInLocus(0),inAlign.getSequenceCount(),inAlign.getSiteCount()); propMissing=new double[inAlign.getSequenceCount()]; int startBlock=0; int endBlock=inAlign.getAllelePresenceForAllSites(0, 0).getNumWords(); TreeMap<Integer,Integer> presentRanking=createPresentRankingForWindow(inAlign, startBlock, endBlock, minSites, maxHetFreq); System.out.printf("Block %d Inbred and modest coverage:%d %n",startBlock,presentRanking.size()); System.out.printf("Current Site %d Current block %d EndBlock: %d %n",startSite, startBlock, endBlock); TreeMap<Integer,byte[][]> results=mergeWithinWindow(inAlign, presentRanking, startBlock, endBlock, maxDistance, startSite); MutableNucleotideAlignment mna=createEmptyHaplotypeAlignment(inAlign, results.size()); int index=0; for (byte[][] calls : results.values()) { mna.setBaseRange(index, 0, calls[0]); mna.setTaxonName(index, new Identifier("h"+index+(new String(calls[1])))); index++; } mna.clean(); return mna; } private int[][] divideChromosome(Alignment a, int appoxSitesPerHaplotype) { Locus[] theL=a.getLoci(); ArrayList<int[]> allDivisions=new ArrayList<int[]>(); for (Locus aL: theL) { System.out.println(""); int locusSites=aL.getEnd()-aL.getStart()+1; int subAlignCnt=(int)Math.round((double)locusSites/(double)appoxSitesPerHaplotype); if(subAlignCnt==0) subAlignCnt++; int prefBlocks=(locusSites/(subAlignCnt*64)); System.out.printf("Chr:%s Alignment Sites:%d subAlignCnt:%d RealSites:%d %n", aL.getChromosomeName(),locusSites, subAlignCnt, prefBlocks*64); for (int i = 0; i < subAlignCnt; i++) { int[] divs=new int[2]; divs[0]=(i*prefBlocks*64)+aL.getStart(); divs[1]=divs[0]+(prefBlocks*64)-1; if(i==subAlignCnt-1) divs[1]=aL.getEnd(); allDivisions.add(divs); } } int[][] result=new int[allDivisions.size()][2]; for (int i = 0; i < result.length; i++) { result[i]=allDivisions.get(i); System.out.printf("Chromosome Divisions: %s start:%d end:%d %n", a.getLocus(result[i][0]).getName(), result[i][0], result[i][1]); } return result; } private TreeMap<Integer,Integer> createPresentRankingForWindow(Alignment inAlign, int startBlock, int endBlock, int minSites, double maxHetFreq) { int sites=64*(endBlock-startBlock+1); TreeMap<Integer,Integer> presentRanking=new TreeMap<Integer,Integer>(Collections.reverseOrder()); for (int i = 0; i < inAlign.getSequenceCount(); i++) { long[] mj=inAlign.getAllelePresenceForSitesBlock(i, 0, startBlock, endBlock); long[] mn=inAlign.getAllelePresenceForSitesBlock(i, 1, startBlock, endBlock); int totalSitesNotMissing = 0; int hetCnt=0; for (int j = 0; j < mj.length; j++) { totalSitesNotMissing+=BitUtil.pop(mj[j]|mn[j]); hetCnt+=BitUtil.pop(mj[j]&mn[j]); } double hetFreq=(double)hetCnt/(double)totalSitesNotMissing; propMissing[i]=(double)(1+sites-totalSitesNotMissing)/(double)sites; //1 prevents error in joint missing calculations double propPresent=1.0-propMissing[i]; if((hetFreq>maxHetFreq)||(totalSitesNotMissing<minSites)) continue; int index=(1000000*((int)(propPresent*100)))+i; // System.out.println(index); presentRanking.put(index, i); } return presentRanking; } private MutableNucleotideAlignment createEmptyHaplotypeAlignment(Alignment inAlign, int maxHaplotypes) { IdGroup outIDG=new SimpleIdGroup(maxHaplotypes); for (int i = 0; i < maxHaplotypes; i++) { outIDG.setIdentifier(i, new Identifier("Hap"+i)); } MutableNucleotideAlignment mna=MutableNucleotideAlignment.getInstance(outIDG, inAlign.getSiteCount()); for (int i = 0; i < inAlign.getSiteCount(); i++) { mna.addSite(i); mna.setLocusOfSite(i, inAlign.getLocus(i)); mna.setPositionOfSite(i, inAlign.getPositionInLocus(i)); } return mna; } private BitSet maskBadSites(GeneticMap gm, Alignment a) { OpenBitSet obs=new OpenBitSet(a.getSiteCount()); int count=0; for (int i = 0; i < gm.getNumberOfMarkers(); i++) { int site=a.getSiteOfPhysicalPosition(gm.getPhysicalPosition(i), null); if(site>0) {obs.set(site);} } System.out.println("Bad Sites matched:"+obs.cardinality()); obs.not(); //change all bad sites to 0, good to 1 return obs; } private void exportBadSites(Alignment baseAlign, String exportMap, double errorThreshold) { BufferedWriter bw = null; try { String fullFileName = Utils.addSuffixIfNeeded(exportMap, ".txt", new String[]{".txt"}); bw = Utils.getBufferedWriter(fullFileName); bw.write("<Map>\n"); for (int i = 0; i < baseAlign.getSiteCount(); i++) { double errorsRate=(double)siteErrors[i]/(double)siteCallCnt[i]; if(errorsRate<errorThreshold) continue; bw.write(baseAlign.getSNPID(i)+"\t"); bw.write(baseAlign.getLocusName(i) +"\t"); bw.write(i+"\t"); //dummy for genetic position bw.write(baseAlign.getPositionInLocus(i) +"\n"); //dummy for genetic position } bw.close(); } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("Error writing GeneticMap file: " + exportMap + ": " + ExceptionUtils.getExceptionCauses(e)); } } private TreeMap<Integer,byte[][]> mergeWithinWindow(Alignment inAlign, TreeMap<Integer,Integer> presentRanking, int startBlock, int endBlock, double maxDistance, int siteOffsetForError){ int startSite=startBlock*64; int endSite=63+(endBlock*64); if(endSite>=inAlign.getSiteCount()) endSite=inAlign.getSiteCount()-1; TreeMap<Integer,ArrayList> mergeSets=new TreeMap<Integer,ArrayList>(); TreeMap<Integer,byte[][]> results=new TreeMap<Integer,byte[][]>(Collections.reverseOrder()); TreeSet<Integer> unmatched=new TreeSet<Integer>(presentRanking.values()); IdGroup inIDG=inAlign.getIdGroup(); for (Entry<Integer,Integer> e : presentRanking.entrySet()) { int taxon1=e.getValue(); if(unmatched.contains(taxon1)==false) continue;//already included in another group ArrayList<Integer> hits=new ArrayList<Integer>(); unmatched.remove(taxon1); for(int taxon2 : unmatched) { double[] dist=IBSDistanceMatrix.computeHetBitDistances(inAlign, taxon1, taxon2, minSitesForSectionComp, startBlock, endBlock, badMask); if((!Double.isNaN(dist[0]))&&(dist[0]<maxDistance)) { hits.add(taxon2); } } byte[] calls=null; if(((hits.size()+1)<this.minTaxaInGroup)) continue; if(hits.size()>0) { ArrayList<String> mergeNames=new ArrayList<String>(); mergeNames.add(inIDG.getIdentifier(taxon1).getFullName()); mergeSets.put(taxon1, hits); System.out.print(inAlign.getFullTaxaName(taxon1)+"="); for (Integer taxon2 : hits) { unmatched.remove(taxon2); System.out.print(inAlign.getFullTaxaName(taxon2)+"="); mergeNames.add(inIDG.getIdentifier(taxon2).getFullName()); } System.out.println(""); calls=consensusGameteCalls(inAlign, mergeNames, startSite, endSite, maxErrorInCreatingConsensus, siteOffsetForError); } else { calls=inAlign.getBaseRange(taxon1, startSite, endSite+1); } int[] unkCnt=countUnknown(calls); double missingFreq=(double)unkCnt[0]/(double)inAlign.getSiteCount(); double hetFreq=(double)unkCnt[1]/(double)(inAlign.getSiteCount()-unkCnt[0]); if(((missingFreq<maximumMissing)&&(hetFreq<maxHetFreq))) { int index=(hits.size()*200000)+taxon1; System.out.printf("Output %s plus %d missingF:%g hetF:%g index: %d %n",inIDG.getIdentifier(taxon1).getFullName(), hits.size(), missingFreq, hetFreq, index); byte[][] callPlusNames=new byte[2][]; callPlusNames[0]=calls; String newName=inIDG.getIdentifier(taxon1).getNameLevel(0)+":d"+(hits.size()+1); callPlusNames[1]=newName.getBytes(); results.put(index, callPlusNames); } if(results.size()>=maxHaplotypes) break; } return results; } private byte[] consensusGameteCalls(Alignment a, List<String> taxa, int startSite, int endSite, double maxError, int siteOffsetForError) { int[] taxaIndex = new int[taxa.size()]; for (int t = 0; t < taxaIndex.length; t++) { //why are we working with names rather than numbers taxaIndex[t] = a.getIdGroup().whichIdNumber(taxa.get(t)); } byte[] calls = new byte[endSite-startSite+1]; Arrays.fill(calls, Alignment.UNKNOWN_DIPLOID_ALLELE); for (int s = startSite; s <= endSite; s++) { byte mjAllele = a.getMajorAllele(s); byte mnAllele = a.getMinorAllele(s); byte mj=AlignmentUtils.getUnphasedDiploidValue(mjAllele,mjAllele); byte mn=AlignmentUtils.getUnphasedDiploidValue(mnAllele,mnAllele); byte het = AlignmentUtils.getUnphasedDiploidValue(mjAllele, mnAllele); int mjCnt=0, mnCnt=0; for (int t = 0; t < taxaIndex.length; t++) { byte ob = a.getBase(taxaIndex[t], s); if (ob == Alignment.UNKNOWN_DIPLOID_ALLELE) { continue; } if (ob == mj) { mjCnt++; } else if (ob == mn) { mnCnt++; } else if (AlignmentUtils.isEqual(ob, het)) { mjCnt++; mnCnt++; } } int totalCnt = mjCnt + mnCnt; if (totalCnt == 0) { double missingProp=1.0; for (int t : taxaIndex) {missingProp*=propMissing[t];} if(callGaps&(missingProp<minJointGapProb)) calls[s-startSite]=NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE; continue; } double errorRate; if(totalCnt>1) siteCallCnt[s+siteOffsetForError]+=totalCnt; if(mjCnt < mnCnt) { errorRate=(double)mjCnt/(double)totalCnt; if(errorRate<maxError) {calls[s-startSite] = mn;} else {siteErrors[s+siteOffsetForError]+=mjCnt;} } else { errorRate=(double)mnCnt/(double)totalCnt; if(errorRate<maxError) {calls[s-startSite] = mj;} else {siteErrors[s+siteOffsetForError]+=mnCnt;} } } return calls; } public static ArrayList<Integer> maxMajorAllelesTaxa(Alignment a, int numMaxTaxa, int alleleNumber) { ArrayList<Integer> maxTaxa=new ArrayList<Integer>(); OpenBitSet curMj=new OpenBitSet(a.getSiteCount()); long maxMjCnt=curMj.cardinality(); for (int i = 0; i < numMaxTaxa; i++) { long bestCnt=0; int bestAddTaxa=-1; for (int t = 0; t < a.getSequenceCount(); t++) { BitSet testMj=new OpenBitSet(a.getAllelePresenceForAllSites(t, alleleNumber)); testMj.union(curMj); long cnt=testMj.cardinality(); if(cnt>bestCnt) { bestCnt=cnt; bestAddTaxa=t; } } if(maxMjCnt==bestCnt) continue; curMj.union(a.getAllelePresenceForAllSites(bestAddTaxa, alleleNumber)); maxMjCnt=curMj.cardinality(); maxTaxa.add(bestAddTaxa); System.out.printf("Allele:%d Taxa: %s %d %n",alleleNumber,a.getTaxaName(bestAddTaxa),maxMjCnt); } return maxTaxa; } private int[] countUnknown(byte[] b) { int cnt=0, cntHet=0; for (int i = 0; i < b.length; i++) { if(b[i]==Alignment.UNKNOWN_DIPLOID_ALLELE) {cnt++;} else if(AlignmentUtils.isHeterozygous(b[i])) {cntHet++;} } int[] result={cnt,cntHet}; return result; } @Override public void setParameters(String[] args) { if (args.length == 0) { printUsage(); throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n"); } engine.add("-hmp", "-hmpFile", true); engine.add("-o", "--outFile", true); engine.add("-oE", "--outErrorFile", true); engine.add("-sC", "--startChrom", true); engine.add("-eC", "--endChrom", true); engine.add("-mxDiv", "--mxDiv", true); engine.add("-mxHet", "--mxHet", true); engine.add("-hapSize", "--hapSize", true); engine.add("-minPres", "--minPres", true); engine.add("-maxHap", "--maxHap", true); engine.add("-maxOutMiss", "--maxOutMiss", true); engine.parse(args); if (engine.getBoolean("-sC")) { startChr = Integer.parseInt(engine.getString("-sC")); } if (engine.getBoolean("-eC")) { endChr = Integer.parseInt(engine.getString("-eC")); } hmpFile = engine.getString("-hmp"); outFileBase = engine.getString("-o"); errFile = engine.getString("-oE"); if (engine.getBoolean("-mxDiv")) { maxDistFromFounder = Double.parseDouble(engine.getString("-mxDiv")); } if (engine.getBoolean("-mxHet")) { maxHetFreq = Double.parseDouble(engine.getString("-mxHet")); } if (engine.getBoolean("-maxOutMiss")) { maximumMissing = Double.parseDouble(engine.getString("-maxOutMiss")); } if (engine.getBoolean("-hapSize")) { appoxSitesPerHaplotype = Integer.parseInt(engine.getString("-hapSize")); } if (engine.getBoolean("-minPres")) { minSitesPresentPerHap = Integer.parseInt(engine.getString("-minPres")); } if (engine.getBoolean("-maxHap")) { maxHaplotypes = Integer.parseInt(engine.getString("-maxHap")); } } private void printUsage() { myLogger.info( "\n\n\nAvailable options for the FindMergeHaplotypesPlugin are as follows:\n" + "-hmp Input HapMap file (either hmp.txt.gz or hmp.h5)\n" + "-o Output file(s) must include 's+.' plus will be replace by segment (0..(~sites/hapSize)\n" + "-oE Optional file to record site by sites errors as the haplotypes are developed\n" + "-sC Start chromosome\n" + "-eC End chromosome\n" + "-mxDiv Maximum divergence from founder haplotype\n" + "-mxHet Maximum heterozygosity of haplotype to even scanned\n" + "-hapSize Preferred haplotype block size in sites\n" + "-minPres Minimum number of present sites within input sequence to do the search\n" + "-maxHap Maximum number of haplotypes per segment\n" + "-maxOutMiss Maximum frequency of missing data in the output haplotype" ); } @Override public DataSet performFunction(DataSet input) { if(outFileBase.contains(".gX.")) { runFindMergeHaplotypes(hmpFile, outFileBase, errFile, maxDistFromFounder, minSitesPresentPerHap, appoxSitesPerHaplotype); return null; } for (int chr = startChr; chr <=endChr; chr++) { String chrHmpFile=hmpFile.replace("chrX", "chr"+chr); chrHmpFile=chrHmpFile.replace("cX", "c"+chr); String chrOutfiles=outFileBase.replace("chrX", "chr"+chr); chrOutfiles=chrOutfiles.replace("cX", "c"+chr); runFindMergeHaplotypes(chrHmpFile, chrOutfiles, errFile, maxDistFromFounder, minSitesPresentPerHap, appoxSitesPerHaplotype); } return null; } @Override public ImageIcon getIcon() { return null; } @Override public String getButtonName() { return "ExtractInbredHaplotypes"; } @Override public String getToolTipText() { return "Creates haplotype alignments based on long IBD regions of inbred lines"; } /** * * @param args */ public static void main(String[] args) { // String root="/Users/edbuckler/SolexaAnal/GBS/build20120701/impOrig/"; // String root="/Users/edbuckler/SolexaAnal/GBS/build20120701/IMP26/orig/"; // String rootOut="/Users/edbuckler/SolexaAnal/GBS/build20120701/IMP26/haplos/"; String root="/Volumes/LaCie/build20120701/IMP26/orig/"; String rootOut="/Volumes/LaCie/build20120701/IMP26/haplos/"; String infileH5=root+"AllZeaGBS_v2.6.chrX.hmp.h5"; String secFile26v=rootOut+"Tall26_8k.cXsX.hmp.txt.gz"; String errorFile=rootOut+"mcErrorXMerge20130425.txt"; String[] args2 = new String[]{ "-hmp", infileH5, "-o", secFile26v, "-sC","8", "-eC","8", "-mxDiv", "0.01", "-mxHet", "0.01", "-hapSize", "8000", "-minPres", "500", "-maxOutMiss","0.4", "-maxHap", "2000", }; FindMergeHaplotypesPlugin plugin = new FindMergeHaplotypesPlugin(); plugin.setParameters(args2); plugin.performFunction(null); } }
package org.anddev.andengine.opengl.texture.bitmap; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.opengl.texture.Texture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.util.GLState; import org.anddev.andengine.util.StreamUtils; import org.anddev.andengine.util.exception.NullBitmapException; import org.anddev.andengine.util.math.MathUtils; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLUtils; public abstract class BitmapTexture extends Texture { // Constants // Fields private final int mWidth; private final int mHeight; private final BitmapTextureFormat mBitmapTextureFormat; // Constructors public BitmapTexture() throws IOException { this(BitmapTextureFormat.RGBA_8888, TextureOptions.DEFAULT, null); } public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat) throws IOException { this(pBitmapTextureFormat, TextureOptions.DEFAULT, null); } public BitmapTexture(final TextureOptions pTextureOptions) throws IOException { this(BitmapTextureFormat.RGBA_8888, pTextureOptions, null); } public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions) throws IOException { this(pBitmapTextureFormat, pTextureOptions, null); } public BitmapTexture(final BitmapTextureFormat pBitmapTextureFormat, final TextureOptions pTextureOptions, final ITextureStateListener pTextureStateListener) throws IOException { super(pBitmapTextureFormat.getPixelFormat(), pTextureOptions, pTextureStateListener); this.mBitmapTextureFormat = pBitmapTextureFormat; final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inJustDecodeBounds = true; final InputStream in = null; try { BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); } finally { StreamUtils.close(in); } this.mWidth = decodeOptions.outWidth; this.mHeight = decodeOptions.outHeight; } // Getter & Setter @Override public int getWidth() { return this.mWidth; } @Override public int getHeight() { return this.mHeight; } // Methods for/from SuperClass/Interfaces @Override public BitmapTexture load() { super.load(); return this; } @Override public BitmapTexture unload() { super.unload(); return this; } protected abstract InputStream onGetInputStream() throws IOException; @Override protected void writeTextureToHardware() throws IOException { final Config bitmapConfig = this.mBitmapTextureFormat.getBitmapConfig(); final Bitmap bitmap = this.onGetBitmap(bitmapConfig); if(bitmap == null) { throw new NullBitmapException("Caused by: '" + this.toString() + "'."); } final boolean useDefaultAlignment = MathUtils.isPowerOfTwo(bitmap.getWidth()) && MathUtils.isPowerOfTwo(bitmap.getHeight()) && this.mPixelFormat == PixelFormat.RGBA_8888; if(!useDefaultAlignment) { GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1); } final boolean preMultipyAlpha = this.mTextureOptions.mPreMultipyAlpha; if(preMultipyAlpha) { GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); } else { GLState.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0, this.mPixelFormat); } /* Restore default alignment. */ if(!useDefaultAlignment) { GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, GLState.GL_UNPACK_ALIGNMENT_DEFAULT); } bitmap.recycle(); } // Methods protected Bitmap onGetBitmap(final Config pBitmapConfig) throws IOException { final BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); decodeOptions.inPreferredConfig = pBitmapConfig; return BitmapFactory.decodeStream(this.onGetInputStream(), null, decodeOptions); } // Inner and Anonymous Classes public static enum BitmapTextureFormat { // Elements RGBA_8888(Config.ARGB_8888, PixelFormat.RGBA_8888), RGB_565(Config.RGB_565, PixelFormat.RGB_565), RGBA_4444(Config.ARGB_4444, PixelFormat.RGBA_4444), // TODO A_8(Config.ALPHA_8, PixelFormat.A_8); // TODO // Constants // Fields private final Config mBitmapConfig; private final PixelFormat mPixelFormat; // Constructors private BitmapTextureFormat(final Config pBitmapConfig, final PixelFormat pPixelFormat) { this.mBitmapConfig = pBitmapConfig; this.mPixelFormat = pPixelFormat; } public static BitmapTextureFormat fromPixelFormat(final PixelFormat pPixelFormat) { switch(pPixelFormat) { case RGBA_8888: return RGBA_8888; case RGBA_4444: return RGBA_4444; case RGB_565: return RGB_565; case A_8: return A_8; default: throw new IllegalArgumentException("Unsupported " + PixelFormat.class.getName() + ": '" + pPixelFormat + "'."); } } // Getter & Setter public Config getBitmapConfig() { return this.mBitmapConfig; } public PixelFormat getPixelFormat() { return this.mPixelFormat; } // Methods from SuperClass/Interfaces // Methods // Inner and Anonymous Classes } }
package org.gridlab.gridsphere.core.persistence.hibernate; import net.sf.hibernate.HibernateException; import net.sf.hibernate.MappingException; import net.sf.hibernate.cfg.Configuration; import net.sf.hibernate.connection.DriverManagerConnectionProvider; import net.sf.hibernate.tool.hbm2ddl.SchemaExport; import net.sf.hibernate.tool.hbm2ddl.SchemaUpdate; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.PersistenceManagerRdbms; import org.gridlab.gridsphere.portlet.PortletLog; import org.gridlab.gridsphere.portlet.impl.SportletLog; import org.gridlab.gridsphere.portlet.impl.SportletUserImpl; import org.gridlab.gridsphere.portletcontainer.GridSphereConfig; import java.io.*; import java.sql.Connection; import java.sql.SQLException; import java.util.*; /* * @author <a href="mailto:oliver.wehrens@aei.mpg.de">Oliver Wehrens</a> * @version $Id$ */ /** * Ant task to create/update the database. */ public class DBTask extends Task { private PortletLog log = SportletLog.getInstance(DBTask.class); public final static String ACTION_CREATE = "CREATE"; public final static String ACTION_UPDATE = "UPDATE"; public final static String ACTION_CHECKDB = "CHECKDB"; private String MAPPING_ERROR = "FATAL: Could not create database! Please check above errormessages! "; private String CONFIGFILE_ERROR = "FATAL: No database configfile found! "; private String CHECK_PROPS = "Please check the hibernate.properties file! "; private String DATABASE_CONNECTION_NOT_VALID = "FATAL: Database conenction is not valid! "; private String CONNECTION_ERROR = "FATAL: Could not connect to database! "; private String NOT_INSTALLED = "Gridsphere is NOT correctly installed! "; private String NO_CORE_TABLES = "Some core tables could not be found!"; private String CREATION_ERROR = "Could not create database!"; private String UPDATE_ERROR = "Could not update database!"; private String hibernatePropertiesFileName = "hibernate.properties"; private String configDir = ""; private String action = ""; /** * Sets the configuration directory of the database. All mappingfiles and the hibernate.properties * are located in this directory. * * @param configDir full path to the configuration directory */ public void setConfigDir(String configDir) { SportletLog.setConfigureURL(configDir + "/WEB-INF/classes/log4j.properties"); this.configDir = configDir; } public void setAction(String action) { this.action = action; } private void createDatabase(Configuration cfg) throws BuildException { try { new SchemaExport(cfg).create(false, true); log.info("Successfully created DB"); } catch (HibernateException e) { throw new BuildException("DB Error: " + CREATION_ERROR + " " + NOT_INSTALLED + " !"); } } private void updateDatabase(Configuration cfg) throws BuildException { try { new SchemaUpdate(cfg).execute(false, true); } catch (HibernateException e) { throw new BuildException("DB Error: " + UPDATE_ERROR + " " + NOT_INSTALLED + " !"); } } private void checkDatabase() throws BuildException { try { PersistenceManagerRdbms rdbms = PersistenceManagerFactory.createGridSphereRdbms(); // check if there is the user table, should be enough List r = rdbms.restoreList("select uzer from " + SportletUserImpl.class.getName() + " uzer"); } catch (Exception e) { throw new BuildException("DB Error: " + NO_CORE_TABLES + " " + NOT_INSTALLED); } } /** * Loads properties from a given directory. * * @return * @throws BuildException */ private Properties loadGSProperties() throws BuildException { Properties prop = new Properties(); String hibPath = configDir + File.separator + "WEB-INF" + File.separator + "CustomPortal" + File.separator + "database" + File.separator + hibernatePropertiesFileName; try { FileInputStream fis = new FileInputStream(hibPath); prop.load(fis); log.info("Using database configuration information from: " + hibPath); } catch (IOException e) { throw new BuildException("DB Error:" + CONFIGFILE_ERROR + " (" + hibPath + ")"); } return prop; } /** * Loads properties from a given directory. * * @return * @throws BuildException */ private Properties loadProjectProperties() throws BuildException { Properties prop = new Properties(); String hibPath = configDir + File.separator + "WEB-INF" + File.separator + "persistence" + File.separator + hibernatePropertiesFileName; try { //File hibFile = new File(hibPath); /* if (!hibFile.exists()) { log.info("Copying template hibernate properties file from " + hibPath + " to " + hibPath); GridSphereConfig.copyFile(new File(hibPath), hibFile); } */ FileInputStream fis = new FileInputStream(hibPath); prop.load(fis); log.info("Using database configuration information from: " + hibPath); } catch (IOException e) { throw new BuildException("DB Error:" + CONFIGFILE_ERROR + " (" + hibPath + ")"); } return prop; } /** * Test the Database connection. * * @param props * @throws BuildException */ private void testDBConnection(Properties props) throws BuildException { DriverManagerConnectionProvider dmcp = new DriverManagerConnectionProvider(); try { dmcp.configure(props); Connection con = dmcp.getConnection(); dmcp.closeConnection(con); } catch (HibernateException e) { throw new BuildException("Error: testDBConnection (1) : " + DATABASE_CONNECTION_NOT_VALID + " " + CHECK_PROPS + " " + NOT_INSTALLED); } catch (SQLException e) { throw new BuildException("Error: testDBConnection (2) " + CONNECTION_ERROR + " " + CHECK_PROPS + " " + NOT_INSTALLED); } } /** * Get a hibernate configuration. * * @param props * @return * @throws BuildException */ private Configuration getDBConfiguration(Properties props) throws BuildException { Configuration cfg = null; try { cfg = new Configuration(); cfg.setProperties(props); String mappingPath = configDir + File.separator + "WEB-INF" + File.separator + "persistence"; File mappingdir = new File(mappingPath); String[] children = mappingdir.list(); if (children == null) { // Either dir does not exist or is not a directory } else { // Create list from children array List filenameList = Arrays.asList(children); // Ensure that this list is sorted alphabetically Collections.sort(filenameList); for (Iterator filenames = filenameList.iterator(); filenames.hasNext();) { String filename = (String) filenames.next(); if (filename.endsWith(".hbm.xml")) { // Get filename of file or directory log.debug("add hbm file :" + mappingPath + File.separator + filename); cfg.addFile(mappingPath + File.separator + filename); } } } } catch (MappingException e) { throw new BuildException("DB Error: " + MAPPING_ERROR + " " + NOT_INSTALLED); } catch (HibernateException e) { throw new BuildException("DB Error: " + MAPPING_ERROR + " " + NOT_INSTALLED); } return cfg; } public void execute() throws BuildException { log.info("Database:"); log.info("Config: " + this.configDir); log.info("Action: " + this.action); try { // try to load the properties Properties properties = null; if (configDir.endsWith("gridsphere")) { log.info("Using GridSphere database"); properties = loadGSProperties(); } else { log.info("Using project database"); properties = loadProjectProperties(); } // test the db connection this.testDBConnection(properties); log.info("Tested DB connection."); // get a hibernate db Configuration Configuration cfg = getDBConfiguration(properties); log.info("Got DB configuration."); if (action.equals(ACTION_CHECKDB)) { this.checkDatabase(); } else if (action.equals(ACTION_CREATE)) { this.createDatabase(cfg); } else if (action.equals(ACTION_UPDATE)) { this.updateDatabase(cfg); } else { throw new BuildException("Unknown Action specified (" + this.action + ")!"); } } catch (BuildException e) { log.info("Database not correctly installed.\n" + e); throw new BuildException("The database is not correctly installed!"); } } }
package org.helioviewer.jhv.renderable.components; import java.awt.Component; import java.nio.FloatBuffer; import java.nio.IntBuffer; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.opengl.GLSLLineShader; import org.helioviewer.jhv.opengl.GLSLShader; import org.helioviewer.jhv.opengl.VBO; import org.helioviewer.jhv.renderable.gui.AbstractRenderable; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.GL2; public class RenderableLine extends AbstractRenderable { private float[][] points; private float[][] colors; private int[] vboAttribRefs = { GLSLLineShader.previousLineRef, GLSLLineShader.lineRef, GLSLLineShader.nextLineRef, GLSLLineShader.directionRef, GLSLLineShader.linecolorRef }; private int[] vboAttribLens = { 3, 3, 3, 1, 4 }; private VBO[] vbos = new VBO[5]; private VBO ivbo; private boolean inited = false; public RenderableLine(float[][] _points) { points = _points; } public RenderableLine(FloatBuffer vertices, FloatBuffer _colors) { points = monoToBidi(vertices, vertices.limit() / 3, 3); colors = monoToBidi(_colors, _colors.limit() / 4, 4); } public float[][] monoToBidi(final FloatBuffer array, final int rows, final int cols) { if (array.limit() != (rows * cols)) throw new IllegalArgumentException("Invalid array length"); float[][] bidi = new float[rows][cols]; int c = 0; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) bidi[i][j] = array.get(c++); return bidi; } @Override public void render(Camera camera, Viewport vp, GL2 gl) { if (!inited) return; GLSLLineShader.line.bind(gl); GLSLLineShader.line.setAspect((float) vp.aspect * 2); GLSLLineShader.line.bindParams(gl); bindVBOs(gl); gl.glDrawElements(GL2.GL_TRIANGLES, 6, GL2.GL_UNSIGNED_INT, 0); gl.glDrawElements(GL2.GL_TRIANGLES, vbos[4].bufferSize, GL2.GL_UNSIGNED_INT, 3); unbindVBOs(gl); GLSLShader.unbind(gl); } @Override public void remove(GL2 gl) { } @Override public Component getOptionsPanel() { return null; } @Override public String getName() { return "line"; } @Override public String getTimeString() { return null; } @Override public boolean isDeletable() { return false; } private void bindVBOs(GL2 gl) { for (int i = 0; i < vbos.length; i++) { vbos[i].bindArray(gl); } ivbo.bindArray(gl); } private void unbindVBOs(GL2 gl) { for (int i = vbos.length - 1; i >= 0; i vbos[i].unbindArray(gl); } ivbo.unbindArray(gl); } private void initVBOs(GL2 gl) { for (int i = 0; i < vboAttribRefs.length; i++) { vbos[i] = new VBO(GL2.GL_ARRAY_BUFFER, vboAttribRefs[i], vboAttribLens[i]); vbos[i].init(gl); } ivbo = new VBO(GL2.GL_ELEMENT_ARRAY_BUFFER, -1, -1); } private void disposeVBOs(GL2 gl) { for (int i = 0; i < vbos.length; i++) { vbos[i].dispose(gl); vbos[i] = null; } ivbo.dispose(gl); ivbo = null; } public IntBuffer gen_indices(int length) { IntBuffer indicesBuffer = IntBuffer.allocate(6 * points.length); int i = 0; for (int j = 0; j < length; j++) { indicesBuffer.put(i + 0); indicesBuffer.put(i + 1); indicesBuffer.put(i + 2); indicesBuffer.put(i + 2); indicesBuffer.put(i + 1); indicesBuffer.put(i + 3); i = i + 2; } indicesBuffer.flip(); return indicesBuffer; } @Override public void init(GL2 gl) { if (points.length < 2) return; FloatBuffer previousLineBuffer = FloatBuffer.allocate(6 * points.length); FloatBuffer lineBuffer = FloatBuffer.allocate(6 * points.length); FloatBuffer nextLineBuffer = FloatBuffer.allocate(6 * points.length); FloatBuffer directionBuffer = FloatBuffer.allocate(4 * points.length); FloatBuffer colorBuffer = FloatBuffer.allocate(2 * 4 * points.length); int dir = -1; for (int i = 0; i < 2 * points.length; i++) { directionBuffer.put(dir); directionBuffer.put(-dir); } previousLineBuffer.put(points[0]); previousLineBuffer.put(points[0]); lineBuffer.put(points[0]); lineBuffer.put(points[0]); colorBuffer.put(colors[0]); colorBuffer.put(colors[0]); nextLineBuffer.put(points[1]); nextLineBuffer.put(points[1]); for (int i = 1; i < points.length - 1; i++) { previousLineBuffer.put(points[i - 1]); previousLineBuffer.put(points[i - 1]); lineBuffer.put(points[i]); lineBuffer.put(points[i]); colorBuffer.put(colors[i]); colorBuffer.put(colors[i]); nextLineBuffer.put(points[i + 1]); nextLineBuffer.put(points[i + 1]); } previousLineBuffer.put(points[points.length - 2]); previousLineBuffer.put(points[points.length - 2]); lineBuffer.put(points[points.length - 1]); lineBuffer.put(points[points.length - 1]); colorBuffer.put(colors[points.length - 1]); colorBuffer.put(colors[points.length - 1]); nextLineBuffer.put(points[points.length - 1]); nextLineBuffer.put(points[points.length - 1]); previousLineBuffer.flip(); lineBuffer.flip(); nextLineBuffer.flip(); directionBuffer.flip(); colorBuffer.flip(); initVBOs(gl); vbos[0].bindBufferData(gl, previousLineBuffer, Buffers.SIZEOF_FLOAT); vbos[1].bindBufferData(gl, lineBuffer, Buffers.SIZEOF_FLOAT); vbos[2].bindBufferData(gl, nextLineBuffer, Buffers.SIZEOF_FLOAT); vbos[3].bindBufferData(gl, directionBuffer, Buffers.SIZEOF_FLOAT); vbos[4].bindBufferData(gl, colorBuffer, Buffers.SIZEOF_FLOAT); IntBuffer indexBuffer = this.gen_indices(points.length); ivbo.bindBufferData(gl, indexBuffer, Buffers.SIZEOF_INT); inited = true; } @Override public void dispose(GL2 gl) { this.disposeVBOs(gl); inited = false; } }
package org.jpos.iso.channel; import java.io.*; import java.util.*; import java.net.ServerSocket; import java.net.Socket; import org.jpos.iso.*; /** * ISOChannel implementation - Postilion Channel * Send packet len (2 bytes network byte order MSB/LSB) followed by * raw data. * * @author salaman@teknos.com * @version Id: PostChannel.java,v 1.0 1999/05/14 19:00:00 may Exp * @see ISOMsg * @see ISOException * @see ISOChannel */ public class PostChannel extends BaseChannel { /** * Public constructor (used by Class.forName("...").newInstance()) */ public PostChannel () { super(); } /** * Construct client ISOChannel * @param host server TCP Address * @param port server port number * @param p an ISOPackager * @see ISOPackager */ public PostChannel (String host, int port, ISOPackager p) { super(host, port, p); } /** * Construct server ISOChannel * @param p an ISOPackager * @exception IOException * @see ISOPackager */ public PostChannel (ISOPackager p) throws IOException { super(p); } /** * constructs a server ISOChannel associated with a Server Socket * @param p an ISOPackager * @param serverSocket where to accept a connection * @exception IOException * @see ISOPackager */ public PostChannel (ISOPackager p, ServerSocket serverSocket) throws IOException { super(p, serverSocket); } protected void sendMessageLength(int len) throws IOException { serverOut.write (len >> 8); serverOut.write (len); } protected int getMessageLength() throws IOException, ISOException { byte[] b = new byte[2]; if (serverIn.read(b,0,2) != 2) throw new EOFException("error reading message length"); return (int) ( ((((int)b[0])&0xFF) << 8) | (((int)b[1])&0xFF)); } }
package au.com.southsky.jfreesane; import com.google.common.truth.Truth; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; /** * Acquires a series of images from the test device and compares them against reference images * obtained from the "scanimage" SANE util. By default, the SANE server running on localhost is * used, but this can be overridden by specifying the address in "host[:port]" format in the * SANE_TEST_SERVER_ADDRESS environment variable. */ @RunWith(Parameterized.class) public class ImageAcquisitionTest { private SanePasswordProvider correctPasswordProvider = SanePasswordProvider.forUsernameAndPassword("testuser", "goodpass"); @Before public void initSession() throws Exception { String address = System.getenv("SANE_TEST_SERVER_ADDRESS"); if (address == null) { address = "localhost"; } URI hostAndPort = URI.create("my://" + address); this.session = SaneSession.withRemoteSane( InetAddress.getByName(hostAndPort.getHost()), hostAndPort.getPort() == -1 ? 6566 : hostAndPort.getPort()); session.setPasswordProvider(correctPasswordProvider); } @Parameterized.Parameters(name = "device={0},mode={1},depth={2},pattern={3}") public static Iterable<Object[]> parameters() { List<String> devices = Collections.singletonList("test"); List<String> modes = Arrays.asList("Gray", "Color"); List<Integer> depths = Arrays.asList(1, 8, 16); List<String> patterns = Arrays.asList("Solid white", "Solid black", "Color pattern"); List<Object[]> result = new ArrayList<>(depths.size() * modes.size() * depths.size() * patterns.size()); for (String dev : devices) { for (String mode : modes) { for (int depth : depths) { for (String pattern : patterns) { result.add(new Object[] {dev, mode, depth, pattern}); } } } } return result; } private SaneSession session; private final String device; private final String mode; private final int depth; private final String pattern; public ImageAcquisitionTest(String device, String mode, int depth, String pattern) { this.device = device; this.mode = mode; this.depth = depth; this.pattern = pattern; } @Test public void testImageAcquisition() throws IOException, SaneException { Assume.assumeFalse("color tests at depth 1 are skipped", depth == 1 && "Color".equals(mode)); BufferedImage expectedImage = getExpectedImage(); try (SaneDevice dev = session.getDevice(device)) { dev.open(); Truth.assertThat(dev.getOption("mode").setStringValue(mode)).isEqualTo(mode); Truth.assertThat(dev.getOption("depth").setIntegerValue(depth)).isEqualTo(depth); Truth.assertThat(dev.getOption("test-picture").setStringValue(pattern)).isEqualTo(pattern); BufferedImage actualImage = dev.acquireImage(); assertImagesEqual(expectedImage, actualImage); } } /** * Reads the expected image from test resources. If those resources are not present, scanimage is * invoked to read the reference image. */ private BufferedImage getExpectedImage() throws IOException { String resourceName = String.format("/%s-%d-%s.png", mode, depth, pattern.replace(" ", "_")); InputStream resource = ImageAcquisitionTest.class.getResource(resourceName).openStream(); return ImageIO.read(resource); } private void assertImagesEqual(BufferedImage expected, BufferedImage actual) { assertEquals("image widths differ", expected.getWidth(), actual.getWidth()); assertEquals("image heights differ", expected.getHeight(), actual.getHeight()); for (int x = 0; x < expected.getWidth(); x++) { for (int y = 0; y < expected.getHeight(); y++) { Truth.assertThat(actual.getRGB(x, y)).isEqualTo(expected.getRGB(x, y)); } } } }
package br.com.caelum.pagpag.aceitacao.util; public class ServerInfo { private static final String TEST_SERVER = "vraptor.server_host"; static final int PORT = 8080; public interface AcceptanceTest { static final ServerInfo SERVER = new ServerInfo(); } public String urlFor(String path) { return getRoot() + path; } public String getRoot() { return "http://" + ACTUAL_HOST; } private static final String ACTUAL_HOST = getHost(); private static String getHost() { if (isRemoteRun()) return System.getProperty(TEST_SERVER); return "localhost:" + PORT; } private static boolean isRemoteRun() { String server = System.getProperty(TEST_SERVER); return server != null && !server.isEmpty(); } }
package com.celements.xwikiPatches; import static com.celements.common.test.CelementsTestUtils.*; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.exception.ExceptionUtils; import org.easymock.IAnswer; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.classic.Session; import org.hibernate.impl.AbstractQueryImpl; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.cache.CacheFactory; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.context.ExecutionContextException; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.WikiReference; import com.celements.common.test.AbstractComponentTest; import com.celements.navigation.INavigationClassConfig; import com.celements.pagetype.IPageTypeClassConfig; import com.celements.web.service.IWebUtilsService; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConfig; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.PropertyInterface; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.store.XWikiCacheStore; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.hibernate.HibernateSessionFactory; import com.xpn.xwiki.util.AbstractXWikiRunnable; import com.xpn.xwiki.web.Utils; public class ConcurrentCacheTest extends AbstractComponentTest { private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentCacheTest.class); private volatile XWikiCacheStore theCacheStore; private volatile ConcurrentMap<DocumentReference, List<BaseObject>> baseObjMap = new ConcurrentHashMap<>(); private volatile DocumentReference testDocRef; private static volatile Collection<Object> defaultMocks; private static volatile XWikiContext defaultContext; private final String wikiName = "testWiki"; private final WikiReference wikiRef = new WikiReference(wikiName); private String testFullName = "TestSpace.TestDoc"; private XWikiConfig configMock; private SessionFactory sessionFactoryMock; private IPageTypeClassConfig pageTypeClassConfig; private INavigationClassConfig navClassConfig; private IWebUtilsService webUtilsService; @SuppressWarnings("deprecation") @Before public void setUp_ConcurrentCatchTest() throws Exception { pageTypeClassConfig = Utils.getComponent(IPageTypeClassConfig.class); navClassConfig = Utils.getComponent(INavigationClassConfig.class); webUtilsService = Utils.getComponent(IWebUtilsService.class); getContext().setDatabase(wikiName); sessionFactoryMock = createMockAndAddToDefault(SessionFactory.class); Utils.getComponent(HibernateSessionFactory.class).setSessionFactory(sessionFactoryMock); testDocRef = new DocumentReference(wikiName, "TestSpace", "TestDoc"); configMock = createMockAndAddToDefault(XWikiConfig.class); expect(getWikiMock().getConfig()).andReturn(configMock).anyTimes(); expect(configMock.getProperty(eq("xwiki.store.hibernate.path"), eq( "/WEB-INF/hibernate.cfg.xml"))).andReturn("testhibernate.cfg.xml"); expect(getWikiMock().Param(eq("xwiki.store.cache.capacity"))).andReturn(null).anyTimes(); expect(getWikiMock().Param(eq("xwiki.store.cache.pageexistcapacity"))).andReturn( null).anyTimes(); CacheFactory cacheFactory = Utils.getComponent(CacheFactory.class, "jbosscache"); expect(getWikiMock().getCacheFactory()).andReturn(cacheFactory).anyTimes(); expect(getWikiMock().getPlugin(eq("monitor"), isA(XWikiContext.class))).andReturn( null).anyTimes(); expect(getWikiMock().hasDynamicCustomMappings()).andReturn(false).anyTimes(); expect(getWikiMock().isVirtualMode()).andReturn(false).anyTimes(); expect(getWikiMock().Param(eq("xwiki.store.hibernate.useclasstables.read"), eq("1"))).andReturn( "0").anyTimes(); expect(getWikiMock().getXClass(isA(DocumentReference.class), isA( XWikiContext.class))).andStubDelegateTo(new TestXWiki()); createBaseObjects(); } @Test public void test_singleThreaded_sync() throws Exception { Session sessionMock = createMockAndAddToDefault(Session.class); expect(sessionFactoryMock.openSession()).andReturn(sessionMock).once(); sessionMock.setFlushMode(eq(FlushMode.COMMIT)); expectLastCall().atLeastOnce(); sessionMock.setFlushMode(eq(FlushMode.MANUAL)); expectLastCall().atLeastOnce(); Transaction transactionMock = createMockAndAddToDefault(Transaction.class); expect(sessionMock.beginTransaction()).andReturn(transactionMock).once(); transactionMock.rollback(); expectLastCall().once(); expect(sessionMock.close()).andReturn(null).once(); XWikiDocument myDoc = new XWikiDocument(testDocRef); expectXWikiDocLoad(sessionMock, myDoc); expectLoadEmptyAttachmentList(sessionMock); expectBaseObjectLoad(sessionMock); replayDefault(); initStorePrepareMultiThreadMocks(); LoadXWikiDocCommand testLoadCommand = new LoadXWikiDocCommand(); List<Object> result = testLoadCommand.call(); assertTrue((Boolean) result.get(0)); verifyDefault(); } @Test public void test_singleThreaded_async() throws Exception { Session sessionMock = createMockAndAddToDefault(Session.class); expect(sessionFactoryMock.openSession()).andReturn(sessionMock).once(); sessionMock.setFlushMode(eq(FlushMode.COMMIT)); expectLastCall().atLeastOnce(); sessionMock.setFlushMode(eq(FlushMode.MANUAL)); expectLastCall().atLeastOnce(); Transaction transactionMock = createMockAndAddToDefault(Transaction.class); expect(sessionMock.beginTransaction()).andReturn(transactionMock).once(); transactionMock.rollback(); expectLastCall().once(); expect(sessionMock.close()).andReturn(null).once(); XWikiDocument myDoc = new XWikiDocument(testDocRef); expectXWikiDocLoad(sessionMock, myDoc); expectLoadEmptyAttachmentList(sessionMock); expectBaseObjectLoad(sessionMock); replayDefault(); initStorePrepareMultiThreadMocks(); ScheduledExecutorService theExecutor = Executors.newScheduledThreadPool(1); Future<List<Object>> testFuture = theExecutor.submit( (Callable<List<Object>>) new LoadXWikiDocCommand()); theExecutor.shutdown(); while (!theExecutor.isTerminated()) { Thread.sleep(500L); } List<Object> result = testFuture.get(); @SuppressWarnings("unchecked") List<String> messages = (List<String>) result.get(1); assertTrue(Arrays.deepToString(messages.toArray()), (Boolean) result.get(0)); verifyDefault(); } @Test public void test_multiRuns_singleThreaded() throws Exception { executeMultiRunsTest(1, 50000); } @Test public void test_multiThreaded() throws Exception { int cores = Runtime.getRuntime().availableProcessors(); assertTrue("This tests needs real multi core processors, but found " + cores, cores > 1); executeMultiRunsTest(cores, 100000); } private void executeMultiRunsTest(int cores, int executeRuns) throws Exception { Session sessionMock = createMockAndAddToDefault(Session.class); expect(sessionFactoryMock.openSession()).andReturn(sessionMock).anyTimes(); sessionMock.setFlushMode(eq(FlushMode.COMMIT)); expectLastCall().atLeastOnce(); sessionMock.setFlushMode(eq(FlushMode.MANUAL)); expectLastCall().atLeastOnce(); Transaction transactionMock = createMockAndAddToDefault(Transaction.class); expect(sessionMock.beginTransaction()).andReturn(transactionMock).anyTimes(); transactionMock.rollback(); expectLastCall().anyTimes(); expect(sessionMock.close()).andReturn(null).anyTimes(); XWikiDocument myDoc = new XWikiDocument(testDocRef); expectXWikiDocLoad(sessionMock, myDoc); expectLoadEmptyAttachmentList(sessionMock); expectBaseObjectLoad(sessionMock); replayDefault(); initStorePrepareMultiThreadMocks(); ScheduledExecutorService theExecutor = Executors.newScheduledThreadPool(cores); List<Future<List<Object>>> futureList = new ArrayList<>(executeRuns * (cores + 1)); for (int i = 1; i < executeRuns; i++) { futureList.add(theExecutor.submit((Callable<List<Object>>) new LoadXWikiDocCommand())); CountDownLatch doneSignal = new CountDownLatch(cores); CountDownLatch startSignal = new CountDownLatch(cores); for (int j = 1; j <= cores; j++) { Future<List<Object>> testFuture = theExecutor.schedule( (Callable<List<Object>>) new LoadXWikiDocCommand(startSignal, doneSignal), 100, TimeUnit.MILLISECONDS); futureList.add(testFuture); } doneSignal.await(); theExecutor.submit(new ResetCacheEntryCommand()); } CountDownLatch startSignal2 = new CountDownLatch(cores); CountDownLatch doneSignal2 = new CountDownLatch(executeRuns); List<Future<List<Object>>> futureList2 = new ArrayList<>(executeRuns); futureList2.add(theExecutor.submit((Callable<List<Object>>) new LoadXWikiDocCommand(null, doneSignal2))); for (int i = 1; i < executeRuns; i++) { Future<List<Object>> testFuture = theExecutor.schedule( (Callable<List<Object>>) new LoadXWikiDocCommand(startSignal2, doneSignal2), 500, TimeUnit.MILLISECONDS); futureList2.add(testFuture); } doneSignal2.await(); theExecutor.submit(new ResetCacheEntryCommand()); CountDownLatch startSignal3 = new CountDownLatch(cores); CountDownLatch doneSignal3 = new CountDownLatch(executeRuns); List<Future<List<Object>>> futureList3 = new ArrayList<>(executeRuns); futureList3.add(theExecutor.submit((Callable<List<Object>>) new LoadXWikiDocCommand(null, doneSignal3))); for (int i = 1; i < executeRuns; i++) { Future<List<Object>> testFuture = theExecutor.schedule( (Callable<List<Object>>) new LoadXWikiDocCommand(startSignal3, doneSignal3), 1000, TimeUnit.MILLISECONDS); futureList3.add(testFuture); } doneSignal3.await(); theExecutor.shutdown(); while (!theExecutor.isTerminated()) { Thread.sleep(500L); } assertSuccessFullRuns(futureList); assertSuccessFullRuns(futureList2); assertSuccessFullRuns(futureList3); verifyDefault(); } void assertSuccessFullRuns(List<Future<List<Object>>> futureList) throws InterruptedException, ExecutionException { int successfulRuns = 0; List<String> failMessgs = new ArrayList<>(); for (Future<List<Object>> testFuture : futureList) { List<Object> result = testFuture.get(); if ((Boolean) result.get(0)) { successfulRuns += 1; } else { @SuppressWarnings("unchecked") List<String> messages = (List<String>) result.get(1); failMessgs.addAll(messages); } } assertEquals("Found failing runs: " + Arrays.deepToString(failMessgs.toArray()), futureList.size(), successfulRuns); } private void expectBaseObjectLoad(Session sessionMock) { String loadBaseObjectHql = "from BaseObject as bobject where bobject.name = :name order by " + "bobject.number"; Query queryObj = new TestQuery<BaseObject>(loadBaseObjectHql, new QueryList<BaseObject>() { @Override public List<BaseObject> list(String string, Map<String, Object> params) throws HibernateException { DocumentReference theDocRef = webUtilsService.resolveDocumentReference((String) params.get( "name")); List<BaseObject> attList = new ArrayList<>(); for (BaseObject templBaseObject : baseObjMap.get(theDocRef)) { BaseObject bObj = createBaseObject(templBaseObject.getNumber(), templBaseObject.getXClassReference()); bObj.setDocumentReference(theDocRef); attList.add(bObj); } return attList; } }); expect(sessionMock.createQuery(eq(loadBaseObjectHql))).andReturn(queryObj).anyTimes(); expectPropertiesLoad(sessionMock); } private void expectPropertiesLoad(Session sessionMock) { String loadPropHql = "select prop.name, prop.classType from BaseProperty as prop where " + "prop.id.id = :id"; Query queryProp = new TestQuery<String[]>(loadPropHql, new QueryList<String[]>() { @Override public List<String[]> list(String string, Map<String, Object> params) throws HibernateException { Integer objId = (Integer) params.get("id"); List<String[]> propList = new ArrayList<>(); for (BaseObject templBaseObject : baseObjMap.get(testDocRef)) { if (objId.equals(templBaseObject.getId())) { for (Object theObj : templBaseObject.getFieldList()) { PropertyInterface theField = (PropertyInterface) theObj; String[] row = new String[2]; row[0] = theField.getName(); row[1] = theField.getClass().getCanonicalName(); propList.add(row); } } } return propList; } }); expect(sessionMock.createQuery(eq(loadPropHql))).andReturn(queryProp).atLeastOnce(); sessionMock.load(isA(PropertyInterface.class), isA(Serializable.class)); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { BaseProperty property = (BaseProperty) getCurrentArguments()[0]; Integer objId = property.getObject().getId(); for (BaseObject templBaseObject : baseObjMap.get(testDocRef)) { if (objId.equals(templBaseObject.getId())) { for (Object theObj : templBaseObject.getFieldList()) { BaseProperty theField = (BaseProperty) theObj; if (theField.getName().equals(property.getName()) && theField.getClass().equals( property.getClass())) { property.setValue(theField.getValue()); } } } } return this; } }).atLeastOnce(); } private void expectLoadEmptyAttachmentList(Session sessionMock) { String loadAttachmentHql = "from XWikiAttachment as attach where attach.docId=:docid"; Query query = new TestQuery<XWikiAttachment>(loadAttachmentHql, new QueryList<XWikiAttachment>() { @Override public List<XWikiAttachment> list(String string, Map<String, Object> params) throws HibernateException { List<XWikiAttachment> attList = new ArrayList<>(); return attList; } }); expect(sessionMock.createQuery(eq(loadAttachmentHql))).andReturn(query).anyTimes(); } private void expectXWikiDocLoad(Session sessionMock, XWikiDocument myDoc) { sessionMock.load(isA(XWikiDocument.class), eq(new Long(myDoc.getId()))); expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { XWikiDocument theDoc = (XWikiDocument) getCurrentArguments()[0]; if (testDocRef.equals(theDoc)) { theDoc.setContent("test Content"); theDoc.setTitle("the test Title"); theDoc.setAuthor("XWiki.testAuthor"); theDoc.setCreationDate(new java.sql.Date(new Date().getTime() - 5000L)); theDoc.setContentUpdateDate(new java.sql.Date(new Date().getTime() - 2000L)); } return this; } }).anyTimes(); } private void createBaseObjects() { DocumentReference testDocRefClone = new DocumentReference(testDocRef.clone()); BaseObject bObj1 = createBaseObject(0, navClassConfig.getMenuNameClassRef(wikiName)); bObj1.setDocumentReference(testDocRefClone); addStringField(bObj1, INavigationClassConfig.MENU_NAME_LANG_FIELD, "de"); addStringField(bObj1, INavigationClassConfig.MENU_NAME_FIELD, "Hause"); BaseObject bObj2 = createBaseObject(1, navClassConfig.getMenuNameClassRef(wikiName)); bObj2.setDocumentReference(testDocRefClone); addStringField(bObj2, INavigationClassConfig.MENU_NAME_LANG_FIELD, "en"); addStringField(bObj2, INavigationClassConfig.MENU_NAME_FIELD, "Home"); BaseObject bObj3 = createBaseObject(0, navClassConfig.getMenuItemClassRef(wikiRef)); bObj3.setDocumentReference(testDocRefClone); addIntField(bObj3, INavigationClassConfig.MENU_POSITION_FIELD, 1); BaseObject bObj4 = createBaseObject(0, pageTypeClassConfig.getPageTypeClassRef(wikiRef)); bObj4.setDocumentReference(testDocRefClone); addStringField(bObj4, IPageTypeClassConfig.PAGE_TYPE_FIELD, "Performance"); List<BaseObject> attList = new Vector<>(Arrays.asList(bObj1, bObj2, bObj3, bObj4)); baseObjMap.put(testDocRefClone, attList); } private void initStorePrepareMultiThreadMocks() throws XWikiException { XWikiStoreInterface store = Utils.getComponent(XWikiStoreInterface.class); defaultContext = (XWikiContext) getContext().clone(); theCacheStore = new XWikiCacheStore(store, defaultContext); defaultMocks = Collections.unmodifiableCollection(getDefaultMocks()); } private class ResetCacheEntryCommand implements Runnable { @Override public void run() { String key = theCacheStore.getKey(wikiName, testFullName, ""); if (theCacheStore.getCache() != null) { theCacheStore.getCache().remove(key); } } } private class LoadXWikiDocCommand extends AbstractXWikiRunnable implements Callable<List<Object>> { private XWikiDocument loadedXWikiDoc; private boolean hasNewContext; private final List<String> messages = new Vector<String>(); private final CountDownLatch startSignal; private final CountDownLatch doneSignal; private boolean startDone = false; public LoadXWikiDocCommand() { startSignal = null; doneSignal = null; } public LoadXWikiDocCommand(CountDownLatch startSignal, CountDownLatch doneSignal) { this.startSignal = startSignal; this.doneSignal = doneSignal; } private ExecutionContext getExecutionContext() { return Utils.getComponent(Execution.class).getContext(); } @Override public List<Object> call() throws Exception { boolean result = false; try { try { hasNewContext = (getExecutionContext() == null); if (hasNewContext) { initExecutionContext(); getExecutionContext().setProperty(EXECUTIONCONTEXT_KEY_MOCKS, defaultMocks); getExecutionContext().setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, defaultContext.clone()); } try { runInternal(); result = testLoadedDocument(); } finally { if (hasNewContext) { // cleanup execution context cleanupExecutionContext(); } } } catch (ExecutionContextException e) { LOGGER.error("Failed to initialize execution context", e); } } catch (Throwable exp) { // anything could happen in the test and we want to catch all failures messages.add("Exception: " + exp.getMessage() + "\\n" + ExceptionUtils.getStackTrace(exp)); } finally { if ((startSignal != null) && !startDone) { startSignal.countDown(); } if (doneSignal != null) { doneSignal.countDown(); } } return Arrays.asList(result, messages); } private boolean testLoadedDocument() { boolean testResult = loadedXWikiDoc != null; if (testResult) { for (BaseObject theTestObj : baseObjMap.get(testDocRef)) { Map<DocumentReference, List<BaseObject>> loadedObjs = loadedXWikiDoc.getXObjects(); if (!loadedObjs.get(theTestObj.getXClassReference()).contains(theTestObj)) { messages.add("Object missing " + theTestObj); testResult = false; } } } return testResult; } @Override public void runInternal() { try { if (startSignal != null) { startSignal.countDown(); startSignal.await(); startDone = true; } XWikiDocument myDoc = new XWikiDocument(testDocRef); try { loadedXWikiDoc = theCacheStore.loadXWikiDoc(myDoc, getContext()); } catch (XWikiException exp) { throw new IllegalStateException(exp); } } catch (Exception exp) { throw new RuntimeException(exp); } } } private final void addIntField(BaseObject bObj, String fieldName, int value) { bObj.setIntValue(fieldName, value); } private final void addStringField(BaseObject bObj, String fieldName, String value) { bObj.setStringValue(fieldName, value); } private final BaseObject createBaseObject(int num, DocumentReference classRef) { BaseObject bObj = new BaseObject(); bObj.setXClassReference(new DocumentReference(classRef.clone())); bObj.setNumber(num); return bObj; } private interface QueryList<T> { public List<T> list(String string, Map<String, Object> params) throws HibernateException; } private class TestQuery<T> extends AbstractQueryImpl { private Query theQueryMock; private QueryList<T> listStub; private Map<String, Object> params; public TestQuery(String queryStr, QueryList<T> listStub) { super(queryStr, FlushMode.AUTO, null, null); this.listStub = listStub; this.params = new HashMap<String, Object>(); theQueryMock = createMock(Query.class); replay(theQueryMock); } @SuppressWarnings("rawtypes") @Override public Iterator iterate() throws HibernateException { return theQueryMock.iterate(); } @Override public ScrollableResults scroll() throws HibernateException { return theQueryMock.scroll(); } @Override public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException { return theQueryMock.scroll(scrollMode); } @SuppressWarnings("unchecked") @Override public List<T> list() throws HibernateException { if (listStub != null) { return listStub.list(getQueryString(), params); } return theQueryMock.list(); } @Override public Query setText(String named, String val) { this.params.put(named, val); return this; } @Override public Query setInteger(String named, int val) { this.params.put(named, new Integer(val)); return this; } @Override public Query setLong(String named, long val) { this.params.put(named, new Long(val)); return this; } @Override public int executeUpdate() throws HibernateException { return theQueryMock.executeUpdate(); } @Override public Query setLockMode(String alias, LockMode lockMode) { return theQueryMock.setLockMode(alias, lockMode); } @SuppressWarnings("rawtypes") @Override protected Map getLockModes() { throw new UnsupportedOperationException("getLockModes not supported"); } } private class TestXWiki extends XWiki { @Override public BaseClass getXClass(DocumentReference documentReference, XWikiContext context) throws XWikiException { // Used to avoid recursive loading of documents if there are recursives usage of classes BaseClass bclass = context.getBaseClass(documentReference); if (bclass == null) { bclass = new BaseClass(); bclass.setDocumentReference(documentReference); context.addBaseClass(bclass); } return bclass; } } }
package com.example.javamavenjunithelloworld; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; /** * Unit test for Hello. * A unit test aims to test all code. */ public class HelloTest { @Test public void testSayHello() { OutputStream os = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(os, true); Hello hi = new Hello(); hi.sayHello(stream); assertThat(os.toString(), is(equalTo(Hello.HELLO + "\r\n"))); } @Test public void testSayHelloAFewTimes() { OutputStream os = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(os, true); Hello hi = new Hello(); hi.setTimes(3); hi.sayHello(stream); // Does it say "Hello!" three times? String goal = Hello.HELLO + "\r\n" + Hello.HELLO + "\r\n" + Hello.HELLO + "\r\n"; assertThat(os.toString(), is(equalTo(goal))); } @Test(expected = IllegalArgumentException.class) public void testIllegalArgumentForHello21() { Hello hi = new Hello(); hi.setTimes(Hello.MAXIMUM_AMOUNT_OF_TIMES + 1); } @Test(expected = IllegalArgumentException.class) public void testIllegalArgumentForHelloNegative() { Hello hi = new Hello(); hi.setTimes(-1); } }
package com.github.davidmoten.rtree.geometry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class PointTest { private static final double PRECISION = 0.000001; @Test public void testCoordinates() { Point point = Geometries.point(1, 2); assertEquals(1, point.x(), PRECISION); assertEquals(2, point.y(), PRECISION); } @Test public void testDistanceToRectangle() { Point p1 = Geometries.point(1, 2); Rectangle r = Geometries.rectangle(4, 6, 4, 6); assertEquals(5, p1.distance(r), PRECISION); } @Test public void testDistanceToPoint() { Point p1 = Geometries.point(1, 2); Point p2 = Geometries.point(4, 6); assertEquals(5, p1.distance(p2), PRECISION); } @Test public void testMbr() { Point p = Geometries.point(1, 2); Rectangle r = Geometries.rectangle(1, 2, 1, 2); assertEquals(r, p.mbr()); } @Test public void testPointIntersectsItself() { Point p = Geometries.point(1, 2); assertTrue(p.distance(p.mbr()) == 0); } @Test public void testIntersectIsFalseWhenPointsDiffer() { Point p1 = Geometries.point(1, 2); Point p2 = Geometries.point(1, 2.000001); assertFalse(p1.distance(p2.mbr()) == 0); } @Test public void testEquality() { Point p1 = Geometries.point(1, 2); Point p2 = Geometries.point(1, 2); assertTrue(p1.equals(p2)); } @Test public void testInequality() { Point p1 = Geometries.point(1, 2); Point p2 = Geometries.point(1, 3); assertFalse(p1.equals(p2)); } @Test public void testInequalityToNull() { Point p1 = Geometries.point(1, 2); assertFalse(p1.equals(null)); } @Test public void testHashCode() { Point p = Geometries.point(1, 2); assertEquals(-1056041056, p.hashCode()); } }
package com.github.dozedoff.commonj.net; import static org.junit.Assert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.net.URL; import java.nio.file.Files; import java.util.LinkedList; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FileLoaderTest { Dummy cut; class Dummy extends FileLoader { // Download parameters private LinkedList<byte[]> data = new LinkedList<byte[]>(); private LinkedList<File> files = new LinkedList<File>(); private LinkedList<URL> urls = new LinkedList<URL>(); public LinkedList<byte[]> getData() { return data; } public LinkedList<File> getFiles() { return files; } public LinkedList<URL> getUrls() { return urls; } public Dummy(File workingDir, int fileQueueWorkers, DataDownloader ddl) { super(workingDir, fileQueueWorkers, ddl); } @Override protected void afterFileDownload(byte[] data, File fullpath, URL url) { this.data.add(data); this.files.add(fullpath); this.urls.add(url); } } @Before public void setUp() throws Exception { DataDownloader ddl = mock(DataDownloader.class); when(ddl.download(any(URL.class))).thenReturn("42".getBytes()); assertThat(ddl, notNullValue()); cut = new Dummy(Files.createTempDirectory("FileLoaderTest").toFile(), 1, ddl); cut.setDownloadSleep(0); } @After public void tearDown() throws Exception { cut.shutdown(); } @Test(timeout=1000) public void testAdd() throws Exception { cut.add(new URL("http://example.com"), "foo"); while(cut.getUrls().size() < 1) { // spin wait } assertThat(cut.getUrls().size(), is(1)); } @Test public void testAddAlreadyInQueue() throws Exception { cut.setDownloadSleep(70); cut.add(new URL("http://example.com"), "foo"); cut.add(new URL("http://example.com"), "foo"); cut.add(new URL("http://example.com"), "foo"); Thread.sleep(200); assertThat(cut.getUrls().size(), is(2)); } @Test public void testSetDownloadSleepShort() throws Exception { cut.setDownloadSleep(10); cut.add(new URL("http://example.com"), "foo"); cut.add(new URL("http://example.com/bar"), "bar"); Thread.sleep(200); assertThat(cut.getUrls().size(), is(2)); } @Test public void testSetDownloadSleepLong() throws Exception { cut.setDownloadSleep(150); cut.add(new URL("http://example.com"), "foo"); cut.add(new URL("http://example.com/bar"), "bar"); Thread.sleep(200); assertThat(cut.getUrls().size(), is(1)); } @Test public void testClearQueue() throws Exception { cut.setDownloadSleep(150); cut.add(new URL("http://example.com"), "foo"); cut.add(new URL("http://example.com/bar"), "bar"); cut.add(new URL("http://example.com/baz"), "baz"); cut.clearQueue(); Thread.sleep(200); assertThat(cut.getUrls().size(), is(1)); } @Test public void testShutdown() throws Exception { cut.setDownloadSleep(150); cut.add(new URL("http://example.com"), "foo"); cut.add(new URL("http://example.com/bar"), "bar"); cut.add(new URL("http://example.com/baz"), "baz"); cut.shutdown(); Thread.sleep(200); assertThat(cut.getUrls().size(), is(1)); } }
package com.github.sd4324530.fastweixin; import com.github.sd4324530.fastweixin.api.*; import com.github.sd4324530.fastweixin.api.config.ApiConfig; import com.github.sd4324530.fastweixin.api.entity.CustomAccount; import com.github.sd4324530.fastweixin.api.entity.Group; import com.github.sd4324530.fastweixin.api.entity.Menu; import com.github.sd4324530.fastweixin.api.entity.MenuButton; import com.github.sd4324530.fastweixin.api.enums.*; import com.github.sd4324530.fastweixin.api.response.*; import com.github.sd4324530.fastweixin.message.Article; import com.github.sd4324530.fastweixin.message.MpNewsMsg; import com.github.sd4324530.fastweixin.util.StrUtil; import org.apache.http.client.utils.DateUtils; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; /** * @author peiyu */ public class FastweixinTest { private static final Logger LOG = LoggerFactory.getLogger(FastweixinTest.class); /* *AppID(ID)wx8c33ff895df5d0d9 *AppSecret()0705aafac0bef944de4c485d71fce900 */ @Test public void test() { String appid = "wx337021cfcc3e32fb"; String secret = "c50a55b106a4fdb8dc5095a1f7fd9cfe"; ApiConfig config = new ApiConfig(appid, secret); // createMenu(config); // getUserList(config); // uploadMedia(config); // downloadMedia(config); // getUserInfo(config); getMenu(config); // addCustomAccount(config); // getOauthPageUrl(config); // getToken(config); // oauthGetUserInfo(config); // ApiConfig config = new ApiConfig(appid, secret, true); // testGetJsApiTicket(config); // testJsApiSign(config); // getUserData(config); // getArticleData(config); // sendAllMessage(config); //getUserGroups(config); // updateGroup(config); // getCallbackIP(config); // getShortUrl(config); // uploadImageMaterial(config); } /** * * * @param config API */ private void createMenu(ApiConfig config) { MenuAPI menuAPI = new MenuAPI(config); menuAPI.deleteMenu(); Menu request = new Menu(); MenuButton main1 = new MenuButton(); main1.setType(MenuType.CLICK); main1.setKey("main1"); main1.setName(""); MenuButton sub1 = new MenuButton(); sub1.setKey("sub1"); sub1.setName(""); sub1.setType(MenuType.VIEW); sub1.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxafb7b8f9457b5d50&redirect_uri=http://121.40.140.41/erhuluanzi/app/testGet&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect"); MenuButton sub2 = new MenuButton(); sub2.setKey("sub2"); sub2.setName(""); sub2.setType(MenuType.CLICK); List<MenuButton> list = new ArrayList<MenuButton>(); list.add(sub1); list.add(sub2); main1.setSubButton(list); List<MenuButton> mainList = new ArrayList<MenuButton>(); mainList.add(main1); request.setButton(mainList); LOG.debug(request.toJsonString()); ResultType resultType = menuAPI.createMenu(request); LOG.debug(resultType.toString()); } /** * * * @param config API */ public void getUserList(ApiConfig config) { UserAPI userAPI = new UserAPI(config); GetUsersResponse users = userAPI.getUsers(null); LOG.debug("user count:{}", users.getCount()); LOG.debug("user total:{}", users.getTotal()); String[] openids = users.getData().getOpenid(); for (String id : openids) { LOG.debug("id:{}", id); } } /** * * * @param config API */ public void getUserInfo(ApiConfig config) { UserAPI userAPI = new UserAPI(config); GetUserInfoResponse userInfo = userAPI.getUserInfo("opZYwt-OS8WFxwU-colRzpu50eOQ"); LOG.debug(userInfo.toJsonString()); } public void uploadMedia(ApiConfig config) { MediaAPI mediaAPI = new MediaAPI(config); UploadMediaResponse response = mediaAPI.uploadMedia(MediaType.IMAGE, new File("E:/123.jpg")); LOG.debug(response.toJsonString()); } public void downloadMedia(ApiConfig config) { MediaAPI mediaAPI = new MediaAPI(config); DownloadMediaResponse response = mediaAPI.downloadMedia("Kw0k6yeKxLaebweRwAUS2x08bcOx2nHMWAXO4s1lMpN_t5Fcsm-svrxe_EfGAgwo"); LOG.debug("error:{}", response.getErrcode()); try { response.writeTo(new FileOutputStream(new File("E:/222.jpg"))); } catch (FileNotFoundException e) { LOG.error("", e); } catch (IOException e) { LOG.error("", e); } } public void getMenu(ApiConfig config) { MenuAPI api = new MenuAPI(config); GetMenuResponse response = api.getMenu(); LOG.debug(":{}", response.toJsonString()); } public void addCustomAccount(ApiConfig config) { CustomAPI customAPI = new CustomAPI(config); CustomAccount customAccount = new CustomAccount(); customAccount.setAccountName("peiyu@i-xiaoshuo"); customAccount.setNickName(""); // customAccount.setPassword("123456"); ResultType resultType = customAPI.addCustomAccount(customAccount); LOG.debug(":{}", resultType.toString()); } public void getOauthPageUrl(ApiConfig config) { OauthAPI oauthAPI = new OauthAPI(config); String pageUrl = oauthAPI.getOauthPageUrl("http://121.40.140.41/erhuluanzi/app/testGet", OauthScope.SNSAPI_BASE, "123"); LOG.debug("pageUrl:{}", pageUrl); } public void getToken(ApiConfig config) { OauthAPI oauthAPI = new OauthAPI(config); OauthGetTokenResponse response = oauthAPI.getToken("041821d373d6a18679cb0b1d8d5cc1ez"); LOG.debug("response:{}", response.toJsonString()); } public void oauthGetUserInfo(ApiConfig config) { OauthAPI oauthAPI = new OauthAPI(config); GetUserInfoResponse response = oauthAPI.getUserInfo("OezXcEiiBSKSxW0eoylIeKoEzhGrPf8vRE3NugAdMy16Em-NimErLsOMfMlZBW0P0wauuYLIzl1soHnV-9CGvQtUYxmd3F6ruwjs_SQNw90aZd_yFlVc85P2FlC01QVNyRktVrSX5zHIMkETyjZojQ", "opZYwt-OS8WFxwU-colRzpu50eOQ"); LOG.debug("response:{}", response.toJsonString()); } public void testGetJsApiTicket(ApiConfig config){ Assert.assertTrue(StrUtil.isNotBlank(config.getJsApiTicket())); if(StrUtil.isNotBlank(config.getJsApiTicket())){ LOG.debug("ok"); } } public void testJsApiSign(ApiConfig config){ // try { // //JS-SDK // //JS-SDK // String exampleResult = "f4d90daf4b3bca3078ab155816175ba34c443a7b"; // Assert.assertEquals(exampleTestStr, exampleResult); // if(exampleResult.equals(exampleTestStr)) // LOG.debug("ok"); // } catch (Exception e) { // e.printStackTrace(); JsAPI jsAPI = new JsAPI(config); GetSignatureResponse response = jsAPI.getSignature("http://mp.weixin.qq.com"); LOG.debug(response.toJsonString()); } public void getUserData(ApiConfig config) { DataCubeAPI dataAPI = new DataCubeAPI(config); String[] format = {"yyyy-MM-dd"}; Date beginDate = DateUtils.parseDate("2015-01-01", format); Date endDate = DateUtils.parseDate("2015-01-07", format); GetUserSummaryResponse response = dataAPI.getUserSummary(beginDate, endDate); GetUserCumulateResponse cumulateResponse = dataAPI.getUserCumulate(beginDate, endDate); LOG.debug(" LOG.debug(response.toJsonString()); LOG.debug(" LOG.debug(cumulateResponse.toJsonString()); } public void getArticleData(ApiConfig config) { DataCubeAPI dataCubeAPI = new DataCubeAPI(config); String[] format = {"yyyy-MM-dd"}; Date beginDate = DateUtils.parseDate("2015-01-25", format); Date endDate = DateUtils.parseDate("2015-01-26", format); GetArticleSummaryResponse articleSummary = dataCubeAPI.getArticleSummary(endDate); GetArticleTotalResponse articleTotal = dataCubeAPI.getArticleTotal(endDate); GetUserReadResponse userRead = dataCubeAPI.getUserRead(beginDate, endDate); GetUserReadHourResponse userReadHour = dataCubeAPI.getUserReadHour(endDate); GetUserShareResponse userShare = dataCubeAPI.getUserShare(beginDate, endDate); GetUserShareHourResponse userShareHour = dataCubeAPI.getUserShareHour(endDate); LOG.debug(" LOG.debug(articleSummary.toJsonString()); LOG.debug(" LOG.debug(articleTotal.toJsonString()); LOG.debug(" LOG.debug(userRead.toJsonString()); LOG.debug(" LOG.debug(userReadHour.toJsonString()); LOG.debug(" LOG.debug(userShare.toJsonString()); LOG.debug(" LOG.debug(userShareHour.toJsonString()); } public void sendAllMessage(ApiConfig config){ MediaAPI mediaAPI = new MediaAPI(config); UploadMediaResponse response = mediaAPI.uploadMedia(MediaType.IMAGE, new File("/Users/jileilei/Desktop/1.jpg")); String media_id = response.getMediaId(); com.github.sd4324530.fastweixin.api.entity.Article article = new com.github.sd4324530.fastweixin.api.entity.Article(); article.setThumbMediaId(media_id); article.setAuthor(""); article.setContentSourceUrl("http: article.setContent(""); article.setDigest(""); article.setShowConverPic(com.github.sd4324530.fastweixin.api.entity.Article.ShowConverPic.NO); UploadMediaResponse uploadMediaResponse = mediaAPI.uploadNews(Arrays.asList(article)); MpNewsMsg mpNewsMsg = new MpNewsMsg(); mpNewsMsg.setMediaId(uploadMediaResponse.getMediaId()); MessageAPI messageAPI = new MessageAPI(config); GetSendMessageResponse messageResponse = messageAPI.sendMessageToUser(mpNewsMsg, true, "0"); LOG.info("Send Message Id is " + messageResponse.getMsgId()); } public void getUserGroups(ApiConfig config){ UserAPI userAPI = new UserAPI(config); GetGroupsResponse response = userAPI.getGroups(); for(Group group : response.getGroups()){ System.out.println("Group id is " + group.getId() + ", name is " + group.getName() + ", count is " + group.getCount()); } } public void updateGroup(ApiConfig config) { UserAPI userAPI = new UserAPI(config); ResultType type = userAPI.updateGroup(103, "3"); System.out.println(type.toString()); } public void getCallbackIP(ApiConfig config) { SystemAPI systemAPI = new SystemAPI(config); List<String> callbackIP = systemAPI.getCallbackIP(); LOG.debug("callbackIP:{}", callbackIP); } public void getShortUrl(ApiConfig config) { SystemAPI systemAPI = new SystemAPI(config); String shortUrl = systemAPI.getShortUrl("https://github.com/sd4324530/fastweixin"); LOG.debug("getShortUrl:{}", shortUrl); } public void uploadImageMaterial(ApiConfig config){ MediaAPI mediaAPI = new MediaAPI(config); UploadMaterialResponse response = mediaAPI.uploadMaterial(MediaType.IMAGE, new File("/Users/jileilei/Desktop/1.jpg"), "1", "1"); System.out.println(response.getMediaId()); } }
/* * This is free and unencumbered software released into the public domain. */ package com.mycompany; import java.lang.String; import java.util.List; import java.util.concurrent.TimeUnit; import io.github.bonigarcia.wdm.WebDriverManager; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.junit.*; import static org.junit.Assert.*; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; /** * This class uses apache selenium firefox driver to drive commander web ui */ public class ApacheFortressDemoSeleniumITCase { public static final String C123 = "123"; public static final String C789 = "789"; public static final String C456 = "456"; private WebDriver driver; private String baseUrl; private boolean acceptNextAlert = true; private StringBuffer verificationErrors = new StringBuffer(); private static final Logger LOG = Logger.getLogger( ApacheFortressDemoSeleniumITCase.class.getName() ); private static final String DRIVER_SYS_PROP = "web.driver"; private enum DriverType { FIREFOX, CHROME } private static DriverType driverType = DriverType.FIREFOX; @Before public void setUp() throws Exception { // Use Set the hostname:port: baseUrl = "http://localhost:8080"; baseUrl += "/apache-fortress-demo"; driver.manage().timeouts().implicitlyWait( 2500, TimeUnit.MILLISECONDS ); } private void info(String msg) { ( ( JavascriptExecutor ) driver ).executeScript( "$(document.getElementById('infoField')).val('" + msg + "');" ); } @BeforeClass public static void setupClass() { String szDriverType = System.getProperty( DRIVER_SYS_PROP ); if( StringUtils.isNotEmpty( szDriverType ) && szDriverType.equalsIgnoreCase( DriverType.CHROME.toString() )) { driverType = DriverType.CHROME; WebDriverManager.chromedriver().setup(); } else { WebDriverManager.firefoxdriver().setup(); } } @Before public void setupTest() { if ( driverType.equals( DriverType.CHROME ) ) { driver = new ChromeDriver(); } else { driver = new FirefoxDriver( ); } driver.manage().window().maximize(); } @After public void teardown() { if (driver != null) { driver.quit(); } } @Test public void testCase1() throws Exception { LOG.info( "Begin FortressDemo2SeleniumITCase" ); driver.get( baseUrl ); // User 123, has access to all pages, Customer 123 data only: login( GlobalIds.USER_123, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_1, GlobalIds.USER_123, GlobalIds.BTN_PAGE_1 ); doActivateTest( GlobalIds.USER_123, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_123, null, C123, C789, false ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_123, C456 ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_123, C789); driver.findElement( By.linkText( GlobalIds.PAGE_2 ) ).click(); doActivateTest( GlobalIds.USER_123, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_123, GlobalIds.ROLE_PAGE1_123, C123, C789, true ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_123, C456); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_123, C789); driver.findElement( By.linkText( GlobalIds.PAGE_3 ) ).click(); doActivateTest( GlobalIds.USER_123, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_123, GlobalIds.ROLE_PAGE2_123, C123, C789, true ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_123, C456); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_123, C789); logout( GlobalIds.USER_123 ); // User 456, has access to all pages, Customer 456 data only: login( GlobalIds.USER_456, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_1, GlobalIds.USER_456, GlobalIds.BTN_PAGE_1 ); doActivateTest( GlobalIds.USER_456, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_456, null, C456, C123, false ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_456, C123); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_456, C789); driver.findElement( By.linkText( GlobalIds.PAGE_2 ) ).click(); doActivateTest( GlobalIds.USER_456, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_456, GlobalIds.ROLE_PAGE1_456, C456, C789, true ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_456, C123); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_456, C789); driver.findElement( By.linkText( GlobalIds.PAGE_3 ) ).click(); doActivateTest( GlobalIds.USER_456, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_456, GlobalIds.ROLE_PAGE2_456, C456, C789, true ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_456, C123); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_456, C789); logout( GlobalIds.USER_456 ); // User 789, has access to all pages, Customer 789 data only: login( GlobalIds.USER_789, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_1, GlobalIds.USER_789, GlobalIds.BTN_PAGE_1 ); doActivateTest( GlobalIds.USER_789, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_789, null, C789, C123, false ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_789, C123); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_789, C456); driver.findElement( By.linkText( GlobalIds.PAGE_2 ) ).click(); doActivateTest( GlobalIds.USER_789, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_789, GlobalIds.ROLE_PAGE1_789, C789, C456, true ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_789, C123); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_789, C456); driver.findElement( By.linkText( GlobalIds.PAGE_3 ) ).click(); doActivateTest( GlobalIds.USER_789, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_789, GlobalIds.ROLE_PAGE2_789, C789, C123, true ); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_789, C123); TUtils.sleep( 1 ); doNegativeDataTest( GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_789, C456); logout( GlobalIds.USER_789 ); // User 1 has access to Page 1, all customer data with DSD constraints applied:: login( GlobalIds.USER_1, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_1, GlobalIds.USER_1, GlobalIds.BTN_PAGE_1 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_1 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_1 ); activateRole( GlobalIds.ROLE_PAGE1_789 ); doActivateTest( GlobalIds.USER_1, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_123, GlobalIds.ROLE_PAGE1_789, C123, C789, true ); doActivateTest( GlobalIds.USER_1, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_456, GlobalIds.ROLE_PAGE1_123, C456, C123, true ); doActivateTest( GlobalIds.USER_1, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_789, GlobalIds.ROLE_PAGE1_456, C789, C456, true ); logout( GlobalIds.USER_1 ); // User 1 123 has access to Page 1, Customer 123 only: login( GlobalIds.USER_1_123, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_1, GlobalIds.USER_1_123, GlobalIds.BTN_PAGE_1 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_1_123 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_1_123 ); doActivateTest( GlobalIds.USER_1_123, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_123, null, C123, C789, false ); logout( GlobalIds.USER_1_123 ); // User 1 456 has access to Page 1, Customer 456 only:: login( GlobalIds.USER_1_456, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_1, GlobalIds.USER_1_456, GlobalIds.BTN_PAGE_1 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_1_456 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_1_456 ); doActivateTest( GlobalIds.USER_1_456, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_456, null, C456, C123, false ); logout( GlobalIds.USER_1_456 ); // User 1 789 has access to Page 1, Customer 789 only:: login( GlobalIds.USER_1_789, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_1, GlobalIds.USER_1_789, GlobalIds.BTN_PAGE_1 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_1_789 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_1_789 ); doActivateTest( GlobalIds.USER_1_789, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_789, null, C789, C123, false ); logout( GlobalIds.USER_1_789 ); // User 2 has access to Page 2, all customer data with DSD constraints applied:: login( GlobalIds.USER_2, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_2, GlobalIds.USER_2, GlobalIds.BTN_PAGE_2 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_2 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_2 ); activateRole( GlobalIds.ROLE_PAGE2_789 ); doActivateTest( GlobalIds.USER_2, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_123, GlobalIds.ROLE_PAGE2_789, C123, C789, true ); doActivateTest( GlobalIds.USER_2, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_456, GlobalIds.ROLE_PAGE2_123, C456, C123, true ); doActivateTest( GlobalIds.USER_2, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_789, GlobalIds.ROLE_PAGE2_456, C789, C456, true ); logout( GlobalIds.USER_2 ); // User 2 123 has access to Page 2, Customer 123 only:: login( GlobalIds.USER_2_123, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_2, GlobalIds.USER_2_123, GlobalIds.BTN_PAGE_2 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_2_123 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_2_123 ); doActivateTest( GlobalIds.USER_2_123, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_123, null, C123, C789, false ); logout( GlobalIds.USER_2_123 ); // User 2 456 has access to Page 2, Customer 456 only:: login( GlobalIds.USER_2_456, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_2, GlobalIds.USER_2_456, GlobalIds.BTN_PAGE_2 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_2_456 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_2_456 ); doActivateTest( GlobalIds.USER_2_456, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_456, null, C456, C123, false ); logout( GlobalIds.USER_2_456 ); // User 2 789 has access to Page 2, Customer 789 only:: login( GlobalIds.USER_2_789, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_2, GlobalIds.USER_2_789, GlobalIds.BTN_PAGE_2 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_2_789 ); doNegativeLinkTest( GlobalIds.PAGE_3, GlobalIds.USER_2_789 ); doActivateTest( GlobalIds.USER_2_789, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_789, null, C789, C123, false ); logout( GlobalIds.USER_1_789 ); // User 3 has access to Page 3, all customer data with DSD constraints applied:: login( GlobalIds.USER_3, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_3, GlobalIds.USER_3, GlobalIds.BTN_PAGE_3 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_3 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_3 ); activateRole( GlobalIds.ROLE_PAGE3_789 ); doActivateTest( GlobalIds.USER_3, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_123, GlobalIds.ROLE_PAGE3_789, C123, C789, true ); doActivateTest( GlobalIds.USER_3, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_456, GlobalIds.ROLE_PAGE3_123, C456, C123, true ); doActivateTest( GlobalIds.USER_3, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_789, GlobalIds.ROLE_PAGE3_456, C789, C456, true ); logout( GlobalIds.USER_3 ); // User 3 123 has access to Page 3, Customer 123 only:: login( GlobalIds.USER_3_123, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_3, GlobalIds.USER_3_123, GlobalIds.BTN_PAGE_3 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_3_123 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_3_123 ); doActivateTest( GlobalIds.USER_3_123, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_123, null, C123, C789, false ); logout( GlobalIds.USER_3_123 ); // User 3 456 has access to Page 3, Customer 456 only:: login( GlobalIds.USER_3_456, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_3, GlobalIds.USER_3_456, GlobalIds.BTN_PAGE_3 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_3_456 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_3_456 ); doActivateTest( GlobalIds.USER_3_456, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_456, null, C456, C123, false ); logout( GlobalIds.USER_3_456 ); // User 3 789 has access to Page 3, Customer 789 only:: login( GlobalIds.USER_3_789, "password" ); TUtils.sleep( 1 ); doNegativeButtonTests( GlobalIds.PAGE_3, GlobalIds.USER_3_789, GlobalIds.BTN_PAGE_3 ); doNegativeLinkTest( GlobalIds.PAGE_1, GlobalIds.USER_3_789 ); doNegativeLinkTest( GlobalIds.PAGE_2, GlobalIds.USER_3_789 ); doActivateTest( GlobalIds.USER_3_789, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_789, null, C789, C123, false ); logout( GlobalIds.USER_1_789 ); // SuperUser has access to all pages and all customer data without restriction: login( GlobalIds.SUPER_USER, "password"); TUtils.sleep( 1 ); doPositiveButtonTests( GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1 ); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_SUPER, C123); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_SUPER, C456); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_SUPER, C789); TUtils.sleep( 1 ); doPositiveButtonTests( GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2 ); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_SUPER, C123); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_SUPER, C456); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_SUPER, C789); TUtils.sleep( 1 ); doPositiveButtonTests( GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3 ); doPositiveDataTest( GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_SUPER, C123); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_SUPER, C456); TUtils.sleep( 1 ); doPositiveDataTest( GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_SUPER, C789); TUtils.sleep( 1 ); logout( GlobalIds.SUPER_USER ); // Poweruser has access to all pages, and all customer data with DSD constraints applied: login( GlobalIds.POWER_USER, "password"); TUtils.sleep( 1 ); driver.findElement( By.linkText( GlobalIds.PAGE_1 ) ).click(); activateRole( GlobalIds.ROLE_PAGE3_789 ); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_123, GlobalIds.ROLE_PAGE3_789, C123, C456, true ); driver.findElement( By.linkText( GlobalIds.PAGE_2 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_123, GlobalIds.ROLE_PAGE1_123, C123, C456, true ); driver.findElement( By.linkText( GlobalIds.PAGE_3 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_123, GlobalIds.ROLE_PAGE2_123, C123, C456, true ); driver.findElement( By.linkText( GlobalIds.PAGE_1 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_456, GlobalIds.ROLE_PAGE3_123, C456, C789, true ); driver.findElement( By.linkText( GlobalIds.PAGE_2 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_456, GlobalIds.ROLE_PAGE1_456, C456, C789, true ); driver.findElement( By.linkText( GlobalIds.PAGE_3 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_456, GlobalIds.ROLE_PAGE2_456, C456, C789, true ); driver.findElement( By.linkText( GlobalIds.PAGE_1 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_1, GlobalIds.BTN_PAGE_1, GlobalIds.ROLE_PAGE1_789, GlobalIds.ROLE_PAGE3_456, C789, C123, true ); driver.findElement( By.linkText( GlobalIds.PAGE_2 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_2, GlobalIds.BTN_PAGE_2, GlobalIds.ROLE_PAGE2_789, GlobalIds.ROLE_PAGE1_789, C789, C123, true ); driver.findElement( By.linkText( GlobalIds.PAGE_3 ) ).click(); doActivateTest( GlobalIds.POWER_USER, GlobalIds.PAGE_3, GlobalIds.BTN_PAGE_3, GlobalIds.ROLE_PAGE3_789, GlobalIds.ROLE_PAGE2_789, C789, C123, true ); logout( GlobalIds.POWER_USER ); } private void doActivateTest( String userId, String page, String buttonPage, String activateRole, String deactivateRole, String authorizedData, String unauthorizedData, boolean isDeactivateTest ) { info( "Do Role Activation Test role: " + activateRole ); doNegativeButtonTest( userId, page, GlobalIds.ADD ); if(isDeactivateTest) { // Now activate ROLE: activateRole(activateRole); // Make sure the pop-up is correct: if(!processError( GlobalIds.DSD_ERROR_MSG )) fail("doActivate Button Test 2 Failed: " + buttonPage); driver.findElement( By.linkText( page ) ).click(); doNegativeButtonTest( userId, page, buttonPage ); // Now deactivate ROLE_PAGE1: ( ( JavascriptExecutor ) driver ).executeScript( "$(document.getElementById('" + GlobalIds.ACTIVE_ROLES + "')).val('" + deactivateRole + "');" ); driver.findElement( By.name( GlobalIds.ROLES_DEACTIVATE ) ).click(); TUtils.sleep( 1 ); } // Now active ROLE: activateRole(activateRole); //TUtils.sleep( 1 ); // Click the buttons on page 2 doPositiveButtonTests( null, buttonPage ); TUtils.sleep( 1 ); doNegativeDataTest(page, buttonPage, activateRole, unauthorizedData); driver.findElement( By.linkText( page ) ).click(); TUtils.sleep( 1 ); doPositiveDataTest(buttonPage, activateRole, authorizedData); } private void doPositiveDataTest(String buttonPage, String activateRole, String data) { info( "Postive Data test for role: " + activateRole + ", customer: " + data ); driver.findElement( By.id( GlobalIds.CUSTOMER_EF_ID ) ).clear(); driver.findElement( By.id( GlobalIds.CUSTOMER_EF_ID ) ).sendKeys( data ); driver.findElement( By.name( buttonPage + "." + GlobalIds.SEARCH ) ).click(); } private void doNegativeDataTest(String page, String buttonPage, String activateRole, String data) { info( "Negative Data test for role: " + activateRole + ", customer: " + data ); driver.findElement( By.id( GlobalIds.CUSTOMER_EF_ID ) ).clear(); driver.findElement( By.id( GlobalIds.CUSTOMER_EF_ID ) ).sendKeys( data ); driver.findElement( By.name( buttonPage + "." + GlobalIds.SEARCH ) ).click(); if(!processError( GlobalIds.AUTHZ_ERROR_MSG )) fail("doActivateTest Unauthorized data Test Failed: " + buttonPage + "." + GlobalIds.SEARCH); driver.findElement( By.linkText( page ) ).click(); } private void doPositiveButtonTests( String linkName, String pageId ) { info( "Postive Button test for " + linkName ); if(linkName != null) driver.findElement( By.linkText( linkName ) ).click(); TUtils.sleep( 1 ); // Click the buttons on the page doPositiveButtonTest(pageId, GlobalIds.ADD, pageId + "." + GlobalIds.ADD); doPositiveButtonTest(pageId, GlobalIds.UPDATE, pageId + "." + GlobalIds.UPDATE); doPositiveButtonTest(pageId, GlobalIds.DELETE, pageId + "." + GlobalIds.DELETE); doPositiveButtonTest(pageId, GlobalIds.SEARCH, pageId + "." + GlobalIds.SEARCH); } private void doNegativeButtonTests( String linkName, String userId, String pageId ) { info( "Negative Button test for user: " + userId + ", linkName: " + linkName ); if(linkName != null) driver.findElement( By.linkText( linkName ) ).click(); doNegativeButtonTest( userId, pageId, GlobalIds.ADD ); doNegativeButtonTest( userId, pageId, GlobalIds.UPDATE ); doNegativeButtonTest( userId, pageId, GlobalIds.DELETE ); doNegativeButtonTest( userId, pageId, GlobalIds.SEARCH ); } private boolean processPopup(String text) { boolean textFound = false; try { Alert alert = driver.switchTo ().alert (); //alert is present LOG.info( "Button Pressed:" + alert.getText() ); if(alert.getText().contains( text )) textFound = true; alert.accept(); } catch ( NoAlertPresentException n) { //Alert isn't present } return textFound; } private boolean processError(String text) { boolean textFound = false;
package hudson.plugins.warnings.parser; import static org.junit.Assert.*; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import org.junit.Test; import hudson.plugins.analysis.util.model.FileAnnotation; import hudson.plugins.analysis.util.model.Priority; /** * Tests the class {@link PyLintParser}. */ public class PylintParserTest extends ParserTester { private static final String WARNING_TYPE = Messages._Warnings_PyLint_ParserName().toString(Locale.ENGLISH); /** * Parses a txt file, containing 3 warnings. * * @throws IOException * if the file could not be read */ @Test public void pyLintTest() throws IOException { Collection<FileAnnotation> warnings = new PyLintParser().parse(openFile()); assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 6, warnings.size()); Iterator<FileAnnotation> iterator = warnings.iterator(); FileAnnotation warning; warning = iterator.next(); checkWarning(warning, 3, "Line too long (85/80)", "trunk/src/python/cachedhttp.py", WARNING_TYPE, "C", Priority.NORMAL); warning = iterator.next(); checkWarning(warning, 28, "Invalid name \"seasonCount\" (should match [a-z_][a-z0-9_]{2,30}$)", "trunk/src/python/tv.py", WARNING_TYPE, "C0103", Priority.NORMAL); warning = iterator.next(); checkWarning(warning, 35, "Missing docstring", "trunk/src/python/tv.py", WARNING_TYPE, "C0111", Priority.NORMAL); warning = iterator.next(); checkWarning(warning, 39, "Method should have \"self\" as first argument", "trunk/src/python/tv.py", WARNING_TYPE, "E0213", Priority.HIGH); warning = iterator.next(); checkWarning(warning, 5, "Unable to import \"deadbeef\"", "trunk/src/python/tv.py", WARNING_TYPE, "F0401", Priority.HIGH); warning = iterator.next(); checkWarning(warning, 39, "Dangerous default value \"[]\" as argument", "trunk/src/python/tv.py", WARNING_TYPE, "W0102", Priority.HIGH); } @Override protected String getWarningsFile() { return "pyLint.txt"; } }
package hudson.plugins.git.browser; import hudson.EnvVars; import hudson.model.TaskListener; import hudson.plugins.git.GitChangeLogParser; import hudson.plugins.git.GitChangeSet; import hudson.plugins.git.GitChangeSet.Path; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Random; import static org.junit.Assert.*; import org.junit.Test; public class BitbucketServerTest { private static final String BITBUCKET_URL = "http://bitbucket-server:7990/USER/REPO"; private final BitbucketServer bitbucketServer = new BitbucketServer(BITBUCKET_URL); @Test public void testGetUrl() throws IOException { assertEquals(String.valueOf(bitbucketServer.getUrl()), BITBUCKET_URL + "/"); } @Test public void testGetUrlForRepoWithTrailingSlash() throws IOException { assertEquals(String.valueOf(new BitbucketServer(BITBUCKET_URL + "/").getUrl()), BITBUCKET_URL + "/"); } @Test public void testGetChangeSetLinkGitChangeSet() throws Exception { final URL changeSetLink = bitbucketServer.getChangeSetLink(createChangeSet("rawchangelog")); assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString()); } @Test public void testGetDiffLinkPath() throws Exception { final HashMap<String, Path> pathMap = createPathMap("rawchangelog"); final String path1Str = "src/main/java/hudson/plugins/git/browser/GithubWeb.java"; final Path path1 = pathMap.get(path1Str); assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#" + path1Str, bitbucketServer.getDiffLink(path1).toString()); final String path2Str = "src/test/java/hudson/plugins/git/browser/GithubWebTest.java"; final Path path2 = pathMap.get(path2Str); assertEquals(BITBUCKET_URL + "/commits/396fc230a3db05c427737aa5c2eb7856ba72b05d#" + path2Str, bitbucketServer.getDiffLink(path2).toString()); final String path3Str = "src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file"; final Path path3 = pathMap.get(path3Str); assertNull("Do not return a diff link for added files.", bitbucketServer.getDiffLink(path3)); } @Test public void testGetFileLinkPath() throws Exception { final HashMap<String,Path> pathMap = createPathMap("rawchangelog"); final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java"); final URL fileLink = bitbucketServer.getFileLink(path); assertEquals(BITBUCKET_URL + "/browse/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink)); } @Test public void testGetFileLinkPathForDeletedFile() throws Exception { final HashMap<String,Path> pathMap = createPathMap("rawchangelog-with-deleted-file"); final Path path = pathMap.get("bar"); final URL fileLink = bitbucketServer.getFileLink(path); assertEquals(BITBUCKET_URL + "/browse/bar", String.valueOf(fileLink)); } private final Random random = new Random(); private GitChangeSet createChangeSet(String rawchangelogpath) throws Exception { /* Use randomly selected git client implementation since the client implementation should not change result */ GitClient gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(new File(".")).using(random.nextBoolean() ? "Default" : "jgit").getClient(); final GitChangeLogParser logParser = new GitChangeLogParser(gitClient, false); final List<GitChangeSet> changeSetList = logParser.parse(BitbucketServerTest.class.getResourceAsStream(rawchangelogpath)); return changeSetList.get(0); } private HashMap<String, Path> createPathMap(final String changelog) throws Exception { final HashMap<String, Path> pathMap = new HashMap<>(); final Collection<Path> changeSet = createChangeSet(changelog).getPaths(); for (final Path path : changeSet) { pathMap.put(path.getPath(), path); } return pathMap; } }
package org.jboss.msc.registry; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.ImmediateValue; import org.junit.Test; import static org.junit.Assert.fail; /** * Test case used to ensure functionality for the Resolver. * * @author John Bailey */ public class ServiceRegistryTestCase { @Test public void testResolvable() throws Exception { final BatchBuilder builder = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); builder.addService(ServiceName.of("7"), Service.NULL).addDependencies(ServiceName.of("11"), ServiceName.of("8")); builder.addService(ServiceName.of("5"), Service.NULL).addDependencies(ServiceName.of("11")); builder.addService(ServiceName.of("3"), Service.NULL).addDependencies(ServiceName.of("11"), ServiceName.of("9")); builder.addService(ServiceName.of("11"), Service.NULL).addDependencies(ServiceName.of("2"), ServiceName.of("9"), ServiceName.of("10")); builder.addService(ServiceName.of("8"), Service.NULL).addDependencies(ServiceName.of("9")); builder.addService(ServiceName.of("2"), Service.NULL); builder.addService(ServiceName.of("9"), Service.NULL); builder.addService(ServiceName.of("10"), Service.NULL); builder.install(); } @Test public void testResolvableWithPreexistingDeps() throws Exception { final ServiceRegistry registry = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()); final BatchBuilder builder1 = registry.batchBuilder(); builder1.addService(ServiceName.of("2"), Service.NULL); builder1.addService(ServiceName.of("9"), Service.NULL); builder1.addService(ServiceName.of("10"), Service.NULL); builder1.install(); final BatchBuilder builder2 = registry.batchBuilder(); builder2.addService(ServiceName.of("7"), Service.NULL).addDependencies(ServiceName.of("11"), ServiceName.of("8")); builder2.addService(ServiceName.of("5"), Service.NULL).addDependencies(ServiceName.of("11")); builder2.addService(ServiceName.of("3"), Service.NULL).addDependencies(ServiceName.of("11"), ServiceName.of("9")); builder2.addService(ServiceName.of("11"), Service.NULL).addDependencies(ServiceName.of("2"), ServiceName.of("9"), ServiceName.of("10")); builder2.addService(ServiceName.of("8"), Service.NULL).addDependencies(ServiceName.of("9")); builder2.install(); } @Test public void testMissingDependency() throws Exception { try { final BatchBuilder builder = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); builder.addService(ServiceName.of("7"), Service.NULL).addDependencies(ServiceName.of("11"), ServiceName.of("8")); builder.addService(ServiceName.of("5"), Service.NULL).addDependencies(ServiceName.of("11")); builder.addService(ServiceName.of("3"), Service.NULL).addDependencies(ServiceName.of("11"), ServiceName.of("9")); builder.addService(ServiceName.of("11"), Service.NULL).addDependencies(ServiceName.of("2"), ServiceName.of("9"), ServiceName.of("10")); builder.addService(ServiceName.of("8"), Service.NULL).addDependencies(ServiceName.of("9")); builder.addService(ServiceName.of("2"), Service.NULL).addDependencies(ServiceName.of("1")); builder.addService(ServiceName.of("9"), Service.NULL); builder.addService(ServiceName.of("10"), Service.NULL); builder.install(); fail("Should have thrown missing dependency exception"); } catch (ServiceRegistryException expected) { } } @Test public void testCircular() throws Exception { try { final BatchBuilder builder = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); builder.addService(ServiceName.of("7"), Service.NULL).addDependencies(ServiceName.of("5")); builder.addService(ServiceName.of("5"), Service.NULL).addDependencies(ServiceName.of("11")); builder.addService(ServiceName.of("11"), Service.NULL).addDependencies(ServiceName.of("7")); builder.install(); fail("SHould have thrown circular dependency exception"); } catch (ServiceRegistryException expected) { } } @Test public void testMonster() throws Exception { BatchBuilder batch = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); final int totalServiceDefinitions = 100000; for (int i = 0; i < totalServiceDefinitions; i++) { List<ServiceName> deps = new ArrayList<ServiceName>(); int numDeps = Math.min(10, totalServiceDefinitions - i - 1); for (int j = 1; j < numDeps + 1; j++) { deps.add(ServiceName.of(("test" + (i + j)).intern())); } batch.addService(ServiceName.of(("test" + i).intern()), Service.NULL).addDependencies(deps.toArray(new ServiceName[deps.size()])); } long start = System.currentTimeMillis(); batch.install(); long end = System.currentTimeMillis(); System.out.println("Time: " + (end - start)); batch = null; System.gc(); Thread.sleep(10000); System.out.println(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); } @Test public void testLargeNoDeps() throws Exception { BatchBuilder batch = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); final int totalServiceDefinitions = 10000; for (int i = 0; i < totalServiceDefinitions; i++) { batch.addService(ServiceName.of("test" + i), Service.NULL); } long start = System.currentTimeMillis(); batch.install(); long end = System.currentTimeMillis(); System.out.println("Time: " + (end - start)); } public void testBasicInjection() throws Exception { BatchBuilder batch = ServiceRegistry.Factory.create(ServiceContainer.Factory.create()).batchBuilder(); final TestObject testObject = new TestObject(); final TestObjectService service = new TestObjectService(testObject); final Object injectedValue = new Object(); final Object otherInjectedValue = new Object(); final Field field = TestObject.class.getDeclaredField("test"); field.setAccessible(true); final BatchServiceBuilder<TestObject> serviceBuilder = batch.addService(ServiceName.of("testService"), service); serviceBuilder.addInjection(injectedValue).toFieldValue(new ImmediateValue<Field>(field)); serviceBuilder.addInjection(otherInjectedValue).toProperty("other"); batch.install(); } public static class TestObject { private Object test; private Object other; public Object getOther() { return other; } public void setOther(Object other) { this.other = other; } @Override public String toString() { return "TestObject{" + "test=" + test + ", other=" + other + '}'; } } private static class TestObjectService implements Service<TestObject> { private final TestObject value; private TestObjectService(TestObject value) { this.value = value; } @Override public void start(StartContext context) throws StartException { System.out.println("Injected: " + value); } @Override public void stop(StopContext context) { } @Override public TestObject getValue() throws IllegalStateException { return null; } } }
package se.bjurr.gitchangelog.internal.git; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.reverse; import static com.google.common.collect.Maps.newTreeMap; import static org.assertj.core.api.Assertions.assertThat; import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.REF_MASTER; import static se.bjurr.gitchangelog.api.GitChangelogApiConstants.ZERO_COMMIT; import java.io.File; import java.util.List; import java.util.Map; import org.eclipse.jgit.lib.ObjectId; import org.junit.Before; import org.junit.Test; import se.bjurr.gitchangelog.internal.git.model.GitCommit; import se.bjurr.gitchangelog.internal.git.model.GitTag; import com.google.common.base.Optional; import com.google.common.io.Resources; public class GitRepoTest { private static final String FIRST_COMMIT_HASH = "a1aa5ff"; private static final String FIRST_COMMIT_HASH_FULL = "a1aa5ff5b625e63aa5ad7b59367ec7f75658afb8"; private static final String TAG_1_0_HASH = "01484ce71bbc76e1af75ebb07a52844145ce99dc"; private File gitRepoFile; @Before public void before() { this.gitRepoFile = new File(Resources.getResource("github-issues.json").getFile()); } @Test public void testThatCommitsBetweenCommitAndCommitCanBeListed() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId firstCommit = gitRepo.getCommit(FIRST_COMMIT_HASH_FULL); ObjectId lastCommit = gitRepo.getCommit("e3766e2d4bc6d206475c5d2ed96b3f967a6e157e"); List<GitCommit> diff = gitRepo.getGitRepoData(firstCommit, lastCommit, "No tag", Optional.of(".*tag-in-test-feature$")).getGitCommits(); assertThat(diff).isNotEmpty(); assertThat(reverse(diff).get(0).getHash()) .as("first") .startsWith("5aaeb90"); assertThat(diff.get(0).getHash()) .as("last") .startsWith("e3766e2d4bc6d20"); } @Test public void testThatCommitsBetweenCommitAndReferenceCanBeListed() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId firstCommit = gitRepo.getCommit(ZERO_COMMIT); ObjectId lastCommit = gitRepo.getRef(REF_MASTER); List<GitCommit> diff = gitRepo.getGitRepoData(firstCommit, lastCommit, "No tag", Optional.of(".*tag-in-test-feature$")).getGitCommits(); assertThat(diff.size()).isGreaterThan(10); assertThat(reverse(diff).get(0).getHash()).startsWith("5aae"); } @Test public void testThatCommitsBetweenZeroCommitAndCommitCanBeListed() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId firstCommit = gitRepo.getCommit(ZERO_COMMIT); ObjectId lastCommit = gitRepo.getCommit(TAG_1_0_HASH); GitRepoData gitRepoData = gitRepo.getGitRepoData(firstCommit, lastCommit, "No tag", Optional.of(".*tag-in-test-feature$")); assertThat(gitRepoData.getGitCommits()).as("Commits in first release.") .hasSize(5); assertThat(gitRepoData.getGitTags()).as("Tags in first release.") .hasSize(1); assertThat(reverse(gitRepoData.getGitCommits()).get(0).getHash()) .startsWith("5aae"); } @Test public void testThatCommitsCanBeRetrieved() throws Exception { GitRepo gitRepo = getGitRepo(); assertThat(gitRepo.getCommit(FIRST_COMMIT_HASH_FULL)).isNotNull(); assertThat(gitRepo.getCommit(FIRST_COMMIT_HASH_FULL).name()).isEqualTo(FIRST_COMMIT_HASH_FULL); assertThat(gitRepo.getCommit(TAG_1_0_HASH)).isNotNull(); assertThat(gitRepo.getCommit(TAG_1_0_HASH).name()).isEqualTo(TAG_1_0_HASH); } @Test public void testThatCommitsFromMergeNotInFromAreIncluded() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId from = gitRepo.getCommit("c5d37f5"); ObjectId to = gitRepo.getCommit("bb2f35b"); GitRepoData gitRepoData = gitRepo.getGitRepoData(from, to, "No tag", Optional.<String> absent()); List<String> noTagNames = messages(gitRepoData.getGitCommits()); assertThat(noTagNames) .containsExactly( "Merge branch 'test-feature' into test", "Some stuff in test-feature"); } @Test public void testThatCommitsSecondReleaseCommitCanBeListed() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId firstRelease = gitRepo.getRef("refs/tags/1.0"); ObjectId secondRelease = gitRepo.getRef("refs/tags/1.1"); List<GitCommit> diff = gitRepo.getGitRepoData(firstRelease, secondRelease, "No tag", Optional.of(".*tag-in-test-feature$")).getGitCommits(); assertThat(diff) .as("Commits in second release from 1.0.") .hasSize(8); assertThat(diff.get(7).getHash()) .startsWith("3950c64"); assertThat(diff.get(0).getHash()) .startsWith(secondRelease.getName().substring(0, 10)); ObjectId firstCommit = gitRepo.getCommit(ZERO_COMMIT); diff = gitRepo.getGitRepoData(firstCommit, secondRelease, "No tag", Optional.of(".*tag-in-test-feature$")) .getGitCommits(); assertThat(diff) .as("Commits in second release from zero commit.") .hasSize(13); assertThat(diff.get(6).getHash()) .startsWith("ba9d"); assertThat(diff.get(0).getHash()) .startsWith(secondRelease.getName().substring(0, 10)); } @Test public void testThatRepoCanBeFound() throws Exception { GitRepo gitRepo = getGitRepo(); assertThat(gitRepo).isNotNull(); } @Test public void testThatShortHashCanBeUsedToFindCommits() throws Exception { GitRepo gitRepo = getGitRepo(); assertThat(gitRepo.getCommit("5a50ad3672c9f5a273c04711ed9b3daebf1f9b07").getName()) .isEqualTo("5a50ad3672c9f5a273c04711ed9b3daebf1f9b07"); assertThat(gitRepo.getCommit("5a50ad3").getName()) .isEqualTo("5a50ad3672c9f5a273c04711ed9b3daebf1f9b07"); } @Test public void testThatTagCanBeIgnored() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId from = gitRepo.getCommit("87c0d72888961712d4d63dd6298c24c1133a6b51"); ObjectId to = gitRepo.getRef("test"); GitRepoData gitRepoData = gitRepo.getGitRepoData(from, to, "No tag", Optional.of(".*tag-in-test-feature$")); Map<String, GitTag> perTag = perTag(gitRepoData.getGitTags()); assertThat(gitRepoData.getGitTags()) .hasSize(1); assertThat(gitRepoData.getGitTags()) .hasSize(1); assertThat(perTag.keySet()) .hasSize(1) .contains("No tag"); GitTag noTagTag = perTag.get("No tag"); List<String> noTagTagMessages = messages(noTagTag.getGitCommits()); assertThat(noTagTagMessages) .containsExactly( "Some stuff in test again", "Merge branch 'test-feature' into test", "Some stuff in test-feature", "some stuff in test branch"); } @Test public void testThatTagInFeatureBranchAndMainBranchIsNotMixed() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId from = gitRepo.getCommit("87c0d72888961712d4d63dd6298c24c1133a6b51"); ObjectId to = gitRepo.getRef("test"); GitRepoData gitRepoData = gitRepo.getGitRepoData(from, to, "No tag", Optional.<String> absent()); Map<String, GitTag> perTag = perTag(gitRepoData.getGitTags()); assertThat(perTag.keySet()) .hasSize(2) .containsExactly( "No tag", "refs/tags/tag-in-test-feature"); GitTag noTagTag = perTag.get("No tag"); List<String> noTagNames = messages(noTagTag.getGitCommits()); assertThat(noTagNames) .containsExactly( "Some stuff in test again", "Merge branch 'test-feature' into test", "some stuff in test branch"); GitTag testFeatureTag = perTag.get("refs/tags/tag-in-test-feature"); List<String> testFeatureTagMessages = messages(testFeatureTag.getGitCommits()); assertThat(testFeatureTagMessages) .containsExactly( "Some stuff in test-feature"); } @Test public void testThatTagInFeatureBranchDoesNotIncludeNewUnmergedCommitsInItsMainBranchWhenFeatureLaterMerged() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId from = gitRepo.getCommit("090e7f4"); ObjectId to = gitRepo.getCommit("8371342"); GitRepoData gitRepoData = gitRepo.getGitRepoData(from, to, "No tag", Optional.<String> absent()); Map<String, GitTag> perTag = perTag(gitRepoData.getGitTags()); assertThat(perTag.keySet()) .hasSize(1) .containsExactly( "No tag"); GitTag noTagTag = perTag.get("No tag"); List<String> noTagNames = messages(noTagTag.getGitCommits()); assertThat(noTagNames) .containsExactly( "Some stuff in test again", "Merge branch 'test-feature' into test", "some stuff in test branch"); } @Test public void testThatTagsCanBeListed() throws Exception { GitRepo gitRepo = getGitRepo(); GitRepoData gitRepoData = gitRepo.getGitRepoData(gitRepo.getCommit(ZERO_COMMIT), gitRepo.getRef(REF_MASTER), "No tag", Optional.of(".*tag-in-test-feature$")); assertThat(gitRepoData.getGitTags()).isNotEmpty(); } @Test public void testThatZeroCommitCanBeRetrieved() throws Exception { GitRepo gitRepo = getGitRepo(); ObjectId firstCommit = gitRepo.getCommit(ZERO_COMMIT); assertThat(firstCommit).as(gitRepo.toString()).isNotNull(); assertThat(firstCommit.name()).as(gitRepo.toString()).startsWith(FIRST_COMMIT_HASH); } private GitRepo getGitRepo() throws Exception { return new GitRepo(this.gitRepoFile); } private List<String> messages(List<GitCommit> gitCommits) { List<String> messages = newArrayList(); for (GitCommit gc : gitCommits) { messages.add(gc.getMessage().trim()); } return messages; } private Map<String, GitTag> perTag(List<GitTag> gitTags) { Map<String, GitTag> map = newTreeMap(); for (GitTag gitTag : gitTags) { map.put(gitTag.getName(), gitTag); } return map; } }
package seedu.todo.controllers; import java.util.HashMap; import java.util.Map; import org.junit.*; import static org.junit.Assert.*; import seedu.todo.commons.exceptions.UnmatchedQuotesException; import seedu.todo.controllers.concerns.Tokenizer; public class ControllerConcernsTests { private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("tokenType1", new String[] {"token11"}); tokenDefinitions.put("tokenType2", new String[] {"token21", "token22"}); tokenDefinitions.put("tokenType3", new String[] {"token31", "token32", "token33"}); return tokenDefinitions; } @Test public void tokenizer_no_matches() throws Exception { String input = "abcdefg hijklmnop"; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertTrue(output.isEmpty()); } @Test public void tokenizer_empty_string() throws Exception { String input = ""; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertTrue(output == null); } @Test public void tokenizer_single_match() throws Exception { String input = "token11 answer"; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertEquals(output.get("tokenType1")[0], "token11"); assertEquals(output.get("tokenType1")[1], "answer"); } @Test public void tokenizer_empty_match() throws Exception { String input = "token11 token21"; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertEquals(output.get("tokenType1")[0], "token11"); assertEquals(output.get("tokenType1")[1], null); assertEquals(output.get("tokenType2")[0], "token21"); assertEquals(output.get("tokenType2")[1], null); } @Test(expected=UnmatchedQuotesException.class) public void tokenizer_unmatched_quotes() throws Exception { String input = "\"\"\""; Tokenizer.tokenize(getTokenDefinitions(), input); } }
package seedu.todo.controllers; import java.util.HashMap; import java.util.Map; import org.junit.*; import static org.junit.Assert.*; import seedu.todo.commons.exceptions.UnmatchedQuotesException; import seedu.todo.controllers.concerns.Tokenizer; public class ControllerConcernsTests { private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("tokenType1", new String[] {"token11"}); tokenDefinitions.put("tokenType2", new String[] {"token21", "token22"}); tokenDefinitions.put("tokenType3", new String[] {"token31", "token32", "token33"}); return tokenDefinitions; } @Test public void tokenizer_no_matches() throws Exception { String input = "abcdefg hijklmnop"; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertTrue(output.isEmpty()); } @Test public void tokenizer_empty_string() throws Exception { String input = ""; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertTrue(output == null); } @Test public void tokenizer_single_match() throws Exception { String input = "token11 answer"; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertEquals(output.get("tokenType1")[0], "token11"); assertEquals(output.get("tokenType1")[1], "answer"); } @Test public void tokenizer_empty_match() throws Exception { String input = "alamak token11 token21"; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertEquals(output.get("tokenType1")[0], "token11"); assertEquals(output.get("tokenType1")[1], null); assertEquals(output.get("tokenType2")[0], "token21"); assertEquals(output.get("tokenType2")[1], null); } @Test public void tokenizer_match_quotes() throws Exception { String input = "\"token11\" answer"; Map<String, String[]> output = Tokenizer.tokenize(getTokenDefinitions(), input); assertTrue(output.isEmpty()); } @Test(expected=UnmatchedQuotesException.class) public void tokenizer_unmatched_quotes() throws Exception { String input = "\"\"\""; Tokenizer.tokenize(getTokenDefinitions(), input); } }
package org.sfm.utils; import java.io.Closeable; import java.io.IOException; import java.util.Iterator; public class CloseableIterator<E> implements Iterator<E>, Closeable { private final Iterator<E> delegate; private final Closeable resource; public CloseableIterator(Iterator<E> delegate, Closeable resource) { this.resource = resource; this.delegate = delegate; } @Override public void close() throws IOException { resource.close(); } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public void remove() { delegate.remove(); } @Override public E next() { return delegate.next(); } }
public class SelectionSort { /** * Selection Sort is an in-place comparison sort. * It has O(n^2) time complexity. */ public int[] selection_sort(int[] arr) { int min, temp; /* find the min element in the unsorted array */ for (int i = 0; i < arr.length; i++) { /* assume the min is the first element */ min = i; /* test against elements after i to find the smallest */ for (int j = i+1; j < arr.length; j++) { /* if this element is less, then it is the new minimum */ if (arr[j] < arr[min]) { /* found new minimum; remember its index */ min = j; } } if (min != i) { /* swap i and min */ temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } } return arr; } }
package org.lwjgl.demo.opengl.raytracing; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import org.lwjgl.demo.util.Camera; import org.lwjgl.demo.util.Matrix4f; import org.lwjgl.demo.util.Vector3f; import org.lwjgl.glfw.*; import org.lwjgl.opengl.GLContext; import org.lwjgl.system.libffi.Closure; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static java.lang.Math.*; import static org.lwjgl.demo.util.IOUtil.*; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL21.*; import static org.lwjgl.opengl.GL30.*; import static org.lwjgl.opengl.GL31.glDrawArraysInstanced; import static org.lwjgl.opengl.GL33.glVertexAttribDivisor; import static org.lwjgl.opengl.GL40.*; import static org.lwjgl.opengl.GL42.*; import static org.lwjgl.opengl.GL43.*; import static org.lwjgl.system.MathUtil.*; import static org.lwjgl.system.MemoryUtil.*; /** * Photon mapping using cubemap array textures. * <p> * This demo uses a cube map array texture to hold a "photon map" for each of * the boxes in the scene. * <p> * A compute shader is used to shoot light rays into the scene and whenever they * hit a box the texel coordinate is computed and the "photon" is stored in the * corresponding face and layer of the cube map array image. * <p> * Afterwards, the scene is rasterized and the cube map array is sampled via a * samplerCubeArray. The boxes are rendered via hardware instancing and the * layer of the cube map array (i.e. the cube map for that particular box * instance) is obtained via the gl_InstanceID. * * @author Kai Burjack */ public class PhotonMappingDemo { /** * The boxes for both rasterization and ray tracing. */ private static Vector3f[] boxes = { new Vector3f(-5.0f, -0.1f, -5.0f), new Vector3f(5.0f, 0.0f, 5.0f), new Vector3f(-0.5f, 0.0f, -0.5f), new Vector3f(0.5f, 1.0f, 0.5f), new Vector3f(-5.1f, 0.0f, -5.0f), new Vector3f(-5.0f, 5.0f, 5.0f), new Vector3f(5.0f, 0.0f, -5.0f), new Vector3f(5.1f, 5.0f, 5.0f), new Vector3f(-5.0f, 0.0f, -5.1f), new Vector3f(5.0f, 5.0f, -5.0f), new Vector3f(-5.0f, 0.0f, 5.0f), new Vector3f(5.0f, 5.0f, 5.1f), new Vector3f(-5.0f, 5.0f, -5.0f), new Vector3f(5.0f, 5.1f, 5.0f) }; /** * The resolution of the photon map for each box. */ private static int PHOTON_MAP_SIZE = 64; /** * The number of photons to trace when doing a single photonmap computation. */ private static int PHOTON_TRACE_PER_FRAME = 256 * 256; private long window; private int width = 1024; private int height = 768; private boolean resetFramebuffer = true; private int photonMapTexture; private int photonTraceProgram; private int rasterProgram; private int vaoScene; private int ssbo; private int timeUniform; private int lightCenterPositionUniform; private int lightRadiusUniform; private int boxesSsboBinding; private int photonMapsBinding; private int viewMatrixUniform; private int projectionMatrixUniform; private int workGroupSizeX; private int workGroupSizeY; private Camera camera; private float mouseDownX; private float mouseX; private boolean mouseDown; private float currRotationAboutY = 0.0f; private float rotationAboutY = 0.8f; private long firstTime; private float lightRadius = 0.4f; private Vector3f tmpVector = new Vector3f(); private Vector3f cameraLookAt = new Vector3f(0.0f, 0.5f, 0.0f); private Vector3f cameraUp = new Vector3f(0.0f, 1.0f, 0.0f); private ByteBuffer matrixByteBuffer = BufferUtils.createByteBuffer(4 * 16); private FloatBuffer matrixByteBufferFloatView = matrixByteBuffer.asFloatBuffer(); private Vector3f lightCenterPosition = new Vector3f(2.5f, 2.9f, 3); GLFWErrorCallback errCallback; GLFWKeyCallback keyCallback; GLFWFramebufferSizeCallback fbCallback; GLFWCursorPosCallback cpCallback; GLFWMouseButtonCallback mbCallback; Closure debugProc; static { /* * Tell LWJGL that we only want 4.3 functionality. */ System.setProperty("org.lwjgl.opengl.maxVersion", "4.3"); } private void init() throws IOException { glfwSetErrorCallback(errCallback = new GLFWErrorCallback() { private GLFWErrorCallback delegate = Callbacks.errorCallbackPrint(System.err); @Override public void invoke(int error, long description) { if (error == GLFW_VERSION_UNAVAILABLE) System.err .println("This demo requires OpenGL 4.3 or higher. The HybridDemo33 version works on OpenGL 3.3 or higher."); delegate.invoke(error, description); } @Override public void release() { delegate.release(); super.release(); } }); if (glfwInit() != GL_TRUE) throw new IllegalStateException("Unable to initialize GLFW"); glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_VISIBLE, GL_FALSE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); window = glfwCreateWindow(width, height, "Photon Mapping Demo - compute shader (with SSBO) + raster (with instancing)", NULL, NULL); if (window == NULL) { throw new AssertionError("Failed to create the GLFW window"); } glfwSetKeyCallback(window, keyCallback = new GLFWKeyCallback() { @Override public void invoke(long window, int key, int scancode, int action, int mods) { if (action != GLFW_RELEASE) return; if (key == GLFW_KEY_ESCAPE) { glfwSetWindowShouldClose(window, GL_TRUE); } } }); glfwSetFramebufferSizeCallback(window, fbCallback = new GLFWFramebufferSizeCallback() { @Override public void invoke(long window, int width, int height) { if (width > 0 && height > 0 && (PhotonMappingDemo.this.width != width || PhotonMappingDemo.this.height != height)) { PhotonMappingDemo.this.width = width; PhotonMappingDemo.this.height = height; PhotonMappingDemo.this.resetFramebuffer = true; } } }); glfwSetCursorPosCallback(window, cpCallback = new GLFWCursorPosCallback() { @Override public void invoke(long window, double x, double y) { PhotonMappingDemo.this.mouseX = (float) x; if (mouseDown) { } } }); glfwSetMouseButtonCallback(window, mbCallback = new GLFWMouseButtonCallback() { @Override public void invoke(long window, int button, int action, int mods) { if (action == GLFW_PRESS) { PhotonMappingDemo.this.mouseDownX = PhotonMappingDemo.this.mouseX; PhotonMappingDemo.this.mouseDown = true; } else if (action == GLFW_RELEASE) { PhotonMappingDemo.this.mouseDown = false; PhotonMappingDemo.this.rotationAboutY = PhotonMappingDemo.this.currRotationAboutY; } } }); ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); glfwSetWindowPos(window, (GLFWvidmode.width(vidmode) - width) / 2, (GLFWvidmode.height(vidmode) - height) / 2); glfwMakeContextCurrent(window); glfwSwapInterval(0); glfwShowWindow(window); GLContext ctx = GLContext.createFromCurrent(); debugProc = ctx.setupDebugMessageCallback(System.err); /* Create all needed GL resources */ createPhotonMapTexture(); createPhotonTraceProgram(); initPhotonTraceProgram(); createRasterProgram(); initRasterProgram(); createSceneSSBO(); createSceneVao(); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); /* Setup camera */ camera = new Camera(); firstTime = System.nanoTime(); } /** * Create a Shader Storage Buffer Object which will hold our boxes to be * read by our Compute Shader. */ private void createSceneSSBO() { this.ssbo = glGenBuffers(); glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo); ByteBuffer ssboData = BufferUtils.createByteBuffer(4 * (4 + 4) * boxes.length / 2); FloatBuffer fv = ssboData.asFloatBuffer(); for (int i = 0; i < boxes.length; i += 2) { Vector3f min = boxes[i]; Vector3f max = boxes[i + 1]; fv.put(min.x).put(min.y).put(min.z).put(0.0f); fv.put(max.x).put(max.y).put(max.z).put(0.0f); } glBufferData(GL_SHADER_STORAGE_BUFFER, ssboData, GL_STATIC_DRAW); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } /** * Creates a VAO for the scene. */ private void createSceneVao() { int vao = glGenVertexArrays(); /* Create vertex data */ int vbo = glGenBuffers(); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); ByteBuffer bb = BufferUtils.createByteBuffer(4 * (3 + 3) * 6 * 6); FloatBuffer fv = bb.asFloatBuffer(); triangulateUnitBox(fv); glBufferData(GL_ARRAY_BUFFER, bb, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, false, 4 * (3 + 3), 0L); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, false, 4 * (3 + 3), 4 * 3); glBindBuffer(GL_ARRAY_BUFFER, 0); /* Create per instance data (position and size of box) */ int ivbo = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, ivbo); bb = BufferUtils.createByteBuffer(4 * (3 + 3) * boxes.length); fv = bb.asFloatBuffer(); for (int i = 0; i < boxes.length; i += 2) { Vector3f min = boxes[i]; Vector3f max = boxes[i + 1]; fv.put((max.x + min.x) / 2.0f).put((max.y + min.y) / 2.0f).put((max.z + min.z) / 2.0f); fv.put((max.x - min.x) / 2.0f).put((max.y - min.y) / 2.0f).put((max.z - min.z) / 2.0f); } glBufferData(GL_ARRAY_BUFFER, bb, GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, false, 4 * (3 + 3), 0L); glVertexAttribDivisor(2, 1); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, false, 4 * (3 + 3), 4 * 3); glVertexAttribDivisor(3, 1); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); this.vaoScene = vao; } /** * Write the vertices (position and normal) of an axis-aligned unit box into * the provided {@link FloatBuffer}. * * @param fv * the {@link FloatBuffer} receiving the vertex position and * normal */ private static void triangulateUnitBox(FloatBuffer fv) { /* Front face */ fv.put(-1.0f).put(-1.0f).put(1.0f).put(0.0f).put(0.0f).put(1.0f); fv.put(1.0f).put(-1.0f).put(1.0f).put(0.0f).put(0.0f).put(1.0f); fv.put(1.0f).put(1.0f).put(1.0f).put(0.0f).put(0.0f).put(1.0f); fv.put(1.0f).put(1.0f).put(1.0f).put(0.0f).put(0.0f).put(1.0f); fv.put(-1.0f).put(1.0f).put(1.0f).put(0.0f).put(0.0f).put(1.0f); fv.put(-1.0f).put(-1.0f).put(1.0f).put(0.0f).put(0.0f).put(1.0f); /* Back face */ fv.put(1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(0.0f).put(-1.0f); fv.put(-1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(0.0f).put(-1.0f); fv.put(-1.0f).put(1.0f).put(-1.0f).put(0.0f).put(0.0f).put(-1.0f); fv.put(-1.0f).put(1.0f).put(-1.0f).put(0.0f).put(0.0f).put(-1.0f); fv.put(1.0f).put(1.0f).put(-1.0f).put(0.0f).put(0.0f).put(-1.0f); fv.put(1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(0.0f).put(-1.0f); /* Left face */ fv.put(-1.0f).put(-1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(0.0f); fv.put(-1.0f).put(-1.0f).put(1.0f).put(-1.0f).put(0.0f).put(0.0f); fv.put(-1.0f).put(1.0f).put(1.0f).put(-1.0f).put(0.0f).put(0.0f); fv.put(-1.0f).put(1.0f).put(1.0f).put(-1.0f).put(0.0f).put(0.0f); fv.put(-1.0f).put(1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(0.0f); fv.put(-1.0f).put(-1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(0.0f); /* Right face */ fv.put(1.0f).put(-1.0f).put(1.0f).put(1.0f).put(0.0f).put(0.0f); fv.put(1.0f).put(-1.0f).put(-1.0f).put(1.0f).put(0.0f).put(0.0f); fv.put(1.0f).put(1.0f).put(-1.0f).put(1.0f).put(0.0f).put(0.0f); fv.put(1.0f).put(1.0f).put(-1.0f).put(1.0f).put(0.0f).put(0.0f); fv.put(1.0f).put(1.0f).put(1.0f).put(1.0f).put(0.0f).put(0.0f); fv.put(1.0f).put(-1.0f).put(1.0f).put(1.0f).put(0.0f).put(0.0f); /* Top face */ fv.put(-1.0f).put(1.0f).put(1.0f).put(0.0f).put(1.0f).put(0.0f); fv.put(1.0f).put(1.0f).put(1.0f).put(0.0f).put(1.0f).put(0.0f); fv.put(1.0f).put(1.0f).put(-1.0f).put(0.0f).put(1.0f).put(0.0f); fv.put(1.0f).put(1.0f).put(-1.0f).put(0.0f).put(1.0f).put(0.0f); fv.put(-1.0f).put(1.0f).put(-1.0f).put(0.0f).put(1.0f).put(0.0f); fv.put(-1.0f).put(1.0f).put(1.0f).put(0.0f).put(1.0f).put(0.0f); /* Bottom face */ fv.put(-1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(-1.0f).put(0.0f); fv.put(1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(-1.0f).put(0.0f); fv.put(1.0f).put(-1.0f).put(1.0f).put(0.0f).put(-1.0f).put(0.0f); fv.put(1.0f).put(-1.0f).put(1.0f).put(0.0f).put(-1.0f).put(0.0f); fv.put(-1.0f).put(-1.0f).put(1.0f).put(0.0f).put(-1.0f).put(0.0f); fv.put(-1.0f).put(-1.0f).put(-1.0f).put(0.0f).put(-1.0f).put(0.0f); } /** * Create a shader object from the given classpath resource. * * @param resource * the class path * @param type * the shader type * * @return the shader object id * * @throws IOException */ private static int createShader(String resource, int type) throws IOException { int shader = glCreateShader(type); ByteBuffer source = ioResourceToByteBuffer(resource, 8192); PointerBuffer strings = BufferUtils.createPointerBuffer(1); IntBuffer lengths = BufferUtils.createIntBuffer(1); strings.put(0, source); lengths.put(0, source.remaining()); glShaderSource(shader, strings, lengths); glCompileShader(shader); int compiled = glGetShaderi(shader, GL_COMPILE_STATUS); String shaderLog = glGetShaderInfoLog(shader); if (!shaderLog.trim().isEmpty()) { System.err.println(shaderLog); } if (compiled == 0) { throw new AssertionError("Could not compile shader"); } return shader; } private void createPhotonTraceProgram() throws IOException { int program = glCreateProgram(); int cshader = createShader("demo/raytracing/photonmap.glsl", GL_COMPUTE_SHADER); int random = createShader("demo/raytracing/random.glsl", GL_COMPUTE_SHADER); glAttachShader(program, cshader); glAttachShader(program, random); glLinkProgram(program); int linked = glGetProgrami(program, GL_LINK_STATUS); String programLog = glGetProgramInfoLog(program); if (!programLog.trim().isEmpty()) { System.err.println(programLog); } if (linked == 0) { throw new AssertionError("Could not link program"); } this.photonTraceProgram = program; } private void initPhotonTraceProgram() { glUseProgram(photonTraceProgram); IntBuffer workGroupSize = BufferUtils.createIntBuffer(3); glGetProgram(photonTraceProgram, GL_COMPUTE_WORK_GROUP_SIZE, workGroupSize); workGroupSizeX = workGroupSize.get(0); workGroupSizeY = workGroupSize.get(1); timeUniform = glGetUniformLocation(photonTraceProgram, "time"); lightCenterPositionUniform = glGetUniformLocation(photonTraceProgram, "lightCenterPosition"); glUniform3f(lightCenterPositionUniform, lightCenterPosition.x, lightCenterPosition.y, lightCenterPosition.z); lightRadiusUniform = glGetUniformLocation(photonTraceProgram, "lightRadius"); glUniform1f(lightRadiusUniform, lightRadius); /* Query the binding point of the SSBO */ /* * First, obtain the "resource index" used for further queries on that * resource. */ int boxesResourceIndex = glGetProgramResourceIndex(photonTraceProgram, GL_SHADER_STORAGE_BLOCK, "Boxes"); IntBuffer props = BufferUtils.createIntBuffer(1); IntBuffer params = BufferUtils.createIntBuffer(1); props.put(0, GL_BUFFER_BINDING); /* Now query the "BUFFER_BINDING" of that resource */ glGetProgramResource(photonTraceProgram, GL_SHADER_STORAGE_BLOCK, boxesResourceIndex, props, null, params); boxesSsboBinding = params.get(0); /* Query the "image binding point" of the photonMaps uniform image2D */ int loc = glGetUniformLocation(photonTraceProgram, "photonMaps"); glGetUniform(photonTraceProgram, loc, params); photonMapsBinding = params.get(0); glUseProgram(0); } /** * Create the cubemap texture array for our photon map. */ private void createPhotonMapTexture() { this.photonMapTexture = glGenTextures(); glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, photonMapTexture); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexStorage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 1, GL_RG16F, PHOTON_MAP_SIZE, PHOTON_MAP_SIZE, 6 * boxes.length / 2); /* * Clear the first level of the texture with black without allocating * host memory by using a buffer object and uploading it via PBO to the * texture. I would rather use clearTexImage but that is only available * in 4.4. */ int texBuffer = glGenBuffers(); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, texBuffer); int size = 2 * 2 * PHOTON_MAP_SIZE * PHOTON_MAP_SIZE * 6 * boxes.length / 2; glBufferData(GL_PIXEL_UNPACK_BUFFER, size, (ByteBuffer) null, GL_STATIC_DRAW); glClearBufferSubData(GL_PIXEL_UNPACK_BUFFER, GL_RG16F, 0, size, GL_RG, GL_HALF_FLOAT, (ByteBuffer) null); glTexSubImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, 0, 0, 0, PHOTON_MAP_SIZE, PHOTON_MAP_SIZE, 6 * boxes.length / 2, GL_RG, GL_HALF_FLOAT, 0L); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glDeleteBuffers(texBuffer); glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0); } /** * Create the raster shader. * * @throws IOException */ private void createRasterProgram() throws IOException { int program = glCreateProgram(); int vshader = createShader("demo/raytracing/rasterPhotonMap.vs", GL_VERTEX_SHADER); int fshader = createShader("demo/raytracing/rasterPhotonMap.fs", GL_FRAGMENT_SHADER); glAttachShader(program, vshader); glAttachShader(program, fshader); glBindAttribLocation(program, 0, "vertexPosition"); glBindAttribLocation(program, 1, "vertexNormal"); glBindAttribLocation(program, 2, "boxCenter"); glBindAttribLocation(program, 3, "boxHalfSize"); glBindFragDataLocation(program, 0, "color"); glLinkProgram(program); int linked = glGetProgrami(program, GL_LINK_STATUS); String programLog = glGetProgramInfoLog(program); if (!programLog.trim().isEmpty()) { System.err.println(programLog); } if (linked == 0) { throw new AssertionError("Could not link program"); } this.rasterProgram = program; } private void initRasterProgram() { glUseProgram(rasterProgram); viewMatrixUniform = glGetUniformLocation(rasterProgram, "viewMatrix"); projectionMatrixUniform = glGetUniformLocation(rasterProgram, "projectionMatrix"); int cubeMapsUniform = glGetUniformLocation(rasterProgram, "cubeMaps"); glUniform1i(cubeMapsUniform, 0); glUseProgram(0); } private void update() { if (mouseDown) { /* * If mouse is down, compute the camera rotation based on mouse * cursor location. */ currRotationAboutY = rotationAboutY + (mouseX - mouseDownX) * 0.01f; } else { currRotationAboutY = rotationAboutY; } /* Rotate camera about Y axis. */ tmpVector.set((float) sin(-currRotationAboutY) * 3.0f, 2.0f, (float) cos(-currRotationAboutY) * 3.0f); camera.setLookAt(tmpVector, cameraLookAt, cameraUp); if (resetFramebuffer) { camera.setFrustumPerspective(60.0f, (float) width / height, 0.01f, 100.0f); resetFramebuffer = false; } } /** * Set the given {@link Matrix4f matrix} as a 4x4 uniform in the active * shader. * * @param location * the uniform location of the mat4 uniform * @param value * the {@link Matrix4f matrix} to set * @param transpose * whether the matrix should be transposed (automatic row-major * to column-major transposition is done automatically on top of * that) */ private void matrixUniform(int location, Matrix4f value, boolean transpose) { matrixByteBufferFloatView.put(value.m00).put(value.m10).put(value.m20).put(value.m30).put(value.m01) .put(value.m11).put(value.m21).put(value.m31).put(value.m02).put(value.m12).put(value.m22) .put(value.m32).put(value.m03).put(value.m13).put(value.m23).put(value.m33); matrixByteBufferFloatView.rewind(); glUniformMatrix4f(location, 1, transpose, matrixByteBuffer); } /** * Trace some rays from the light. */ private void trace() { glUseProgram(photonTraceProgram); glDisable(GL_DEPTH_TEST); long thisTime = System.nanoTime(); float elapsedSeconds = (thisTime - firstTime) / 1E9f; glUniform1f(timeUniform, elapsedSeconds); /* Bind photon maps */ glBindImageTexture(photonMapsBinding, photonMapTexture, 0, true, 0, GL_READ_WRITE, GL_RG16F); /* Bind the SSBO containing our boxes */ glBindBufferBase(GL_SHADER_STORAGE_BUFFER, boxesSsboBinding, ssbo); /* Compute appropriate invocation dimension. */ int invocationsPerDimension = (int) Math.sqrt(PHOTON_TRACE_PER_FRAME); int worksizeX = mathRoundPoT(invocationsPerDimension); int worksizeY = mathRoundPoT(invocationsPerDimension); /* Invoke the compute shader. */ glDispatchCompute(worksizeX / workGroupSizeX, worksizeY / workGroupSizeY, 1); glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT); /* Reset bindings. */ glBindBufferBase(GL_SHADER_STORAGE_BUFFER, boxesSsboBinding, 0); glBindImageTexture(photonMapsBinding, 0, 0, true, 0, GL_READ_WRITE, GL_RG16F); glUseProgram(0); } /** * Rasterize the boxes by sampling the traced photon maps and present the * final image on the screen/viewport. */ private void raster() { glEnable(GL_DEPTH_TEST); glUseProgram(rasterProgram); /* Update matrices in shader */ Matrix4f viewMatrix = camera.getViewMatrix(); matrixUniform(viewMatrixUniform, viewMatrix, false); Matrix4f projMatrix = camera.getProjectionMatrix(); matrixUniform(projectionMatrixUniform, projMatrix, false); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, photonMapTexture); glBindVertexArray(vaoScene); glDrawArraysInstanced(GL_TRIANGLES, 0, 6 * 6, boxes.length / 2); glBindVertexArray(0); glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0); glUseProgram(0); } private void loop() { while (glfwWindowShouldClose(window) == GL_FALSE) { glfwPollEvents(); glViewport(0, 0, width, height); update(); trace(); raster(); glfwSwapBuffers(window); } } private void run() { try { init(); loop(); if (debugProc != null) debugProc.release(); errCallback.release(); keyCallback.release(); fbCallback.release(); cpCallback.release(); mbCallback.release(); glfwDestroyWindow(window); } catch (Throwable t) { t.printStackTrace(); } finally { glfwTerminate(); } } public static void main(String[] args) { new PhotonMappingDemo().run(); } }
package uk.gov.dvla.domain; import java.lang.String; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Indexed; @Entity(value = "drivers", noClassnameStored = true) public class Driver extends Person { @Indexed(unique = true) private String currentDriverNumber = null; private List<DriverNumber> driverNumberHistory; private List<DriverFlag> flags; private Licence licence; private DriverStatus status; private DriverStatedFlags driverStatedFlags; private Date firstProvisionalDate; private Date disqualifiedUntilDate; private String HROType; private List<ConductCase> conductCases; private List<Disqualification> disqualifications; private List<TachoCard> tachoCards; private List<CertificateOfProfessionalCompetence> CPCs; private List<DriverQualificationCard> DQCs; private List<TestPass> testPasses; private List<String> errorCodes; private boolean nslInCorruptedRange; private List<LicenceToken> licenceTokens; public void addErrorCode(String code) { if (null == errorCodes) { errorCodes = new ArrayList<String>(); } errorCodes.add(code); } public void addDriverFlag(DriverFlag flag) { if(null == flags) { flags = new ArrayList<DriverFlag>(); } flags.add(flag); } public void addTestPass(TestPass testPass) { if(null == testPasses) { testPasses = new ArrayList<TestPass>(); } testPasses.add(testPass); } public String getCurrentDriverNumber() { return currentDriverNumber; } public void setCurrentDriverNumber(String currentDriverNumber) { this.currentDriverNumber = currentDriverNumber; } public List<DriverNumber> getDriverNumberHistory() { return driverNumberHistory; } public void setDriverNumberHistory(List<DriverNumber> driverNumberHistory) { this.driverNumberHistory = driverNumberHistory; } public List<DriverFlag> getFlags() { return flags; } public void setFlags(List<DriverFlag> flags) { this.flags = flags; } public Licence getLicence() { return licence; } public void setLicence(Licence licence) { this.licence = licence; } public DriverStatus getStatus() { return status; } public void setStatus(DriverStatus status) { this.status = status; } public DriverStatedFlags getDriverStatedFlags() { return driverStatedFlags; } public void setDriverStatedFlags(DriverStatedFlags driverStatedFlags) { this.driverStatedFlags = driverStatedFlags; } public Date getFirstProvisionalDate() { return firstProvisionalDate; } public void setFirstProvisionalDate(Date firstProvisionalDate) { this.firstProvisionalDate = firstProvisionalDate; } public Date getDisqualifiedUntilDate() { return disqualifiedUntilDate; } public void setDisqualifiedUntilDate(Date disqualifiedUntilDate) { this.disqualifiedUntilDate = disqualifiedUntilDate; } public String getHROType() { return HROType; } public void setHROType(String HROType) { this.HROType = HROType; } public List<ConductCase> getConductCases() { return conductCases; } public void setConductCases(List<ConductCase> conductCases) { this.conductCases = conductCases; } public List<Disqualification> getDisqualifications() { return disqualifications; } public void setDisqualifications(List<Disqualification> disqualifications) { this.disqualifications = disqualifications; } public List<TachoCard> getTachoCards() { return tachoCards; } public void setTachoCards(List<TachoCard> tachoCards) { this.tachoCards = tachoCards; } public List<CertificateOfProfessionalCompetence> getCPCs() { return CPCs; } public void setCPCs(List<CertificateOfProfessionalCompetence> CPCs) { this.CPCs = CPCs; } public List<DriverQualificationCard> getDQCs() { return DQCs; } public void setDQCs(List<DriverQualificationCard> DQCs) { this.DQCs = DQCs; } public List<TestPass> getTestPasses() { return testPasses; } public void setTestPasses(List<TestPass> testPasses) { this.testPasses = testPasses; } public List<String> getErrorCodes() { return errorCodes; } public void setErrorCodes(List<String> errorCodes) { this.errorCodes = errorCodes; } public boolean isNslInCorruptedRange() { return nslInCorruptedRange; } public void setNslInCorruptedRange(boolean nslInCorruptedRange) { this.nslInCorruptedRange = nslInCorruptedRange; } public TestPass getTestPassForEntitlement(Entitlement ent) { ArrayList<TestPass> possibleTestPasses = new ArrayList<TestPass>(); if(testPasses == null) { return null; } for(TestPass testPass : testPasses) { if(testPass.getEntitlementType().equals(ent.getCode())) { possibleTestPasses.add(testPass); } } if(possibleTestPasses.size() == 0) { return null; } else { //Ensure the most recent is returned Collections.reverse(possibleTestPasses); return possibleTestPasses.get(0); } } public List<LicenceToken> getLicenceTokens() { return licenceTokens; } public void setLicenceTokens(List<LicenceToken> licenceTokens) { this.licenceTokens = licenceTokens; } }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { private static final int DISTRICT_COUNT = 10; private static final int MAX_DISTRICT_SIZE = 650000; private static final int MIN_DISTRICT_SIZE = 550000; private static int democratVoteTarget = 10; private static int republicanVotes = 0; private static County[] counties; private static int[] districtSizes; private static LinkedHashSet<County> unusedCounties; private static LinkedHashSet<County>[] districts; private static PrintWriter writer; private static int[] districtMargins = new int[DISTRICT_COUNT]; private static double startTime; private static long numberOfCountiesSelected = 0; private static HashSet<LinkedHashSet<County>>[] attemptedDistricts = new HashSet[DISTRICT_COUNT]; public static void main(String[] args) { if (args.length < 1) { System.err.println("Please enter an input file path"); return; } FileInputStream inStream; BufferedReader reader; try { inStream = new FileInputStream(args[0]); reader = new BufferedReader(new InputStreamReader(inStream)); writer = new PrintWriter(args[0] + ".output"); } catch (Exception e) { System.err.println("File could not be opened"); e.printStackTrace(); return; } int numCounties = 0; try { String line = reader.readLine(); numCounties = Integer.parseInt(line); counties = new County[numCounties]; for (int i = 0; i < numCounties; i++) { counties[i] = new County(); counties[i].name = reader.readLine(); counties[i].republicanCount = Integer.parseInt(reader.readLine()); counties[i].democratCount = Integer.parseInt(reader.readLine()); counties[i].totalPopulation = counties[i].democratCount + counties[i].republicanCount; line = reader.readLine(); while (!line.equals("`")) { counties[i].adjacentCountiesIndexes.add(Integer.parseInt(line) - 1); line = reader.readLine(); } } reader.close(); for (int i = 0; i < counties.length; i++) { counties[i].adjacentCounties = new County[counties[i].adjacentCountiesIndexes.size()]; for (int j = 0; j < counties[i].adjacentCountiesIndexes.size(); j++) { int k = counties[i].adjacentCountiesIndexes.get(j); counties[i].adjacentCounties[j] = counties[k]; } counties[i].margin = counties[i].democratCount - counties[i].republicanCount; } } catch (IOException e) { System.err.println("An error occurred"); e.printStackTrace(); return; } districts = new LinkedHashSet[DISTRICT_COUNT]; for (int i = 0; i < districts.length; i++) { districts[i] = new LinkedHashSet<County>(numCounties, 1); } unusedCounties = new LinkedHashSet<County>(numCounties, 1); for (County c : counties) { unusedCounties.add(c); } districtSizes = new int[DISTRICT_COUNT]; for (int i = 0; i < attemptedDistricts.length; i++) { attemptedDistricts[i] = new HashSet<LinkedHashSet<County>>(); for (int j = 0; j < attemptedDistricts[i].size(); j++) { attemptedDistricts[i].add(new LinkedHashSet<County>(numCounties, 1)); } } // Manually choose districts unusedCounties.remove(counties[11]); unusedCounties.remove(counties[10]); unusedCounties.remove(counties[12]); unusedCounties.remove(counties[21]); unusedCounties.remove(counties[22]); districtSizes[0] = 600000; districtMargins[0] = 11600; districts[0].add(counties[11]); districts[0].add(counties[10]); districts[0].add(counties[12]); districts[0].add(counties[21]); districts[0].add(counties[22]); unusedCounties.remove(counties[9]); unusedCounties.remove(counties[2]); unusedCounties.remove(counties[0]); unusedCounties.remove(counties[1]); unusedCounties.remove(counties[8]); unusedCounties.remove(counties[15]); districtSizes[1] = 605000; districtMargins[1] = 20600; districts[1].add(counties[9]); districts[1].add(counties[2]); districts[1].add(counties[0]); districts[1].add(counties[1]); districts[1].add(counties[8]); districts[1].add(counties[15]); /* unusedCounties.remove(counties[3]); unusedCounties.remove(counties[4]); unusedCounties.remove(counties[5]); unusedCounties.remove(counties[7]); unusedCounties.remove(counties[17]); unusedCounties.remove(counties[18]); unusedCounties.remove(counties[27]); districtSizes[2] = 595000; districtMargins[2] = 18600; districts[2].add(counties[3]); districts[2].add(counties[4]); districts[2].add(counties[5]); districts[2].add(counties[7]); districts[2].add(counties[17]); districts[2].add(counties[18]); districts[2].add(counties[27]); */ unusedCounties.remove(counties[3]); districts[2].add(counties[3]); Timer timer = new Timer(1, -1, new Main(), "printProgress"); timer.start(); startTime = Timer.getTime(); System.out.println(gerrymander(counties[3], 2)); timer.stop(); System.out.println(arrayString(districts)); writer.close(); } private static int gerrymander(County current, int currentDistrict) { numberOfCountiesSelected++; if (unusedCounties.size() == 0) { //System.out.println(arrayString(districts)); if (districtSizes[DISTRICT_COUNT - 1] < MIN_DISTRICT_SIZE || (districtMargins[currentDistrict] <= 0 && republicanVotes >= DISTRICT_COUNT - democratVoteTarget)) { return -1; } int democratWins = 0; for (int i = 0; i < districts.length; i++) { int totalRepublicans = 0; int totalDemocrats = 0; for (County c : districts[i]) { totalDemocrats += c.democratCount; totalRepublicans += c.republicanCount; } if (totalRepublicans < totalDemocrats) { democratWins++; } } //if (democratWins > democratVoteTarget) { //democratVoteTarget = democratWins; //System.out.println(democratWins + "\n" + arrayString(districts)); //writeln(democratWins + "\n" + arrayString(districts)); return democratWins; //return republicanWins; } //System.out.println(arrayString(districts)); if (districtSizes[currentDistrict] > MIN_DISTRICT_SIZE && currentDistrict < DISTRICT_COUNT - 1 && (districtMargins[currentDistrict] > 0 || republicanVotes < DISTRICT_COUNT - democratVoteTarget) && !attemptedDistricts[currentDistrict].contains(districts[currentDistrict])) { attemptedDistricts[currentDistrict].add(new LinkedHashSet<County>(districts[currentDistrict])); County firstUnusedCounty = null; for (County c : unusedCounties) { firstUnusedCounty = c; break; } unusedCounties.remove(firstUnusedCounty); districts[currentDistrict + 1].add(firstUnusedCounty); districtMargins[currentDistrict + 1] += firstUnusedCounty.democratCount - firstUnusedCounty.republicanCount; districtSizes[currentDistrict + 1] += firstUnusedCounty.totalPopulation; boolean isRepublicanVote = districtMargins[currentDistrict] <= 0; if (isRepublicanVote) { republicanVotes++; } int result = gerrymander(firstUnusedCounty, currentDistrict + 1); if (result >= democratVoteTarget) { return result; } else { unusedCounties.add(firstUnusedCounty); districts[currentDistrict + 1].remove(firstUnusedCounty); districtMargins[currentDistrict + 1] -= firstUnusedCounty.democratCount - firstUnusedCounty.republicanCount; districtSizes[currentDistrict + 1] -= firstUnusedCounty.totalPopulation; if (isRepublicanVote) { republicanVotes } } } //System.out.println(arrayString(districts)); County.targetSortMargin = -districtMargins[currentDistrict]; Arrays.sort(current.adjacentCounties); for (County c : current.adjacentCounties) { if (unusedCounties.contains(c) && districtSizes[currentDistrict] + c.totalPopulation <= MAX_DISTRICT_SIZE) { unusedCounties.remove(c); districts[currentDistrict].add(c); districtMargins[currentDistrict] += c.democratCount - c.republicanCount; districtSizes[currentDistrict] += c.totalPopulation; int result = gerrymander(c, currentDistrict); if (result >= democratVoteTarget) { return result; } else { unusedCounties.add(c); districts[currentDistrict].remove(c); districtMargins[currentDistrict] -= c.democratCount - c.republicanCount; districtSizes[currentDistrict] -= c.totalPopulation; } } } attemptedDistricts[currentDistrict].clear(); System.gc(); return -1; } private static String arrayString(Object[] s) { if (s.length == 0) { return "[]"; } String ret = "["; try { for (int i = 0; i < s.length - 1; i++) { Object o = s[i]; ret += o + ", "; } ret += s[s.length - 1]; } catch (ConcurrentModificationException e) { return ""; } return ret + "]"; } private static void writeln(String s) { writer.println(s); writer.flush(); } public void printProgress() { System.out.printf("County selections attempted: " + numberOfCountiesSelected + "\tTime elapsed: %.3f" + "\t" + arrayString(districts) + '\n', Timer.getTime() - startTime); } } class County implements Comparable<County> { public String name; public int totalPopulation; public int democratCount; public int republicanCount; public int margin; public County[] adjacentCounties; public ArrayList<Integer> adjacentCountiesIndexes = new ArrayList<Integer>(); public static int targetSortMargin; public String toString() { return name; } public int compareTo(County c) { int a = targetSortMargin - margin; int b = targetSortMargin - c.margin; return b - a; } }
import java.io.RandomAccessFile; import java.io.IOException; public final class PDBDecoder { /** * <p>This method decodes a pdb file into a PalmDB object.</p> * * <p>First, read in the header data using <code>PDBHeader</code>'s * <code>read</code> method</p>. Next, read in the record list * section. Store the record offsets for use when parsing the records. * Based on these offsets, read in each record's bytes and store * each in a <code>Record</code> object. Lastly, create a * <code>PalmDB</code> object with the read in <code>Record</code>s. * * @param fileName pdb file name * @throws IOException if I/O error occurs */ public PalmDB parse(String fileName) throws IOException { RandomAccessFile file = new RandomAccessFile(fileName, "r"); // read the pdb header PDBHeader header = new PDBHeader(); header.read(file); Record recArray[] = new Record[header.numRecords]; if (header.numRecords != 0) { // read in the record indices + offsets int recOffset[] = new int[header.numRecords]; for (int i = 0; i < header.numRecords; i++) { recOffset[i] = file.readInt(); int attr = file.readInt(); // read in attribute. } // read the records int len = 0; byte[] bytes = null; int lastIndex = header.numRecords - 1; for (int i = 0; i < lastIndex; i++) { file.seek(recOffset[i]); len = recOffset[i+1] - recOffset[i]; bytes = new byte[len]; file.readFully(bytes); recArray[i] = new Record(bytes); } // last record file.seek(recOffset[lastIndex]); len = (int) file.length() - recOffset[lastIndex]; bytes = new byte[len]; file.readFully(bytes); recArray[lastIndex] = new Record(bytes); } file.close(); // create PalmDB and return it PalmDB pdb = new PalmDB(header.pdbName, recArray); return pdb; } }
package com.xpn.xwiki.web; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; import org.apache.ecs.Filter; import org.apache.ecs.filter.CharacterFilter; import org.apache.log4j.MDC; import org.apache.struts.upload.MultipartRequestWrapper; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import com.novell.ldap.util.Base64; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.plugin.fileupload.FileUploadPlugin; import com.xpn.xwiki.xmlrpc.XWikiXmlRpcRequest; public class Utils { /** A key that is used for placing a map of replaced (for protection) strings in the context. */ private static final String PLACEHOLDERS_CONTEXT_KEY = Utils.class.getCanonicalName() + "_placeholders"; /** Whether placeholders are enabled or not. */ private static final String PLACEHOLDERS_ENABLED_CONTEXT_KEY = Utils.class.getCanonicalName() + "_placeholders_enabled"; /** * The component manager used by {@link #getComponent(String)} and {@link #getComponent(String, String)}. It is * useful for any non component code that need to initialize/access components. */ private static ComponentManager componentManager; public static void parseTemplate(String template, XWikiContext context) throws XWikiException { parseTemplate(template, true, context); } public static void parseTemplate(String template, boolean write, XWikiContext context) throws XWikiException { XWikiResponse response = context.getResponse(); // Set content-type and encoding (this can be changed later by pages themselves) if (context.getResponse() instanceof XWikiPortletResponse) { response.setContentType("text/html"); } else { response.setContentType("text/html; charset=" + context.getWiki().getEncoding()); } String action = context.getAction(); if ((!"download".equals(action)) && (!"skin".equals(action))) { if (context.getResponse() instanceof XWikiServletResponse) { // Add a last modified to tell when the page was last updated if (context.getWiki().getXWikiPreferenceAsLong("headers_lastmodified", 0, context) != 0) { if (context.getDoc() != null) { response.setDateHeader("Last-Modified", context.getDoc().getDate().getTime()); } } // Set a nocache to make sure the page is reloaded after an edit if (context.getWiki().getXWikiPreferenceAsLong("headers_nocache", 1, context) != 0) { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); } // Set an expires in one month long expires = context.getWiki().getXWikiPreferenceAsLong("headers_expires", -1, context); if (expires == -1) { response.setDateHeader("Expires", -1); } else if (expires != 0) { response.setDateHeader("Expires", (new Date()).getTime() + 30 * 24 * 3600 * 1000L); } } } if (("download".equals(action)) || ("skin".equals(action))) { // Set a nocache to make sure these files are not cached by proxies if (context.getWiki().getXWikiPreferenceAsLong("headers_nocache", 1, context) != 0) { response.setHeader("Cache-Control", "no-cache"); } } context.getWiki().getPluginManager().beginParsing(context); // This class allows various components in the rendering chain to use placeholders for some fragile data. For // example, the URL generated for the image macro should not be further rendered, as it might get broken by wiki // filters. For this to work, keep a map of used placeholders -> values in the context, and replace them when // the content is fully rendered. The rendering code can use Utils.createPlaceholder. // Initialize the placeholder map enablePlaceholders(context); String content = context.getWiki().parseTemplate(template + ".vm", context); // Replace all placeholders with the protected values content = replacePlaceholders(content, context); disablePlaceholders(context); content = context.getWiki().getPluginManager().endParsing(content.trim(), context); if (content.equals("")) { // get Error template "This template does not exist content = context.getWiki().parseTemplate("templatedoesnotexist.vm", context); content = content.trim(); } if (!context.isFinished()) { if (context.getResponse() instanceof XWikiServletResponse) { // Set the content length to the number of bytes, not the // string length, so as to handle multi-byte encodings try { response.setContentLength(content.getBytes(context.getWiki().getEncoding()).length); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } if (write) { try { try { response.getOutputStream().write(content.getBytes(context.getWiki().getEncoding())); } catch (IllegalStateException ex) { response.getWriter().write(content); } } catch (IOException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e); } } } try { response.getOutputStream().flush(); } catch (Throwable ex) { try { response.getWriter().flush(); } catch (Throwable ex2) { } } } public static String getRedirect(XWikiRequest request, String defaultRedirect) { String redirect; redirect = request.getParameter("xredirect"); if ((redirect == null) || (redirect.equals(""))) { redirect = defaultRedirect; } return redirect; } public static String getRedirect(String action, String params, XWikiContext context) { String redirect; redirect = context.getRequest().getParameter("xredirect"); if (StringUtils.isBlank(redirect)) { redirect = context.getDoc().getURL(action, params, true, context); } return redirect; } public static String getRedirect(String action, XWikiContext context) { return getRedirect(action, null, context); } public static String getPage(XWikiRequest request, String defaultpage) { String page; page = request.getParameter("xpage"); if ((page == null) || (page.equals(""))) { page = defaultpage; } return page; } public static String getFileName(List filelist, String name) { FileItem fileitem = null; for (int i = 0; i < filelist.size(); i++) { FileItem item = (FileItem) filelist.get(i); if (name.equals(item.getFieldName())) { fileitem = item; break; } } if (fileitem == null) { return null; } return fileitem.getName(); } public static byte[] getContent(List filelist, String name) throws XWikiException { FileItem fileitem = null; for (int i = 0; i < filelist.size(); i++) { FileItem item = (FileItem) filelist.get(i); if (name.equals(item.getFieldName())) { fileitem = item; break; } } if (fileitem == null) { return null; } byte[] data = new byte[(int) fileitem.getSize()]; InputStream fileis = null; try { fileis = fileitem.getInputStream(); fileis.read(data); fileis.close(); } catch (IOException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_FILE_EXCEPTION, "Exception while reading uploaded parsed file", e); } return data; } public static XWikiContext prepareContext(String action, XWikiRequest request, XWikiResponse response, XWikiEngineContext engine_context) throws XWikiException { XWikiContext context = new XWikiContext(); String dbname = "xwiki"; URL url = XWiki.getRequestURL(request); context.setURL(url); // Push the URL into the Log4j MDC context so that we can display it in the generated logs // using the // %X{url} syntax. MDC.put("url", url); context.setEngineContext(engine_context); context.setRequest(request); context.setResponse(response); context.setAction(action); context.setDatabase(dbname); int mode = 0; if (request instanceof XWikiXmlRpcRequest) { mode = XWikiContext.MODE_XMLRPC; } else if (request instanceof XWikiServletRequest) { mode = XWikiContext.MODE_SERVLET; } else if (request instanceof XWikiPortletRequest) { mode = XWikiContext.MODE_PORTLET; } context.setMode(mode); // This is a temporary bridge so that non XWiki component classes can lookup XWiki // components. A ComponentManager instance has been set up in the Servlet Context and // we now populate the XWiki Context with it so that code can then use it to look up // components. // This is of course not necessary for XWiki components since they just need to implement // the Composable interface to get access to the Component Manager or better they simply // need to define the Components they require as field members and configure the Plexus // deployment descriptors (components.xml) so that they are automatically injected. ComponentManager componentManager = (ComponentManager) engine_context.getAttribute(ComponentManager.class.getName()); context.put(ComponentManager.class.getName(), componentManager); // Statically store the component manager in {@link Utils} to be able to access it without // the context. Utils.setComponentManager(componentManager); return context; } public static Map<String, String[]> parseParameters(String data, String encoding) throws UnsupportedEncodingException { if ((data != null) && (data.length() > 0)) { // use the specified encoding to extract bytes out of the // given string so that the encoding is not lost. If an // encoding is not specified, let it use platform default byte[] bytes = null; try { if (encoding == null) { bytes = data.getBytes(); } else { bytes = data.getBytes(encoding); } } catch (UnsupportedEncodingException uee) { } return parseParameters(bytes, encoding); } return Collections.emptyMap(); } public static Map<String, String[]> parseParameters(byte[] data, String encoding) throws UnsupportedEncodingException { Map<String, String[]> map = new HashMap<String, String[]>(); if (data != null && data.length > 0) { int ix = 0; int ox = 0; String key = null; String value = null; while (ix < data.length) { byte c = data[ix++]; switch ((char) c) { case '&': value = new String(data, 0, ox, encoding); if (key != null) { putMapEntry(map, key, value); key = null; } ox = 0; break; case '=': if (key == null) { key = new String(data, 0, ox, encoding); ox = 0; } else { data[ox++] = c; } break; case '+': data[ox++] = (byte) ' '; break; case '%': data[ox++] = (byte) ((convertHexDigit(data[ix++]) << 4) + convertHexDigit(data[ix++])); break; default: data[ox++] = c; } } // The last value does not end in '&'. So save it now. if (key != null) { value = new String(data, 0, ox, encoding); putMapEntry(map, key, value); } } return map; } /** * Convert a byte character value to hexidecimal digit value. * * @param b the character value byte <p/> Code borrowed from Apache Tomcat 5.0 */ private static byte convertHexDigit(byte b) { if ((b >= '0') && (b <= '9')) { return (byte) (b - '0'); } if ((b >= 'a') && (b <= 'f')) { return (byte) (b - 'a' + 10); } if ((b >= 'A') && (b <= 'F')) { return (byte) (b - 'A' + 10); } return 0; } /** * Put name value pair in map. <p/> Put name and value pair in map. When name already exist, add value to array of * values. <p/> Code borrowed from Apache Tomcat 5.0 */ private static void putMapEntry(Map<String, String[]> map, String name, String value) { String[] newValues = null; String[] oldValues = map.get(name); if (oldValues == null) { newValues = new String[1]; newValues[0] = value; } else { newValues = new String[oldValues.length + 1]; System.arraycopy(oldValues, 0, newValues, 0, oldValues.length); newValues[oldValues.length] = value; } map.put(name, newValues); } public static String formEncode(String value) { Filter filter = new CharacterFilter(); filter.removeAttribute("'"); String svalue = filter.process(value); return svalue; } public static String SQLFilter(String text) { try { return text.replaceAll("'", "''"); } catch (Exception e) { return text; } } // TODO: Duplicate of Util.encodeURI(). Keep only one /** * @deprecated replaced by Util#encodeURI since 1.3M2 */ @Deprecated public static String encode(String name, XWikiContext context) { try { return URLEncoder.encode(name, context.getWiki().getEncoding()); } catch (Exception e) { return name; } } // TODO: Duplicate of Util.decodeURI(). Keep only one /** * @deprecated replaced by Util#decodeURI since 1.3M2 */ @Deprecated public static String decode(String name, XWikiContext context) { try { // Make sure + is considered as a space String result = name.replaceAll("\\+", " "); // It seems Internet Explorer can send us back UTF-8 // instead of ISO-8859-1 for URLs if (Base64.isValidUTF8(result.getBytes(), false)) { result = new String(result.getBytes(), "UTF-8"); } // Still need to decode URLs return URLDecoder.decode(result, context.getWiki().getEncoding()); } catch (Exception e) { return name; } } public static FileUploadPlugin handleMultipart(HttpServletRequest request, XWikiContext context) { FileUploadPlugin fileupload = null; try { if (request instanceof MultipartRequestWrapper) { fileupload = new FileUploadPlugin("fileupload", "fileupload", context); fileupload.loadFileList(context); context.put("fileuploadplugin", fileupload); MultipartRequestWrapper mpreq = (MultipartRequestWrapper) request; List fileItems = fileupload.getFileItems(context); for (Iterator iter = fileItems.iterator(); iter.hasNext();) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String sName = item.getFieldName(); String sValue = item.getString(); mpreq.setParameter(sName, sValue); } } } } catch (Exception e) { if ((e instanceof XWikiException) && (((XWikiException) e).getCode() == XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE)) { context.put("exception", e); } else { e.printStackTrace(); } } return fileupload; } /** * @param componentManager the component manager used by {@link #getComponent(String)} and * {@link #getComponent(String, String)} */ public static void setComponentManager(ComponentManager componentManager) { Utils.componentManager = componentManager; } /** * @return the component manager used by {@link #getComponent(String)} and {@link #getComponent(String, String)} */ public static ComponentManager getComponentManager() { return Utils.componentManager; } /** * Lookup a XWiki component by role and hint. * * @param role the component's identity (usually the component's interface name as a String) * @param hint a value to differentiate different component implementations for the same role * @return the component's Object */ public static Object getComponent(String role, String hint) { Object component = null; if (componentManager != null) { try { component = componentManager.lookup(role, hint); } catch (ComponentLookupException e) { throw new RuntimeException("Failed to load component [" + role + "] for hint [" + hint + "]", e); } } else { throw new RuntimeException("Component manager has not been initialized before lookup for [" + role + "] for hint [" + hint + "]"); } return component; } /** * Lookup a XWiki component by role (uses the default hint). * * @param role the component's identity (usually the component's interface name as a String) * @return the component's Object */ public static Object getComponent(String role) { return getComponent(role, "default"); } /** * Check if placeholders are enabled in the current context. * * @param context The current context. * @return <code>true</code> if placeholders can be used, <code>false</code> otherwise. */ public static boolean arePlaceholdersEnabled(XWikiContext context) { Boolean enabled = (Boolean) context.get(PLACEHOLDERS_ENABLED_CONTEXT_KEY); return enabled != null && enabled.booleanValue(); } /** * Enable placeholder support in the current request context. * * @param context The current context. */ public static void enablePlaceholders(XWikiContext context) { context.put(PLACEHOLDERS_CONTEXT_KEY, new HashMap<String, String>()); context.put(PLACEHOLDERS_ENABLED_CONTEXT_KEY, new Boolean(true)); } /** * Disable placeholder support in the current request context. * * @param context The current context. */ public static void disablePlaceholders(XWikiContext context) { context.remove(PLACEHOLDERS_CONTEXT_KEY); context.remove(PLACEHOLDERS_ENABLED_CONTEXT_KEY); } /** * Create a placeholder key for a string that should be protected from further processing. The value is stored in * the context, and the returned key can be used by the calling code as many times in the rendering result. At the * end of the rendering process all placeholder keys are replaced with the values they replace. * * @param value The string to hide. * @param context The current context. * @return The key to be used instead of the value. */ @SuppressWarnings("unchecked") public static String createPlaceholder(String value, XWikiContext context) { if (!arePlaceholdersEnabled(context)) { return value; } Map<String, String> renderingKeys = (Map<String, String>) context.get(PLACEHOLDERS_CONTEXT_KEY); String key; do { key = "KEY" + RandomStringUtils.randomAlphanumeric(10) + "KEY"; } while (renderingKeys.containsKey(key)); renderingKeys.put(key, value); return key; } /** * Insert back the replaced strings. * * @param content The rendered content, with placeholders. * @param context The current context. * @return The content with all placeholders replaced with the real values. */ @SuppressWarnings("unchecked") public static String replacePlaceholders(String content, XWikiContext context) { if (!arePlaceholdersEnabled(context)) { return content; } String result = content; Map<String, String> renderingKeys = (Map<String, String>) context.get(PLACEHOLDERS_CONTEXT_KEY); for (Entry<String, String> e : renderingKeys.entrySet()) { result = result.replace(e.getKey(), e.getValue()); } return result; } }
package uk.ac.ox.oucs.vle; import java.util.Date; import java.util.List; import java.util.Set; public interface CourseSignupService { public static enum Status { PENDING(false), WITHDRAWN(false), APPROVED(true), ACCEPTED(true), REJECTED(false); private final boolean takeSpace; Status(boolean takeSpace) { this.takeSpace = takeSpace; } public boolean isTakingSpace() { return takeSpace; } public int getSpacesTaken() { return (takeSpace)?1:0; } }; public static enum Range {ALL, UPCOMING, PREVIOUS}; // List of events public static final String EVENT_SIGNUP = "coursesignup.signup"; public static final String EVENT_ACCEPT = "coursesignup.accept"; public static final String EVENT_WITHDRAW = "coursesignup.withdraw"; public static final String EVENT_APPROVE = "coursesignup.approve"; public static final String EVENT_REJECT = "coursesignup.reject"; public CourseGroup getCourseGroup(String courseId, Range range); /** * This loads a course group with only the data that is available at the moment. * @param courseId * @return */ public CourseGroup getAvailableCourseGroup(String courseId); /** * Finds all course groups * @param deptId * @param range * @return */ public List<CourseGroup> getCourseGroups(String deptId, Range range); public String findSupervisor(String search); public void signup(String courseId, Set<String> components, String supervisorEmail, String message); /** * A signup made * @param userId * @param courseId * @param components */ public void signup(String userId, String courseId, Set<String> components, String supervisorId); public List<CourseSignup> getCourseSignups(String courseId, Set<Status> statuses); public List<CourseSignup> getComponentSignups(String componentId, Set<Status> statuses); public List<CourseSignup> getApprovals(); public void approve(String signupId); public void accept(String signupId); public void reject(String signupId); public void withdraw(String signupId); /** * Gets all the CourseGroups that the current user can administer. * @return */ public List<CourseGroup> getAdministering(); public void setSignupStatus(String signupId, Status status); public List<CourseGroup> search(String search, Range range); /** * This is what the service should use when determining the current time. * This is to support testing the data against different times. * @return */ public Date getNow(); public List<CourseSignup> getMySignups(Set<Status> statuses); public List<CourseSignup> getUserComponentSignups(String userId, Set<Status> statuses); /** * Find a particular signup. * @param signupId The signup to load. * @return The signup or null if it couldn't be found. */ public CourseSignup getCourseSignup(String signupId); }
package com.galvarez.ttw.model; import java.util.EnumSet; import java.util.Map.Entry; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.annotations.Wire; import com.artemis.systems.EntityProcessingSystem; import com.galvarez.ttw.model.components.AIControlled; import com.galvarez.ttw.model.components.Discoveries; import com.galvarez.ttw.model.components.Policies; import com.galvarez.ttw.model.components.Research; import com.galvarez.ttw.model.data.Culture; import com.galvarez.ttw.model.data.Discovery; import com.galvarez.ttw.model.data.Empire; import com.galvarez.ttw.model.data.Policy; import com.galvarez.ttw.rendering.components.Name; @Wire public final class AIDiscoverySystem extends EntityProcessingSystem { private static final Logger log = LoggerFactory.getLogger(AIDiscoverySystem.class); private ComponentMapper<Discoveries> discoveries; private ComponentMapper<Policies> policies; private ComponentMapper<Empire> empires; private DiscoverySystem discoverySystem; @SuppressWarnings("unchecked") public AIDiscoverySystem() { super(Aspect.getAspectForAll(AIControlled.class, Discoveries.class, Empire.class)); } @Override protected boolean checkProcessing() { return true; } @Override protected void process(Entity e) { Discoveries d = discoveries.get(e); if (d.next == null) { Culture culture = empires.get(e).culture; Entry<Faction, Research> prefered = null; float max = Float.NEGATIVE_INFINITY; for (Entry<Faction, Research> possible : discoverySystem.possibleDiscoveries(e, d).entrySet()) { Faction faction = possible.getKey(); float score = culture.ai.get(faction) * possible.getValue().target.factions.get(faction, 1); if (score > max) { max = score; prefered = possible; } } if (prefered != null) { log.info("{} follows {} advice to investigate {} from {}", e.getComponent(Name.class), prefered.getKey(), prefered.getValue().target, prefered.getValue().previous); d.next = prefered.getValue(); } Set<Policy> newPolicies; if (d.last != null && (newPolicies = getPolicies(d.last.target)) != null) { Policies empirePolicies = policies.get(e); for (Policy p : newPolicies) { Discovery newD = d.last.target; Discovery oldD = empirePolicies.policies.get(p); float oldScore = policyScore(oldD, culture); float newScore = policyScore(newD, culture); if (newScore > oldScore) { log.info("{} replaced policy {}={}(score={}) by {}(score={})", e.getComponent(Name.class), p, oldD, oldScore, newD, newScore); empirePolicies.policies.put(p, newD); } else log.info("{} did not replace policy {}={}(score={}) by {}(score={})", e.getComponent(Name.class), p, oldD, oldScore, newD, newScore); } } } } private static float policyScore(Discovery d, Culture culture) { if (d == null) return 0f; float score = 0f; for (Faction f : Faction.values()) score += d.factions.get(f, 0f) * culture.ai.get(f).floatValue(); return score; } private Set<Policy> getPolicies(Discovery d) { Set<Policy> set = null; for (String group : d.groups) { Policy p = Policy.get(group); if (p != null) { if (set == null) set = EnumSet.of(p); else set.add(p); } } return set; } private boolean hasPolicy(Discovery d) { for (String group : d.groups) if (Policy.get(group) != null) return true; return false; } }
package com.gamestudio24.cityescape.actors; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.physics.box2d.Body; import com.gamestudio24.cityescape.box2d.EnemyUserData; import com.gamestudio24.cityescape.utils.Constants; public class Enemy extends GameActor { private Animation animation; private float stateTime; public Enemy(Body body) { super(body); TextureAtlas textureAtlas = new TextureAtlas(Constants.SPRITES_ATLAS_PATH); TextureRegion[] runningFrames = new TextureRegion[getUserData().getTextureRegions().length]; for (int i = 0; i < getUserData().getTextureRegions().length; i++) { String path = getUserData().getTextureRegions()[i]; runningFrames[i] = textureAtlas.findRegion(path); } animation = new Animation(0.1f, runningFrames); stateTime = 0f; } @Override public EnemyUserData getUserData() { return (EnemyUserData) userData; } @Override public void act(float delta) { super.act(delta); body.setLinearVelocity(getUserData().getLinearVelocity()); } @Override public void draw(Batch batch, float parentAlpha) { super.draw(batch, parentAlpha); stateTime += Gdx.graphics.getDeltaTime(); batch.draw(animation.getKeyFrame(stateTime, true), (screenRectangle.x - (screenRectangle.width * 0.1f)), screenRectangle.y, screenRectangle.width * 1.2f, screenRectangle.height * 1.1f); } }
package net.time4j.format; import net.time4j.base.MathUtils; import java.util.Locale; /** * <p>Defines the number system. </p> * * @author Meno Hochschild * @since 3.11/4.8 */ /*[deutsch] * <p>Definiert ein Zahlsystem. </p> * * @author Meno Hochschild * @since 3.11/4.8 */ public enum NumberSystem { /** * Arabic numbers with digits 0-9 (default setting). */ /*[deutsch] * Arabische Zahlen mit den Ziffern 0-9 (Standardeinstellung). */ ARABIC() { @Override public String toNumeral(int number) { return Integer.toString(number); } @Override public int toInteger(String numeral, Leniency leniency) { return Integer.parseInt(numeral); } @Override public boolean contains(char digit) { return ((digit >= '0') && (digit <= '9')); } }, ETHIOPIC() { @Override public String toNumeral(int number) { if (number < 1) { throw new IllegalArgumentException("Can only convert positive numbers: " + number); } String value = String.valueOf(number); int n = value.length() - 1; if ((n % 2) == 0) { value = "0" + value; n++; } StringBuilder numeral = new StringBuilder(); char asciiOne, asciiTen, ethioOne, ethioTen; for (int place = n; place >= 0; place ethioOne = ethioTen = 0x0; asciiTen = value.charAt(n - place); place asciiOne = value.charAt(n - place); if (asciiOne != '0') { ethioOne = (char) ((int) asciiOne + (ETHIOPIC_ONE - '1')); } if (asciiTen != '0') { ethioTen = (char) ((int) asciiTen + (ETHIOPIC_TEN - '1')); } int pos = (place % 4) / 2; char sep = 0x0; if (place != 0) { sep = ( (pos != 0) ? (((ethioOne != 0x0) || (ethioTen != 0x0)) ? ETHIOPIC_HUNDRED : 0x0) : ETHIOPIC_TEN_THOUSAND); } if ((ethioOne == ETHIOPIC_ONE) && (ethioTen == 0x0) && (n > 1)) { if ((sep == ETHIOPIC_HUNDRED) || ((place + 1) == n)) { ethioOne = 0x0; } } if (ethioTen != 0x0) { numeral.append(ethioTen); } if (ethioOne != 0x0) { numeral.append(ethioOne); } if (sep != 0x0) { numeral.append(sep); } } return numeral.toString(); } @Override public int toInteger(String numeral, Leniency leniency) { int total = 0; int sum = 0; int factor = 1; boolean hundred = false; boolean thousand = false; int n = numeral.length() - 1; for (int place = n; place >= 0; place char digit = numeral.charAt(place); if ((digit >= ETHIOPIC_ONE) && (digit < ETHIOPIC_TEN)) { sum += (1 + digit - ETHIOPIC_ONE); } else if ((digit >= ETHIOPIC_TEN) && (digit < ETHIOPIC_HUNDRED)) { // 10-90 sum += ((1 + digit - ETHIOPIC_TEN) * 10); } else if (digit == ETHIOPIC_TEN_THOUSAND) { if (hundred && (sum == 0)) { sum = 1; } total = add(total, sum, factor); if (hundred) { factor *= 100; } else { factor *= 10000; } sum = 0; hundred = false; thousand = true; } else if (digit == ETHIOPIC_HUNDRED) { total = add(total, sum, factor); factor *= 100; sum = 0; hundred = true; thousand = false; } } if ((hundred || thousand) && (sum == 0)) { sum = 1; } total = add(total, sum, factor); return total; } @Override public boolean contains(char digit) { return ((digit >= ETHIOPIC_ONE) && (digit <= ETHIOPIC_TEN_THOUSAND)); } }, ROMAN() { @Override public String toNumeral(int number) { if ((number < 1) || (number > 3999)) { throw new IllegalArgumentException("Out of range (1-3999): " + number); } int n = number; StringBuilder roman = new StringBuilder(); for (int i = 0; i < NUMBERS.length; i++) { while (n >= NUMBERS[i]) { roman.append(LETTERS[i]); n -= NUMBERS[i]; } } return roman.toString(); } @Override public int toInteger(String numeral, Leniency leniency) { if (numeral.isEmpty()) { throw new NumberFormatException("Empty Roman numeral."); } String ucase = numeral.toUpperCase(Locale.US); // use ASCII-base boolean strict = leniency.isStrict(); int len = numeral.length(); int i = 0; int total = 0; while (i < len) { char roman = ucase.charAt(i); int value = getValue(roman); int j = i + 1; int count = 1; if (j == len) { total += value; } else { while (j < len) { char test = ucase.charAt(j); j++; if (test == roman) { count++; if ((count >= 4) && strict) { throw new NumberFormatException( "Roman numeral contains more than 3 equal letters in sequence: " + numeral); } if (j == len) { total += (value * count); } } else { int next = getValue(test); if (next < value) { total += (value * count); j } else { // next > value if (strict) { if ((count > 1) || !isValidCombination(roman, test)) { throw new NumberFormatException("Not conform with modern usage: " + numeral); } } total = total + next - (value * count); } break; } } } i = j; } if (total > 3999) { throw new NumberFormatException("Roman numbers bigger than 3999 not supported."); } else if (strict) { if (total >= 900 && ucase.contains("DCD")) { throw new NumberFormatException("Roman number contains invalid sequence DCD."); } if (total >= 90 && ucase.contains("LXL")) { throw new NumberFormatException("Roman number contains invalid sequence LXL."); } if (total >= 9 && ucase.contains("VIV")) { throw new NumberFormatException("Roman number contains invalid sequence VIV."); } } return total; } @Override public boolean contains(char digit) { char c = Character.toUpperCase(digit); return ((c == 'I') || (c == 'V') || (c == 'X') || (c == 'L') || (c == 'C') || (c == 'D') || (c == 'M')); } }; private static final char ETHIOPIC_ONE = 0x1369; // 1, 2, ..., 8, 9 private static final char ETHIOPIC_TEN = 0x1372; // 10, 20, ..., 80, 90 private static final char ETHIOPIC_HUNDRED = 0x137B; private static final char ETHIOPIC_TEN_THOUSAND = 0x137C; private static final int[] NUMBERS = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; private static final String[] LETTERS = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; public String toNumeral(int number) { throw new AbstractMethodError(); } /** * <p>Converts given text numeral to an integer in smart mode. </p> * * @param numeral text numeral to be evaluated as number * @return integer * @throws NumberFormatException if given number has wrong format * @throws ArithmeticException if int-range overflows * @since 3.11/4.8 */ /*[deutsch] * <p>Konvertiert das angegebene Numeral zu einer Ganzzahl im SMART-Modus. </p> * * @param numeral text numeral to be evaluated as number * @return integer * @throws NumberFormatException if given number has wrong format * @throws ArithmeticException if int-range overflows * @since 3.11/4.8 */ public final int toInteger(String numeral) { return this.toInteger(numeral, Leniency.SMART); } /** * <p>Converts given text numeral to an integer. </p> * * <p>In most cases, the leniency will not be taken into account, but parsing of some odd roman numerals * can be enabled in non-strict mode (for example: IIXX instead of XVIII). </p> * * @param numeral text numeral to be evaluated as number * @param leniency determines how lenient the parsing of given numeral should be * @return integer * @throws NumberFormatException if given number has wrong format * @throws ArithmeticException if int-range overflows * @since 3.15/4.12 */ /*[deutsch] * <p>Konvertiert das angegebene Numeral zu einer Ganzzahl. </p> * * <p>In den meisten F&auml;llen wird das Nachsichtigkeitsargument nicht in Betracht gezogen. Aber die * Interpretation von nicht dem modernen Gebrauch entsprechenden r&ouml;mischen Numeralen kann im * nicht-strikten Modus erfolgen (zum Beispiel IIXX statt XVIII). </p> * * @param numeral text numeral to be evaluated as number * @param leniency determines how lenient the parsing of given numeral should be * @return integer * @throws NumberFormatException if given number has wrong format * @throws ArithmeticException if int-range overflows * @since 3.15/4.12 */ public int toInteger( String numeral, Leniency leniency ) { throw new AbstractMethodError(); } /** * <p>Does this number system contains given digit char? </p> * * @param digit numerical char to be checked * @return boolean * @since 3.11/4.8 */ /*[deutsch] * <p>Enth&auml;lt dieses Zahlensystem die angegebene Ziffer? </p> * * @param digit numerical char to be checked * @return boolean * @since 3.11/4.8 */ public boolean contains(char digit) { throw new AbstractMethodError(); } private static int add( int total, int sum, int factor ) { return MathUtils.safeAdd(total, MathUtils.safeMultiply(sum, factor)); } private static int getValue(char roman) { switch (roman) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: throw new NumberFormatException("Invalid Roman digit: " + roman); } } private static boolean isValidCombination( char previous, char next ) { switch (previous) { case 'C': return ((next == 'M') || (next == 'D')); case 'X': return ((next == 'C') || (next == 'L')); case 'I': return ((next == 'X') || (next == 'V')); default: return false; } } }
package cz.muni.fi.pv243.test; import static org.junit.Assert.*; import java.util.List; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.extension.rest.client.ArquillianResteasyResource; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import cz.muni.fi.pv243.model.Author; import cz.muni.fi.pv243.model.Book; import cz.muni.fi.pv243.model.Volume; import cz.muni.fi.pv243.rest.BookEndpoint; import cz.muni.fi.pv243.service.BookService; @RunWith(Arquillian.class) public class RestTest { @Deployment(testable = false) public static Archive<?> createDeployment() { return ShrinkWrap.create(WebArchive.class, "test.war") .addAsResource("test-persistence.xml", "META-INF/persistence.xml") .addPackage(Book.class.getPackage()) .addPackage(BookService.class.getPackage()) .addPackage(BookEndpoint.class.getPackage()) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } @Test @RunAsClient public void testCreateBookWithAuthor(@ArquillianResteasyResource("") WebTarget webTarget) throws Exception { Author author = new Author(); author.setName("Foo"); author.setSurname("Bar"); Response authorResponse = webTarget .path("authors") .request(MediaType.APPLICATION_JSON) .post(Entity.json(author)); assertEquals(Response.Status.CREATED.getStatusCode(), authorResponse.getStatus()); Author outAuthor = authorResponse.readEntity(Author.class); Book book = new Book(); book.setTitle("Book"); book.setISBN("1234"); book.getAuthors().add(outAuthor); Response bookResponse = webTarget .path("books") .request(MediaType.APPLICATION_JSON) .post(Entity.json(book)); assertEquals(Response.Status.CREATED.getStatusCode(), bookResponse.getStatus()); Book outBook = bookResponse.readEntity(Book.class); assertNotNull(outBook.getId()); bookResponse = webTarget .path("books/" + outBook.getId()) .request(MediaType.APPLICATION_JSON) .get(); assertEquals(Response.Status.OK.getStatusCode(), bookResponse.getStatus()); outBook = bookResponse.readEntity(Book.class); assertEquals("Book", outBook.getTitle()); assertEquals(1, outBook.getAuthors().size()); assertEquals("Foo", outBook.getAuthors().get(0).getName()); } @Test @RunAsClient public void testCreateBookWithVolumes(@ArquillianResteasyResource("") WebTarget webTarget) throws Exception { Volume volume = new Volume(); volume.setBarcodeId(123); Book book = new Book(); book.setTitle("Book"); book.setISBN("1234"); book.getVolumes().add(volume); Response bookResponse = webTarget .path("books") .request(MediaType.APPLICATION_JSON) .post(Entity.json(book)); assertEquals(Response.Status.CREATED.getStatusCode(), bookResponse.getStatus()); Book outBook = bookResponse.readEntity(Book.class); assertNotNull(outBook.getId()); bookResponse = webTarget .path("books/" + outBook.getId()) .request(MediaType.APPLICATION_JSON) .get(); assertEquals(Response.Status.OK.getStatusCode(), bookResponse.getStatus()); outBook = bookResponse.readEntity(Book.class); assertEquals("Book", outBook.getTitle()); List<Volume> volumes = outBook.getVolumes(); assertEquals(1, volumes.size()); Volume outVolume = volumes.get(0); assertEquals(123, outVolume.getBarcodeId()); } }
package com.a2017hkt15.sortaddr; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import com.example.mylibrary.SlidingUpPanelLayout; import com.skp.Tmap.TMapData; import com.skp.Tmap.TMapGpsManager; import com.skp.Tmap.TMapMarkerItem; import com.skp.Tmap.TMapPOIItem; import com.skp.Tmap.TMapView; import java.util.ArrayList; import java.util.Collections; public class InputActivity extends AppCompatActivity implements TMapGpsManager.onLocationChangedCallback { private SlidingUpPanelLayout mLayout; private MarkerController markerController; private CheckBox comeback; private PathBasic pathBasic; private int button_pos; private ListView listview; private ListViewAdapter adapter; private AddressInfo addressInfo = new AddressInfo(); //AddressInfo class private ArrayList<AddressInfo> AddressInfo_array = new ArrayList<>(Collections.nCopies(10,new AddressInfo())); String address_lat_lon; float lat; float lon; static ProgressDialog progressDialog; public static Context mContext; private TMapGpsManager tmapgps = null; private TMapView tmapview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_input); mContext=this; Variable.numberOfLine=0; comeback=(CheckBox)findViewById(R.id.comeBack); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_input); setSupportActionBar(toolbar); toolbar.setTitle(R.string.app_name); String subtitle = " : 10 "; toolbar.setSubtitle(subtitle); toolbar.setTitleTextColor(Color.WHITE); toolbar.setSubtitleTextColor(ContextCompat.getColor(InputActivity.this, R.color.colorSubtitle)); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } LinearLayout layoutForMap = (LinearLayout) findViewById(R.id.layout_for_map); tmapview = new TMapView(this); tmapview.setSKPMapApiKey(Variable.mapApiKey); tmapview.setCompassMode(false); tmapview.setIconVisibility(true); tmapview.setZoomLevel(8); tmapview.setMapType(TMapView.MAPTYPE_STANDARD); tmapview.setLanguage(TMapView.LANGUAGE_KOREAN); tmapgps = new TMapGpsManager(InputActivity.this); tmapgps.setMinTime(1000); tmapgps.setMinDistance(5); tmapgps.setProvider(tmapgps.NETWORK_PROVIDER); // tmapgps.setProvider(tmapgps.GPS_PROVIDER); tmapgps.OpenGps(); tmapview.setTrackingMode(true); tmapview.setSightVisible(true); tmapview.setTrafficInfo(true); tmapview.setOnCalloutRightButtonClickListener(new TMapView.OnCalloutRightButtonClickCallback() { @Override public void onCalloutRightButton(TMapMarkerItem markerItem) { Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY, markerItem.getName()); startActivity(intent); } }); layoutForMap.addView(tmapview); // Adapter adapter = new ListViewAdapter(this); // Adapter listview = (ListView) findViewById(R.id.wayListView1); listview.setAdapter(adapter); listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); adapter.addItem(""); addLine(); ImageButton addimageButton = (ImageButton) findViewById(R.id.addimageButton); addimageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addLine(); } }); Context context = getApplicationContext(); Bitmap startIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.start); Bitmap passIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.pass); Bitmap endIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.end); Bitmap poiIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.search); Bitmap[] numberIcon = new Bitmap[10]; numberIcon[1] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark1); numberIcon[2] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark2); numberIcon[3] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark3); numberIcon[4] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark4); numberIcon[5] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark5); numberIcon[6] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark6); numberIcon[7] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark7); numberIcon[8] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark8); numberIcon[9] = BitmapFactory.decodeResource(context.getResources(), R.drawable.mark9); markerController = new MarkerController(tmapview, startIcon, passIcon, numberIcon, endIcon, poiIcon); pathBasic = new PathBasic(tmapview, markerController); mLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_input, menu); return true; } @Override public void onLocationChange(Location location) { tmapview.setLocationPoint(location.getLongitude(), location.getLatitude()); } @Override public boolean onOptionsItemSelected(android.view.MenuItem item) { switch (item.getItemId()) { case R.id.action_bt1: findButton(); break; case android.R.id.home: Variable.numberOfLine = 0; finish(); break; } return super.onOptionsItemSelected(item); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { progressDialog.dismiss(); // View } }; private void findButton() { if (AddressInfo_array.size() > 1) { //1 1 progressDialog = ProgressDialog.show(InputActivity.this, " ", " "); mHandler = new Handler(); Thread thread = new Thread(new Runnable() { @Override public void run() { pathBasic.calcDistancePath(markerController.getMarkerList(),comeback.isChecked()); mHandler.sendEmptyMessage(0); } }); thread.start(); // mHandler.postDelayed(new Runnable() { // @Override // public void run() { // pathBasic.calcDistancePath(markerController.getMarkerList(),comeback.isChecked()); // }, 1000); } else if (AddressInfo_array.size() == 0) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(InputActivity.this); alertDialog.setTitle("") .setMessage(" ") .setPositiveButton("", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = alertDialog.create(); dialog.show(); } else if (AddressInfo_array.size() == 1) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(InputActivity.this); alertDialog.setTitle("") .setMessage(" ") .setPositiveButton("", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = alertDialog.create(); dialog.show(); } } private void addLine() { if (Variable.numberOfLine < 10) { adapter.addItem(""); } else { Toast.makeText(getApplicationContext(), " .", Toast.LENGTH_LONG).show(); } } //AutoComplete //position, address_name public void onActivityResult(int requestCode, int resultCode, Intent intent) {int division = getIntent().getIntExtra("division",0); if(resultCode == RESULT_OK) { if (requestCode == 10) { final int position = intent.getIntExtra("position", 0); final String address_name = intent.getStringExtra("address_name"); addressInfo.setAddr(address_name); adapter.getItem(position).setAddrStr(address_name); Log.d("dd", "nodeNum : " + Variable.nodeNum); adapter.getItem(Variable.nodeNum).setAddrStr(address_name); //edittext setText adapter.notifyDataSetChanged(); runOnUiThread(new Runnable() { public void run() { TMapData tdata = new TMapData(); tdata.findAllPOI(address_name, new TMapData.FindAllPOIListenerCallback() { @Override public void onFindAllPOI(ArrayList<TMapPOIItem> poiItem) { String[] array; TMapPOIItem item2 = poiItem.get(poiItem.size() - 1); array = item2.getPOIPoint().toString().split(" "); lat = Float.parseFloat(array[1]); addressInfo.setLat(Float.parseFloat(array[1])); lon = Float.parseFloat(array[3]); addressInfo.setLon(lon); } }); } }); Handler mHandler = new Handler(); mHandler.postDelayed(new Runnable() { @Override public void run() { address_lat_lon = address_name + "," + String.valueOf(addressInfo.getLat()) + "," + String.valueOf(addressInfo.getLon()); if (position < AddressInfo_array.size()) { AddressInfo_array.remove(position); AddressInfo_array.add(position, addressInfo); } else if (position == AddressInfo_array.size()) { AddressInfo_array.add(position, addressInfo); } // AddressInfo_array.add(position, addressInfo); if (position == 0) { markerController.setStartMarker(AddressInfo_array.get(position).getLat(), AddressInfo_array.get(position).getLon(), AddressInfo_array.get(0).getAddr()); } else { if (position < markerController.getMarkerList().size()) { markerController.removeMarker(position); markerController.addMarker(AddressInfo_array.get(position).getLat(), AddressInfo_array.get(position).getLon(), AddressInfo_array.get(position).getAddr(), position); } else if (position == markerController.getMarkerList().size()) { markerController.addMarker(AddressInfo_array.get(position).getLat(), AddressInfo_array.get(position).getLon(), AddressInfo_array.get(position).getAddr()); } } } }, 1000); } if (requestCode == 2) { final int position = intent.getIntExtra("position_full", 0); final String address_name = intent.getStringExtra("fulladdress"); addressInfo.setAddr(address_name); adapter.getItem(position).setAddrStr(address_name); //edittext setText adapter.notifyDataSetChanged(); final float lat = intent.getFloatExtra("lati_full", 0); final float lon = intent.getFloatExtra("lon_full", 0); addressInfo.setAddr(address_name); addressInfo.setLat(lat); addressInfo.setLon(lon); Handler mHandler = new Handler(); mHandler.postDelayed(new Runnable() { @Override public void run() { address_lat_lon = address_name + "," + String.valueOf(addressInfo.getLat()) + "," + String.valueOf(addressInfo.getLon()); if (position < AddressInfo_array.size()) { AddressInfo_array.remove(position); AddressInfo_array.add(position, addressInfo); } else if (position == AddressInfo_array.size()) { AddressInfo_array.add(position, addressInfo); } // AddressInfo_array.add(position, addressInfo); if (position == 0) { markerController.setStartMarker(AddressInfo_array.get(position).getLat(), AddressInfo_array.get(position).getLon(), AddressInfo_array.get(0).getAddr()); } else { if (position < markerController.getMarkerList().size()) { markerController.removeMarker(position); markerController.addMarker(AddressInfo_array.get(position).getLat(), AddressInfo_array.get(position).getLon(), AddressInfo_array.get(position).getAddr(), position); } else if (position == markerController.getMarkerList().size()) { markerController.addMarker(AddressInfo_array.get(position).getLat(), AddressInfo_array.get(position).getLon(), AddressInfo_array.get(position).getAddr()); } } } }, 1000); } } else if (resultCode == RESULT_CANCELED) { } Log.d("supl","supl end"); // mLayout.setPanelHeight(Variable.panelHeight); } public int getButton_pos() { return button_pos; } public void setButton_pos(int button_pos) { this.button_pos = button_pos; } public ArrayList<AddressInfo> getAddressInfo_array() { return AddressInfo_array; } public void setAddressInfo_array(ArrayList<AddressInfo> addressInfo_array) { AddressInfo_array = addressInfo_array; } public MarkerController getMarkerController() { return markerController; } public void setMarkerController(MarkerController markerController) { this.markerController = markerController; } }
package com.txt_nifty.sketch.flmml; import android.media.AudioTrack; import android.os.Handler; import android.util.Log; import com.txt_nifty.sketch.flmml.rep.Callback; import com.txt_nifty.sketch.flmml.rep.ConvertedBufferHolder; import com.txt_nifty.sketch.flmml.rep.EventDispatcher; import com.txt_nifty.sketch.flmml.rep.Sound; import java.util.ArrayList; public class MSequencer extends EventDispatcher implements Sound.Writer { public static final int BUFFER_SIZE = 8192; public static final int RATE44100 = 44100; private static final int STATUS_STOP = 0; private static final int STATUS_PAUSE = 1; private static final int STATUS_BUFFERING = 2; private static final int STATUS_PLAY = 3; private static final int STATUS_LAST = 4; private static int sOutputType = Sound.RECOMMENDED_ENCODING; private final int mMultiple; private final BufferingRunnable mBufferingRunnable; private final double[][] mDoubleBuffer; private final ArrayList<MTrack> mTrackArr; private final MSignal[] mSignalArr; private final Runnable mRestTimer; private final Handler mHandler; private final Object mBufferLock = new Object(); public volatile Callback onSignal = null; private volatile boolean mBuffStop; private volatile Sound mSound; private volatile ConvertedBufferHolder[] mBufferHolder; private int mSignalPtr; private volatile int mPlaySide; private volatile int mPlaySize; private volatile boolean mBufferCompleted; private volatile long mPausedPos; private int mSignalInterval; private long mGlobalTick; private volatile long mStartTime; private volatile int mStatus; MSequencer() { this(32); } MSequencer(int multiple) { mMultiple = multiple; mTrackArr = new ArrayList<>(); mSignalArr = new MSignal[3]; for (int i = 0; i < mSignalArr.length; i++) { MSignal sig = new MSignal(i); sig.setFunction(new Callback() { public void call(int... a) { onSignalHandler(a[0], a[1]); } }); mSignalArr[i] = sig; } mSignalPtr = 0; int bufsize = MSequencer.BUFFER_SIZE * mMultiple * 2; mDoubleBuffer = new double[2][bufsize]; mPlaySide = 1; mPlaySize = 0; mBufferCompleted = false; mSound = new Sound(sOutputType, this); mBufferHolder = new ConvertedBufferHolder[2]; for (int i = 0; i < 2; i++) { mBufferHolder[i] = Sound.makeBufferHolder(mSound, bufsize); } mPausedPos = 0; setMasterVolume(100); mSignalInterval = 96; mHandler = new Handler(); mRestTimer = new Runnable() { @Override public void run() { onStopReq(); } }; stop(); mBufferingRunnable = new BufferingRunnable(); mBuffStop = true; Thread thread = new Thread(mBufferingRunnable, "MSequencer-Buffering"); thread.setDaemon(true); thread.start(); } public static void setOutput(int type) { sOutputType = type; } public static int getOutputType() { return sOutputType; } private void prepareSound(boolean rewrite) { if (mSound.getOutputFormat() != sOutputType) { mSound.release(); int vol = mSound.getVolume(); mSound = new Sound(sOutputType, this); mSound.setVolume(vol); for (int i = 0, bufsize = MSequencer.BUFFER_SIZE * mMultiple * 2; i < 2; i++) { mBufferHolder[i] = Sound.makeBufferHolder(mSound, bufsize); } if (rewrite) mBufferingRunnable.rewriteReq(); } } public void play() { if (mStatus != STATUS_PAUSE) { stop(); prepareSound(false); mGlobalTick = 0; for (int i = 0, len = mTrackArr.size(); i < len; i++) { mTrackArr.get(i).seekTop(); } mStatus = STATUS_BUFFERING; processStart(); } else { mStatus = STATUS_PLAY; prepareSound(true); mSound.start(); mStartTime = System.currentTimeMillis(); long totl = getTotalMSec(); long rest = (totl > mPausedPos) ? (totl - mPausedPos) : 0; mHandler.postDelayed(mRestTimer, rest); } } public void stop() { synchronized (mBufferLock) { mHandler.removeCallbacks(mRestTimer); mStatus = STATUS_STOP; } mSound.stop(); mPausedPos = 0; } public void pause() { synchronized (mBufferLock) { mHandler.removeCallbacks(mRestTimer); mStatus = STATUS_PAUSE; } mSound.pause(); mPausedPos = getNowMSec(); } public void setMasterVolume(int i) { mSound.setVolume(i); } public boolean isPlaying() { return (mStatus > STATUS_PAUSE); } public boolean isPaused() { return (mStatus == STATUS_PAUSE); } public void disconnectAll() { synchronized (mTrackArr) { mBuffStop = true; } mTrackArr.clear(); mStatus = STATUS_STOP; } public void connect(MTrack track) { track.mSignalInterval = mSignalInterval; mTrackArr.add(track); } public long getGlobalTick() { return mGlobalTick; } public void setSignalInterval(int interval) { mSignalInterval = interval; } private void onSignalHandler(int globalTick, int event) { mGlobalTick = globalTick; if (onSignal != null) onSignal.call(globalTick, event); } private void reqStop() { onStopReq(); } private void onStopReq() { stop(); dispatchEvent(new MMLEvent(MMLEvent.COMPLETE)); } private void reqBuffering() { onBufferingReq(); } private void onBufferingReq() { pause(); mStatus = STATUS_BUFFERING; } private void processStart() { mBufferCompleted = false; mBuffStop = false; synchronized (mBufferingRunnable) { mBufferingRunnable.notify(); } } private void processAll() { int sLen = MSequencer.BUFFER_SIZE * mMultiple; ArrayList<MTrack> tracks = mTrackArr; int nLen = tracks.size(); double[] buffer = mDoubleBuffer[1 - mPlaySide]; for (int i = sLen * 2 - 1; i >= 0; i buffer[i] = 0; } /* if (nLen > 0) { MTrack track = mTrackArr.get(MTrack.TEMPO_TRACK); track.onSampleData(buffer, 0, sLen, mSignalArr[mSignalPtr]); }*/ for (int processTrack = MTrack.FIRST_TRACK; processTrack < nLen; processTrack++) { if (mStatus == STATUS_STOP) return; tracks.get(processTrack).onSampleData(buffer, 0, sLen); if (mStatus == STATUS_BUFFERING) dispatchEvent(new MMLEvent(MMLEvent.BUFFERING, 0, 0, (processTrack + 2) * 100 / (nLen + 1))); } mBufferHolder[1 - mPlaySide].convertAndSet(buffer); synchronized (mBufferLock) { mBufferCompleted = true; if (mStatus == STATUS_PAUSE && mPlaySize >= mMultiple) { mPlaySide = 1 - mPlaySide; mPlaySize = 0; processStart(); } if (mStatus == STATUS_BUFFERING) { mStatus = STATUS_PLAY; mPlaySide = 1 - mPlaySide; mPlaySize = 0; processStart(); mSound.start(); mStartTime = System.currentTimeMillis(); long totl = getTotalMSec(); long rest = (totl > mPausedPos) ? (totl - mPausedPos) : 0; mHandler.postDelayed(mRestTimer, rest); } } } public void onSampleData(AudioTrack track) { if (mPlaySize >= mMultiple) { synchronized (mBufferLock) { if (mBufferCompleted) { mPlaySide = 1 - mPlaySide; mPlaySize = 0; processStart(); } else { reqBuffering(); return; } } if (mStatus == STATUS_LAST) { Log.v("MSequncer", "STATUS_LAST"); return; } else if (mStatus == STATUS_PLAY && mTrackArr.get(MTrack.TEMPO_TRACK).isEnd() != 0) { mStatus = STATUS_LAST; Log.v("MSequncer", "-> STATUS_LAST"); } } ConvertedBufferHolder bufholder = mBufferHolder[mPlaySide]; int base = (BUFFER_SIZE * mPlaySize) * 2; int len = BUFFER_SIZE << 1; int written = bufholder.writeTo(track, base, len); if (written < len) { //AudioTrack mSound.startPlaying(); bufholder.writeTo(track, base + written, len - written); } mPlaySize++; mSignalPtr = (++mSignalPtr) % mSignalArr.length; } public void createPipes(int num) { MChannel.createPipes(num); } public void createSyncSources(int num) { MChannel.createSyncSources(num); } public long getTotalMSec() { return mTrackArr.get(MTrack.TEMPO_TRACK).getTotalMSec(); } public long getNowMSec() { return mSound.getPlaybackMSec(); /* long now; long tot = getTotalMSec(); switch (mStatus) { case STATUS_PLAY: case STATUS_LAST: now = System.currentTimeMillis() - mStartTime + mPausedPos; return (now < tot) ? now : tot; default: return mPausedPos; } */ } public String getNowTimeStr() { int sec = (int) Math.ceil(getNowMSec() / 1000d); StringBuilder sb = new StringBuilder(); int smin = sec / 60 % 100, ssec = sec % 60; if (smin < 10) sb.append('0'); sb.append(smin).append(':'); if (ssec < 10) sb.append('0'); sb.append(ssec); return sb.toString(); } private class BufferingRunnable implements Runnable { private volatile boolean rewrite = false; public void rewriteReq() { rewrite = true; synchronized (this) { this.notify(); } } @Override public void run() { MChannel.boot(MSequencer.BUFFER_SIZE * mMultiple); MOscillator.boot(); MEnvelope.boot(); MSequencer m = MSequencer.this; while (true) { if (mBuffStop) synchronized (this) { try { this.wait(); if (rewrite) { rewrite = false; mBufferHolder[0].convertAndSet(mDoubleBuffer[0]); mBufferHolder[1].convertAndSet(mDoubleBuffer[1]); } } catch (InterruptedException e) { } } synchronized (mTrackArr) { if (!mBuffStop) { mBuffStop = true; m.processAll(); } } } //Log.v("BufferingThread", "Thread finish."); } } }
package fyp.hkust.facet.activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.view.GravityCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.text.Spannable; import android.text.SpannableString; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.RatingBar; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TextView; import android.widget.Toast; import com.github.pwittchen.swipe.library.Swipe; import com.github.pwittchen.swipe.library.SwipeListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import com.webianks.library.PopupBubble; import java.io.File; import java.text.DateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import de.hdodenhof.circleimageview.CircleImageView; import fyp.hkust.facet.R; import fyp.hkust.facet.adapter.ArrayAdapterWithIcon; import fyp.hkust.facet.model.Brand; import fyp.hkust.facet.model.Product; import fyp.hkust.facet.model.User; import fyp.hkust.facet.skincolordetection.CaptureActivity; import fyp.hkust.facet.skincolordetection.ShowCameraViewActivity; import fyp.hkust.facet.util.CheckConnectivity; import fyp.hkust.facet.util.CustomTypeFaceSpan; import fyp.hkust.facet.util.FontManager; public class MainActivity extends AppCompatActivity { private final static String TAG = "MainActivity"; private static View activity_main_layout; private static final int GALLERY_REQUEST = 1; private static final int CAM_REQUEST = 3; private RecyclerView mProductList; private GridLayoutManager mgr; private DatabaseReference mDatabase; private DatabaseReference mDatabaseBrand; private DatabaseReference mDatabaseUsers; private DatabaseReference mDatabaseRatings; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private static final String NAV_ITEM_ID = "nav_index"; DrawerLayout drawerLayout; private int navItemId; private Toolbar toolbar; private NavigationView view; private Map<String, Product> mProducts = new HashMap<String, Product>(); private Map<String, Brand> mBrand = new HashMap<String, Brand>(); private List<String> brandList = new ArrayList<>(); private int order = 1; private int categoryResult = 0; private int sort = 0; private Spinner filterSpinner; private Spinner orderSpinner; private int brandResult = 0; private static int firstTime = 0; private Map<String, Product> mSortedProducts = new HashMap<String, Product>(); private ProductAdapter mProductAdapter; private ProgressDialog dialog; private TabLayout tabLayout; private SearchView searchView; private MenuItem mMenuItem; private int[] tabIcons = { R.drawable.foundation, R.drawable.blush, R.drawable.eyeshadow, R.drawable.lipstick }; private List<String> brandIDList = new ArrayList<>(); private PopupBubble new_product_popup_bubble; private Swipe swipe; private NavigationView sort_view; private String captureImageFullPath; private int buttonNumber = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activity_main_layout = (CoordinatorLayout) findViewById(R.id.activity_main_layout); CheckConnectivity check = new CheckConnectivity(); Boolean conn = check.checkNow(this.getApplicationContext()); if (conn == true) { //run your normal code path here Log.d(TAG, "Network connected"); } else { //Send a warning message to the user Snackbar snackbar = Snackbar.make(activity_main_layout, "No Internet Access", Snackbar.LENGTH_LONG); snackbar.show(); } //start Typeface fontType = FontManager.getTypeface(getApplicationContext(), FontManager.APP_FONT); Typeface titleFontType = FontManager.getTypeface(getApplicationContext(), FontManager.ROOT + FontManager.TITLE_FONT); FontManager.markAsIconContainer(findViewById(R.id.activity_main_layout), fontType); toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setBackground(new ColorDrawable(Color.parseColor("#00000000"))); setSupportActionBar(toolbar); TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title); toolbarTitle.setTypeface(titleFontType); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); view = (NavigationView) findViewById(R.id.navigation_view); applyCustomFontToWholeMenu(); view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // Toast.makeText(MainActivity.this, menuItem.getTitle() + " pressed", Toast.LENGTH_LONG).show(); navigateTo(menuItem); drawerLayout.closeDrawer(GravityCompat.START); return true; } }); //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { // This method will trigger on item Click of navigation menu @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Check to see which item was being clicked and perform appropriate action switch (menuItem.getItemId()) { //Replacing the main content with ContentFragment Which is our Inbox View; case R.id.nav_facet_match: navItemId = 0; showAlertDialog(); menuItem.setChecked(true); break; case R.id.nav_virtual_makeup: navItemId = 1; showMakeUpDialog(); menuItem.setChecked(true); break; case R.id.nav_product: navItemId = 2; startActivity(new Intent(MainActivity.this, MainActivity.class)); menuItem.setChecked(true); break; case R.id.nav_store_location: navItemId = 3; startActivity(new Intent(MainActivity.this, ShopListActivity.class)); menuItem.setChecked(true); break; case R.id.nav_profile: navItemId = 4; startActivity(new Intent(MainActivity.this, ProfileActivity.class)); menuItem.setChecked(true); break; case R.id.nav_setting: navItemId = 5; startActivity(new Intent(MainActivity.this, SettingsActivity.class)); menuItem.setChecked(true); break; } //Checking if the item is in checked state or not, if not make it in checked state if (menuItem.isChecked()) { menuItem.setChecked(false); } else { menuItem.setChecked(true); } menuItem.setChecked(true); return true; } }); setupTabLayout(); sort_view = (NavigationView) findViewById(R.id.sort_navigation_view); sort_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // Toast.makeText(MainActivity.this, menuItem.getTitle() + " pressed", Toast.LENGTH_LONG).show(); drawerLayout.closeDrawer(GravityCompat.END); /*Important Line*/ return true; } }); setupRightDrawer(); ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); } }; drawerLayout.setDrawerListener(actionBarDrawerToggle); actionBarDrawerToggle.syncState(); if (null != savedInstanceState) { navItemId = savedInstanceState.getInt(NAV_ITEM_ID, R.id.nav_product); } else { navItemId = R.id.nav_product; } navigateTo(view.getMenu().findItem(navItemId)); //end mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (firebaseAuth.getCurrentUser() != null) { setupNavHeader(); } } }; mAuth.addAuthStateListener(mAuthListener); mDatabase = FirebaseDatabase.getInstance().getReference().child("Product"); mDatabase.keepSynced(true); mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users"); mDatabaseUsers.keepSynced(true); mDatabaseBrand = FirebaseDatabase.getInstance().getReference().child("Brand"); mDatabaseRatings = FirebaseDatabase.getInstance().getReference().child("Ratings"); mDatabaseRatings.keepSynced(true); Log.d(TAG + "mDatabaseRatings", mDatabaseRatings.toString()); mProductList = (RecyclerView) findViewById(R.id.product_list); mgr = new GridLayoutManager(this, 2); mProductList.setLayoutManager(mgr); mProductList.setItemAnimator(new DefaultItemAnimator()); new_product_popup_bubble = (PopupBubble) findViewById(R.id.new_product_popup_bubble); new_product_popup_bubble.setPopupBubbleListener(new PopupBubble.PopupBubbleClickListener() { @Override public void bubbleClicked(Context context) { mProductList.getLayoutManager().scrollToPosition(0); //popup_bubble is clicked } }); new_product_popup_bubble.setRecyclerView(mProductList); checkUserExist(); } private void setupTabLayout() { tabLayout = (TabLayout) findViewById(R.id.tabs); Resources res = getResources(); final String[] category = res.getStringArray(R.array.category_type_array); tabLayout.addTab(tabLayout.newTab().setText(category[0])); tabLayout.addTab(tabLayout.newTab().setText(category[1])); tabLayout.addTab(tabLayout.newTab().setText(category[2])); tabLayout.addTab(tabLayout.newTab().setText(category[3])); tabLayout.addTab(tabLayout.newTab().setText(category[4])); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(final TabLayout.Tab tab) { if (tabLayout.getSelectedTabPosition() == 0) { categoryResult = 0; setupProductList(); // Toast.makeText(MainActivity.this, "Tab " + tabLayout.getSelectedTabPosition(), Toast.LENGTH_SHORT).show(); } else if (tabLayout.getSelectedTabPosition() == 1) { categoryResult = 1; setupProductList(); // Toast.makeText(MainActivity.this, "Tab " + tabLayout.getSelectedTabPosition(), Toast.LENGTH_SHORT).show(); } else if (tabLayout.getSelectedTabPosition() == 2) { categoryResult = 2; setupProductList(); // Toast.makeText(MainActivity.this, "Tab " + tabLayout.getSelectedTabPosition(), Toast.LENGTH_SHORT).show(); } else if (tabLayout.getSelectedTabPosition() == 3) { categoryResult = 3; setupProductList(); // Toast.makeText(MainActivity.this, "Tab " + tabLayout.getSelectedTabPosition(), Toast.LENGTH_SHORT).show(); } else if (tabLayout.getSelectedTabPosition() == 4) { categoryResult = 4; setupProductList(); // Toast.makeText(MainActivity.this, "Tab " + tabLayout.getSelectedTabPosition(), Toast.LENGTH_SHORT).show(); } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } private void applyCustomFontToWholeMenu() { Menu m = view.getMenu(); for (int i = 0; i < m.size(); i++) { MenuItem mi = m.getItem(i); // //for applying a font to subMenu ... // SubMenu subMenu = mi.getSubMenu(); // if (subMenu!=null && subMenu.size() >0 ) { // for (int j=0; j <subMenu.size();j++) { // MenuItem subMenuItem = subMenu.getItem(j); // applyFontToMenuItem(subMenuItem); //the method we have create in activity applyFontToMenuItem(mi); } } private void applyFontToMenuItem(MenuItem mi) { Typeface fontType = FontManager.getTypeface(getApplicationContext(), FontManager.APP_FONT); SpannableString mNewTitle = new SpannableString(mi.getTitle()); mNewTitle.setSpan(new CustomTypeFaceSpan("", fontType), 0, mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); mi.setTitle(mNewTitle); } private void setupNavHeader() { View header = view.getHeaderView(0); final TextView usernameHeader = (TextView) header.findViewById(R.id.username_header); final TextView emailHeader = (TextView) header.findViewById(R.id.email_header); final CircleImageView headerphoto = (CircleImageView) header.findViewById(R.id.profile_image); headerphoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent accountIntent = new Intent(MainActivity.this, ProfileActivity.class); accountIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(accountIntent); } }); if (mAuth.getCurrentUser() != null) { mDatabaseUsers.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { final User user_data = dataSnapshot.getValue(User.class); if (user_data != null) { Typeface fontType = FontManager.getTypeface(getApplicationContext(), FontManager.APP_FONT); usernameHeader.setTypeface(fontType); emailHeader.setTypeface(fontType); usernameHeader.setText(user_data.getName()); if (user_data.getEmail() != null && user_data.getEmail().length() > 0) emailHeader.setText(user_data.getEmail()); else if (user_data.getEmail() == null || user_data.getEmail().length() == 0) emailHeader.setText(mAuth.getCurrentUser().getEmail()); Picasso.with(getApplicationContext()).load(user_data.getImage()).networkPolicy(NetworkPolicy.OFFLINE).into(headerphoto, new Callback() { @Override public void onSuccess() { } @Override public void onError() { Picasso.with(getApplicationContext()) .load(user_data.getImage()) .centerCrop() .fit() .into(headerphoto); } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } private void setupRightDrawer() { View sort_main_layout = (View) findViewById(R.id.sort_main_layout); View header2 = sort_view.getHeaderView(0); Typeface fontType = FontManager.getTypeface(getApplicationContext(), FontManager.APP_FONT); TextView refine_title = (TextView) header2.findViewById(R.id.refine_title); refine_title.setTypeface(fontType); Button apply_btn = (Button) sort_main_layout.findViewById(R.id.apply_btn); Button clear_btn = (Button) sort_main_layout.findViewById(R.id.clear_btn); final Button acensding_btn = (Button) sort_main_layout.findViewById(R.id.acensding_btn); final Button decensding_btn = (Button) sort_main_layout.findViewById(R.id.decensding_btn); apply_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setupProductList(); Log.d(TAG, " apply"); drawerLayout.closeDrawer(GravityCompat.END); } }); clear_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, " clear"); categoryResult = 0; order = 1; sort = 0; setupProductList(); drawerLayout.closeDrawer(GravityCompat.END); tabLayout.getTabAt(0).select(); } }); acensding_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, " order = 0"); decensding_btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_button_with_bg)); acensding_btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_button_no_bg)); decensding_btn.setTextColor(getResources().getColor(R.color.white)); acensding_btn.setTextColor(getResources().getColor(R.color.font_color_pirmary)); order = 0; } }); decensding_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, " order = 1"); acensding_btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_button_with_bg)); decensding_btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_button_no_bg)); acensding_btn.setTextColor(getResources().getColor(R.color.white)); decensding_btn.setTextColor(getResources().getColor(R.color.font_color_pirmary)); order = 1; } }); Resources res = getResources(); orderSpinner = (Spinner) findViewById(R.id.sort_spinner); final String[] sortString = res.getStringArray(R.array.sort_type_array); final ArrayAdapter<CharSequence> sortList = ArrayAdapter.createFromResource(MainActivity.this, R.array.sort_type_array, android.R.layout.simple_spinner_dropdown_item); orderSpinner.getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP); sortList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); orderSpinner.setSelection(order); orderSpinner.setAdapter(sortList); orderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView tmpView = (TextView) orderSpinner.getSelectedView().findViewById(android.R.id.text1); tmpView.setTextColor(Color.WHITE); // Toast.makeText(MainActivity.this, "You choose " + sortString[position], Toast.LENGTH_SHORT).show(); sort = position; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void onBackPressed() { super.onBackPressed(); if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else if (drawerLayout.isDrawerOpen(GravityCompat.END)) { /*Closes the Appropriate Drawer*/ drawerLayout.closeDrawer(GravityCompat.END); } else { this.finish(); } if (searchView != null && !searchView.isIconified()) { MenuItemCompat.collapseActionView(mMenuItem); return; } } @Override protected void onStart() { super.onStart(); setupNavHeader(); mDatabase.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.getChildren()) { Product result = ds.getValue(Product.class); if (result.getValidate() == 1) { mProducts.put(ds.getKey(), result); mProducts.get(ds.getKey()).setRating(Long.valueOf(0)); Log.d(" product " + ds.getKey(), result.toString()); } } mDatabaseRatings.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { int count = 0; double totalRating = 0.0; for (DataSnapshot ratingDs : dataSnapshot.getChildren()) { Map<String, Long> td = (HashMap<String, Long>) ratingDs.getValue(); List<String> keys = new ArrayList<>(td.keySet()); List<Long> values = new ArrayList<>(td.values()); for (int i = 0; i < values.size(); i++) { double temp = doubleValue(values.get(i)); Log.d(TAG + " temp", temp + ""); totalRating += temp; count++; } Log.d(" rating " + ratingDs.getKey(), ratingDs.getValue().toString()); Log.d(TAG + " totalRating / count ", totalRating + " " + count); if (count > 0 && mProducts.containsKey(ratingDs.getKey())) mProducts.get(ratingDs.getKey()).setRating((long) (totalRating / count)); count = 0; totalRating = 0.0; } mDatabaseBrand.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { brandIDList.clear(); brandList.clear(); for (DataSnapshot ds : dataSnapshot.getChildren()) { Brand result = ds.getValue(Brand.class); mBrand.put(ds.getKey(), result); brandIDList.add(ds.getKey()); brandList.add(result.getBrand()); Log.d(" brand " + ds.getKey(), result.toString()); Log.d(TAG, "going to filter"); mSortedProducts = filterProduct(mProducts, categoryResult); mProductAdapter = new ProductAdapter(mSortedProducts, getApplicationContext()); mProductList.setAdapter(mProductAdapter); mProductAdapter.notifyDataSetChanged(); filterSpinner = (Spinner) findViewById(R.id.shop_filter_spinner); final ArrayAdapter<String> categoryList = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, brandList); filterSpinner.setSelection(brandResult); categoryList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); filterSpinner.getBackground().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP); filterSpinner.setAdapter(categoryList); filterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { TextView tmpView = (TextView) filterSpinner.getSelectedView().findViewById(android.R.id.text1); tmpView.setTextColor(Color.WHITE); // Toast.makeText(MainActivity.this, "You choose " + brandList.get(position), Toast.LENGTH_SHORT).show(); if (firstTime > 0) { brandResult = position; } firstTime++; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onCancelled(DatabaseError error) { // Failed to read value Log.e(TAG, "Failed to get value.", error.toException()); } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private static double doubleValue(Object value) { return (value instanceof Number ? ((Number) value).doubleValue() : -1.0); } public void setupProductList() { // sort by name a - z if (mProducts.size() > 0) { mSortedProducts = filterProduct(mProducts, categoryResult); if (mSortedProducts.size() > 0) mSortedProducts = filterBrand(mSortedProducts, brandResult); if (mSortedProducts.size() > 0) mSortedProducts = sortByComparator(mSortedProducts, sort, order); mProductAdapter = new ProductAdapter(mSortedProducts, getApplicationContext()); mProductList.setAdapter(mProductAdapter); mProductAdapter.notifyDataSetChanged(); } } private Map<String, Product> filterBrand(Map<String, Product> unsortMap, int brandResult) { List<Map.Entry<String, Product>> temp = new LinkedList<Map.Entry<String, Product>>(unsortMap.entrySet()); //compare temp List<Map.Entry<String, Product>> temp2 = new LinkedList<Map.Entry<String, Product>>(unsortMap.entrySet()); int tempSize = temp2.size(); List<String> removeList = new ArrayList<>(); if (brandResult > 0) { for (int i = 0; i < tempSize; i++) { if (!brandIDList.get(brandResult).equals(temp2.get(i).getValue().getBrandID())) { Log.d(TAG + " remove : " + temp2.get(i).getKey(), brandIDList.get(categoryResult) + " : " + temp2.get(i).getValue().getBrandID()); removeList.add(temp2.get(i).getKey()); } } } Log.d("Filtered ", "Map"); // Maintaining insertion order with the help of LinkedList Map<String, Product> filteredMap = new LinkedHashMap<String, Product>(); for (Map.Entry<String, Product> entry : temp) { if (!removeList.contains(entry.getKey())) { filteredMap.put(entry.getKey(), entry.getValue()); Log.d(entry.getKey(), entry.getValue().getProductName() + " : " + entry.getValue().getBrandID()); } } return filteredMap; } private Map<String, Product> filterProduct(Map<String, Product> unsortMap, int categoryResult) { List<Map.Entry<String, Product>> temp = new LinkedList<Map.Entry<String, Product>>(unsortMap.entrySet()); //compare temp List<Map.Entry<String, Product>> temp2 = new LinkedList<Map.Entry<String, Product>>(unsortMap.entrySet()); int tempSize = temp2.size(); List<String> removeList = new ArrayList<>(); Resources res = getResources(); final String[] categoryArray = res.getStringArray(R.array.category_type_array); if (categoryResult > 0) { for (int i = 0; i < tempSize; i++) { if (!categoryArray[categoryResult].equals(temp2.get(i).getValue().getCategory())) { Log.d(TAG + " remove : " + temp2.get(i).getKey(), categoryArray[categoryResult] + " : " + temp2.get(i).getValue().getCategory()); removeList.add(temp2.get(i).getKey()); } } } Log.d("Filtered ", "Map"); // Maintaining insertion order with the help of LinkedList Map<String, Product> filteredMap = new LinkedHashMap<String, Product>(); for (Map.Entry<String, Product> entry : temp) { if (!removeList.contains(entry.getKey())) { filteredMap.put(entry.getKey(), entry.getValue()); Log.d(entry.getKey(), entry.getValue().getProductName() + " : " + entry.getValue().getCategory()); } } return filteredMap; } private static Map<String, Product> sortByComparator(Map<String, Product> unsortMap, int sort, final int order) { final StringBuilder sortOperation = new StringBuilder(""); List<Map.Entry<String, Product>> list = new LinkedList<Map.Entry<String, Product>>(unsortMap.entrySet()); // Sorting the list based on values switch (sort) { case 0: sortOperation.append("Sort by release date"); Collections.sort(list, new Comparator<Map.Entry<String, Product>>() { public int compare(Map.Entry<String, Product> o1, Map.Entry<String, Product> o2) { if (order == 0) { // sort by name a - z return o1.getValue().getReleaseDate().compareTo(o2.getValue().getReleaseDate()); } else { // sort by name z - a return o2.getValue().getReleaseDate().compareTo(o1.getValue().getReleaseDate()); } } }); break; case 1: sortOperation.append("Sort by product name"); Collections.sort(list, new Comparator<Map.Entry<String, Product>>() { public int compare(Map.Entry<String, Product> o1, Map.Entry<String, Product> o2) { if (order == 0) { // sort by name a - z return o1.getValue().getProductName().compareTo(o2.getValue().getProductName()); } else { // sort by name z - a return o2.getValue().getProductName().compareTo(o1.getValue().getProductName()); } } }); break; case 2: sortOperation.append("Sort by category"); Collections.sort(list, new Comparator<Map.Entry<String, Product>>() { public int compare(Map.Entry<String, Product> o1, Map.Entry<String, Product> o2) { if (order == 0) { // sort by name a - z return o1.getValue().getCategory().compareTo(o2.getValue().getCategory()); } else { // sort by name z - a return o2.getValue().getCategory().compareTo(o1.getValue().getCategory()); } } }); break; case 3: sortOperation.append("Sort by rating"); Collections.sort(list, new Comparator<Map.Entry<String, Product>>() { public int compare(Map.Entry<String, Product> o1, Map.Entry<String, Product> o2) { if (o1.getValue().getRating() != null && o2.getValue().getRating() != null) { if (order == 0) { // sort by name a - z Log.d(TAG, o1.getValue().getRating() + " " + o2.getValue().getRating()); return o1.getValue().getRating().compareTo(o2.getValue().getRating()); } else { // sort by name z - a Log.d(TAG, o1.getValue().getRating() + " " + o2.getValue().getRating()); return o2.getValue().getRating().compareTo(o1.getValue().getRating()); } } return 0; } }); break; } if (order == 0) { // sort by name a - z sortOperation.append(" in ascending order"); } else { // sort by name z - a sortOperation.append(" in descending order"); } // Maintaining insertion order with the help of LinkedList Map<String, Product> sortedMap = new LinkedHashMap<String, Product>(); for (Map.Entry<String, Product> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); Log.d("Sorted ", "Map"); Log.d(entry.getKey(), entry.getValue().toString()); } // Snackbar snackbar = Snackbar.make(activity_main_layout, sortOperation, Snackbar.LENGTH_SHORT); // snackbar.show(); return sortedMap; } private void checkUserExist() { if (mAuth.getCurrentUser() != null) { final String user_id = mAuth.getCurrentUser().getUid(); mDatabaseUsers.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (!dataSnapshot.hasChild(user_id)) { Intent mainIntent = new Intent(MainActivity.this, ProfileEditActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(mainIntent); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } final private android.support.v7.widget.SearchView.OnQueryTextListener queryListener = new android.support.v7.widget.SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String newText) { Map<String, Product> temp = new HashMap<>(mSortedProducts); for (Iterator<Map.Entry<String, Product>> i = temp.entrySet().iterator(); i.hasNext(); ) { Map.Entry<String, Product> e = i.next(); Product v = e.getValue(); if (!v.getProductName().contains(newText)) i.remove(); } mProductAdapter = new ProductAdapter(temp, MainActivity.this); mProductList.setAdapter(mProductAdapter); mProductAdapter.notifyDataSetChanged(); return true; } @Override public boolean onQueryTextSubmit(String query) { searchView.setFocusable(true); Log.d(TAG, "submit:" + query); Map<String, Product> temp = new HashMap<>(mSortedProducts); for (Iterator<Map.Entry<String, Product>> i = temp.entrySet().iterator(); i.hasNext(); ) { Map.Entry<String, Product> e = i.next(); Product v = e.getValue(); if (!v.getProductName().contains(query)) i.remove(); } mProductAdapter = new ProductAdapter(temp, MainActivity.this); mProductList.setAdapter(mProductAdapter); mProductAdapter.notifyDataSetChanged(); return false; } }; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); mMenuItem = menu.findItem(R.id.action_search); try { searchView = (SearchView) MenuItemCompat.getActionView(mMenuItem); searchView.setOnQueryTextListener(queryListener); } catch (Exception e) { Log.e(TAG, e.toString()); } return super.onCreateOptionsMenu(menu); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri pickedImage = data.getData(); Log.d(TAG, "selected!!!" + " : " + pickedImage.getPath()); // Let's read picked image path using content resolver String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(pickedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); Log.d(TAG + "Path:", picturePath); Intent intent = new Intent(); if (buttonNumber == 1) intent.setClass(MainActivity.this, CaptureActivity.class); else if (buttonNumber == 2) intent.setClass(MainActivity.this, ColorizeFaceActivity.class); intent.putExtra("path", picturePath); //intent.putExtra("color" , "" + mBlobColorHsv); startActivity(intent); } else if (requestCode == CAM_REQUEST) { Intent intent = new Intent(); intent.setClass(MainActivity.this, ColorizeFaceActivity.class); intent.putExtra("path", captureImageFullPath); startActivity(intent); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_refine) { drawerLayout.openDrawer(GravityCompat.END); /*Opens the Right Drawer*/ } return super.onOptionsItemSelected(item); } private void navigateTo(MenuItem menuItem) { // contentView.setText(menuItem.getTitle()); navItemId = menuItem.getItemId(); menuItem.setChecked(true); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(NAV_ITEM_ID, navItemId); } public class ProductAdapter extends RecyclerView.Adapter<ProductViewHolder> { private Map<String, Product> mResultProducts = new HashMap<>(); // Allows to remember the last item shown on screen private int lastPosition = -1; private Context context; public ProductAdapter(Map<String, Product> mProducts, Context c) { this.context = c; this.mResultProducts = mProducts; notifyDataSetChanged(); } @Override public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); View view = getLayoutInflater().inflate(R.layout.product_row, parent, false); ProductViewHolder viewHolder = new ProductViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(ProductViewHolder viewHolder, int position) { List<Product> values = new ArrayList<>(mResultProducts.values()); final Product model = values.get(position); List<String> keys = new ArrayList<>(mResultProducts.keySet()); final String product_id = keys.get(position); Log.d(TAG + " product_id", product_id); Log.d(TAG + " product time", model.getReleaseDate() + ""); Log.d(TAG + " product name", model.getProductName()); Log.d(TAG + " product category", model.getCategory()); Log.d(TAG, "loading view " + position); // Log.d(TAG + " product id ", product_id); viewHolder.setProductName(model.getProductName()); if (mBrand != null) viewHolder.setBrandName(mBrand.get(model.getBrandID()).getBrand()); viewHolder.setImage(getApplicationContext(), model.getProductImage()); viewHolder.setUid(model.getUid()); if (model.getRating() == null) viewHolder.setRating((long) 0); else viewHolder.setRating(model.getRating()); viewHolder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent productDetailIntent = new Intent(); productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class); productDetailIntent.putExtra("product_id", product_id); Log.d(TAG + " product_id", product_id); productDetailIntent.putExtra("colorNo", model.getColorNo()); Log.d(TAG + " colorNo", model.getColorNo() + ""); startActivity(productDetailIntent); } }); setAnimation(viewHolder.itemView, position); Log.d(TAG, "finish loading view"); } /** * Here is the key method to apply the animation */ private void setAnimation(View viewToAnimate, int position) { // If the bound view wasn't previously displayed on screen, it's animated if (position > lastPosition) { Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in); animation.setDuration(500); viewToAnimate.startAnimation(animation); lastPosition = position; } } @Override public int getItemCount() { return mResultProducts == null ? 0 : mResultProducts.size(); } } public static class ProductViewHolder extends RecyclerView.ViewHolder { View mView; private Typeface customTypeface = Typeface.createFromAsset(itemView.getContext().getAssets(), FontManager.APP_FONT); public ProductViewHolder(View itemView) { super(itemView); mView = itemView; } public void setRating(Long rating) { RatingBar product_rating_bar = (RatingBar) mView.findViewById(R.id.product_rating_bar); product_rating_bar.setRating(rating); SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(itemView.getContext()); boolean ratingDisplayCheck = SP.getBoolean("ratingButton", true); if (ratingDisplayCheck == false) product_rating_bar.setVisibility(View.INVISIBLE); Log.d(TAG + " ratingDisplayCheck", ratingDisplayCheck + ""); } public void setProductName(String productName) { TextView product_title = (TextView) mView.findViewById(R.id.p_title); product_title.setText(productName); product_title.setTypeface(customTypeface, Typeface.BOLD); } public void setBrandName(String brand) { TextView product_desc = (TextView) mView.findViewById(R.id.p_desc); product_desc.setText(brand); product_desc.setTypeface(customTypeface); } public void setUid(String uid) { TextView product_username = (TextView) mView.findViewById(R.id.p_username); product_username.setText(uid); product_username.setTypeface(customTypeface); } public void setImage(final Context ctx, final String image) { final ImageView post_image = (ImageView) mView.findViewById(R.id.product_image); Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() { @Override public void onSuccess() { Log.d(TAG, "image loading success !"); } @Override public void onError() { Log.d(TAG, "image loading error !"); Picasso.with(ctx) .load(image) .resize(100, 100) .centerCrop() .into(post_image); } }); } } private void showAlertDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose the way to get your selfie"); builder.setIcon(R.drawable.app_icon_100); builder.setCancelable(true); final String[] items = new String[]{"From Gallery", "Take Photo"}; final Integer[] icons = new Integer[]{R.drawable.colorful_gallery_s, R.drawable.colorful_camera_s}; ListAdapter adapter = new ArrayAdapterWithIcon(getApplication(), items, icons); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: { buttonNumber = 1; Intent intent = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, GALLERY_REQUEST); break; } case 1: { Intent cameraViewIntent = new Intent(MainActivity.this, ShowCameraViewActivity.class); // cameraViewIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(cameraViewIntent); break; } } } }).show(); } private void showMakeUpDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose the way to get your selfie"); builder.setIcon(R.drawable.app_icon_100); builder.setCancelable(true); final String[] items = new String[]{"From Gallery", "Take Photo"}; final Integer[] icons = new Integer[]{R.drawable.colorful_gallery_s, R.drawable.colorful_camera_s}; ListAdapter adapter = new ArrayAdapterWithIcon(getApplication(), items, icons); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: { buttonNumber = 2; Intent intent = new Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, GALLERY_REQUEST); break; } case 1: { Intent cameraViewIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File file = getFile(); cameraViewIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); startActivityForResult(cameraViewIntent, CAM_REQUEST); break; } } } }).show(); } private File getFile() { File folder = new File("sdcard/FaceT"); if (!folder.exists()) { folder.mkdir(); } String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date()); captureImageFullPath = folder + "/makeup_" + currentDateTimeString; File imageFile = new File(captureImageFullPath); return imageFile; } }
package co.adhoclabs; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * A schema that describes the format of documents. * * @author Michael Parker (michael.g.parker@gmail.com) */ public class DocumentSchema { private static abstract class Value { public enum Type { OBJECT, ARRAY, STRING, BOOLEAN, INTEGER, FLOAT, NULL } public abstract Type getType(); public abstract void toString(StringBuilder sb); public String toString() { StringBuilder sb = new StringBuilder(); toString(sb); return sb.toString(); } } /** * A value for {@link JSONObject}. */ private static final class ObjectValue extends Value { private static final class Entry { private final String name; private final Value value; private Entry(String name, Value value) { this.name = name; this.value = value; } } private final List<Entry> entries; private ObjectValue(List<Entry> entries) { this.entries = entries; } public Type getType() { return Type.OBJECT; } public void toString(StringBuilder sb) { sb.append("{"); int index = 0; final int lastIndex = entries.size() - 1; for (Entry entry : entries) { sb.append(entry.name).append(": "); entry.value.toString(sb); if (index++ < lastIndex) { sb.append(", "); } } sb.append("}"); } } /** * A value for {@link JSONArray}. */ private static final class ArrayValue extends Value { private final List<Value> elements; private ArrayValue(List<Value> elements) { this.elements = elements; } public Type getType() { return Type.ARRAY; } public void toString(StringBuilder sb) { sb.append("["); int index = 0; final int lastIndex = elements.size() - 1; for (Value element : elements) { element.toString(sb); if (index++ < lastIndex) { sb.append(", "); } } sb.append("]"); } } /** * A value for {@link String}. */ private static final class StringValue extends Value { private static final StringValue INSTANCE = new StringValue(); public Type getType() { return Type.STRING; } public void toString(StringBuilder sb) { sb.append("string"); } } /** * A value for {@link Boolean}. */ private static final class BooleanValue extends Value { private static final BooleanValue INSTANCE = new BooleanValue(); public Type getType() { return Type.BOOLEAN; } public void toString(StringBuilder sb) { sb.append("boolean"); } } /** * A value for {@link Integer}. */ private static final class IntegerValue extends Value { private static final IntegerValue INSTANCE = new IntegerValue(); public Type getType() { return Type.INTEGER; } public void toString(StringBuilder sb) { sb.append("integer"); } } /** * A value for {@link Float}. */ private static final class FloatValue extends Value { private static final FloatValue INSTANCE = new FloatValue(); public Type getType() { return Type.FLOAT; } public void toString(StringBuilder sb) { sb.append("float"); } } /** * A value for {@code null}. */ private static final class NullValue extends Value { private static final NullValue INSTANCE = new NullValue(); public Type getType() { return Type.NULL; } public void toString(StringBuilder sb ) { sb.append("null"); } } @SuppressWarnings("unchecked") private final JSONArray getArray(ArrayValue value, ValueGenerator generator) { JSONArray array = new JSONArray(); for (Value element : value.elements) { array.add(getObject(element, generator)); } return array; } @SuppressWarnings("unchecked") private final JSONObject getObject(ObjectValue value, ValueGenerator generator) { JSONObject object = new JSONObject(); for (ObjectValue.Entry entry : value.entries) { object.put(entry.name, getObject(entry.value, generator)); } return object; } private final Object getObject(Value value, ValueGenerator generator) { switch (value.getType()) { case ARRAY: return getArray((ArrayValue) value, generator); case OBJECT: return getObject((ObjectValue) value, generator); case STRING: return generator.nextString(); case BOOLEAN: return generator.nextBoolean(); case INTEGER: return generator.nextInt(); case FLOAT: return generator.nextFloat(); case NULL: return null; default: break; } return null; } private final ObjectValue root; private DocumentSchema(ObjectValue root) { this.root = root; } /** * Private namespace for methods that parse XML. */ private static final class XmlParser { private static Value parseTag(Element element) { if (element.getTagName().equals("array")) { return parseArrayTag(element); } else if (element.getTagName().equals("object")) { return parseObjectTag(element); } else if (element.getTagName().equals("string")) { return StringValue.INSTANCE; } else if (element.getTagName().equals("integer")) { return IntegerValue.INSTANCE; } else if (element.getTagName().equals("float")) { return FloatValue.INSTANCE; } else if (element.getTagName().equals("boolean")) { return BooleanValue.INSTANCE; } else if (element.getTagName().equals("null")) { return NullValue.INSTANCE; } return null; } private static ArrayValue parseArrayTag(Element element) { List<Value> elements = new LinkedList<Value>(); NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); ++i) { Node childNode = childNodes.item(i); if (childNode instanceof Element) { Element childNodeElement = (Element) childNode; NodeList elementChildNodes = childNodeElement.getChildNodes(); for (int j = 0; j < elementChildNodes.getLength(); ++j) { Node elementChildNode = elementChildNodes.item(j); if (elementChildNode instanceof Element) { elements.add(parseTag((Element) elementChildNode)); } } } } return new ArrayValue(elements); } private static ObjectValue.Entry parseObjectEntryTag(Element element) { String name = null; Value value = null; NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); ++i) { Node childNode = childNodes.item(i); if (childNode instanceof Element) { Element childNodeElement = (Element) childNode; if (childNodeElement.getTagName().equals("name")) { name = childNodeElement.getChildNodes().item(0).getNodeValue(); } else if (childNodeElement.getTagName().equals("value")) { NodeList valueChildNodes = childNodeElement.getChildNodes(); for (int j = 0; j < valueChildNodes.getLength(); ++j) { Node valueChildNode = valueChildNodes.item(j); if (valueChildNode instanceof Element) { value = parseTag((Element) valueChildNode); } } } } } return new ObjectValue.Entry(name, value); } private static ObjectValue parseObjectTag(Element element) { List<ObjectValue.Entry> entries = new LinkedList<DocumentSchema.ObjectValue.Entry>(); NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); ++i) { // Each child node is an <entry> element. Node childNode = childNodes.item(i); if (childNode instanceof Element) { Element entryElement = (Element) childNode; entries.add(parseObjectEntryTag(entryElement)); } } return new ObjectValue(entries); } /** * Given the parsed XML {@link Document}, returns the root {@link ObjectValue}. * * @param document the parsed XML document * @return the root JSON object */ private static ObjectValue parseDocument(Document document) { Element root = document.getDocumentElement(); return parseObjectTag(root); } } /** * Private namespace for methods tat parse JSON. */ private static final class JsonParser { private static Value parseValue(Object object) { if (object == null) { return NullValue.INSTANCE; } else if (object instanceof JSONObject) { JSONObject jsonObject = (JSONObject) object; return parseObjectValue(jsonObject); } else if (object instanceof JSONArray) { JSONArray jsonArray = (JSONArray) object; return parseArrayValue(jsonArray); } else if (object instanceof String) { return StringValue.INSTANCE; } else if (object instanceof Integer) { return IntegerValue.INSTANCE; } else if (object instanceof Float) { return FloatValue.INSTANCE; } else if (object instanceof Boolean) { return BooleanValue.INSTANCE; } return null; } private static ArrayValue parseArrayValue(JSONArray json) { List<Value> elements = new ArrayList<Value>(json.size()); for (Object jsonElement : json) { elements.add(parseValue(jsonElement)); } return new ArrayValue(elements); } @SuppressWarnings("unchecked") private static ObjectValue parseObjectValue(JSONObject json) { List<ObjectValue.Entry> entries = new ArrayList<DocumentSchema.ObjectValue.Entry>(json.size()); Set<Map.Entry<String, Object>> entrySet = json.entrySet(); for (Map.Entry<String, Object> entry : entrySet) { String name = entry.getKey(); Value value = parseValue(entry.getValue()); entries.add(new ObjectValue.Entry(name, value)); } return new ObjectValue(entries); } /** * Given the root {@link JSONObject} of the parsed JSON, returns the root {@link ObjectValue}. * * @param jsonRoot the root JSON object * @return the root JSON object */ private static ObjectValue parseJson(JSONObject jsonRoot) { return parseObjectValue(jsonRoot); } } /** * Returns a {@link DocumentSchema} parsed from the XML in the given file. * * @param schemaFile the file containing the XML of the schema * @return the document schema * @throws BenchmarkException if the file could not be parsed */ public static DocumentSchema createSchemaFromXml(File schemaFile) throws BenchmarkException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(schemaFile); ObjectValue root = XmlParser.parseDocument(document); return new DocumentSchema(root); } catch (ParserConfigurationException e) { throw new BenchmarkException(e); } catch (SAXException e) { throw new BenchmarkException(e); } catch (IOException e) { throw new BenchmarkException(e); } } /** * Returns a {@link DocumentSchema} parsed from the JSON in the given file. * * @param schemaFile the file containing the JSON of the schema * @return the document schema * @throws BenchmarkException if the file could not be parsed */ public static DocumentSchema createSchemaFromJson(File schemaFile) throws BenchmarkException { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(schemaFile)); JSONParser jsonParser = new JSONParser(); JSONObject json = (JSONObject) jsonParser.parse(bufferedReader); ObjectValue root = JsonParser.parseJson(json); return new DocumentSchema(root); } catch (IOException e) { throw new BenchmarkException(e); } catch (ParseException e) { throw new BenchmarkException(e); } } /** * Returns the JSON for a new document that conforms to the schema. * * @param generator the generator for values in the document * @return the JSON for the new document */ public JSONObject getNewDocument(ValueGenerator generator) { return getObject(root, generator); } public String toString() { StringBuilder sb = new StringBuilder(); root.toString(sb); return sb.toString(); } }
package creeper.user.pages; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.apache.tapestry5.annotations.OnEvent; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.ioc.annotations.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.jpa.domain.Specification; import creeper.user.dao.UserDao; import creeper.user.entities.User; public class UserList{ private static Logger logger = LoggerFactory.getLogger(UserList.class); @SuppressWarnings("unused") @Property private User user; @SuppressWarnings("unused") @Property private List<User> users; @Inject private UserDao userDao; void onActivate(final String id,final String name,final String password){ users = userDao.findAll(new Specification<User>() { @Override public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> list = new ArrayList<Predicate>(); if(null != id){list.add(cb.equal(root.get("id"),id));} if(null != name){list.add(cb.equal(root.get("name"),name));} if(null != password){list.add(cb.equal(root.get("pass"),password));} Predicate[] p = new Predicate[list.size()]; return cb.and(list.toArray(p)); } }); } // eventlink @OnEvent(value="del") Object onDeleteUser(User user){ userDao.delete(user); return this; } }
package net.squanchy.tweets.view; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.Browser; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.view.View; import timber.log.Timber; public class TweetUrlSpan extends ClickableSpan { private final String url; private final int linkColor; TweetUrlSpan(String url, int linkColor) { this.url = url; this.linkColor = linkColor; } @Override public void updateDrawState(TextPaint ds) { ds.setColor(linkColor); } @Override public void onClick(View view) { Context context = view.getContext(); Intent intent = createIntentWith(context); try { context.startActivity(intent); } catch (ActivityNotFoundException e) { Timber.e(e, "Unable to start activity for Twitter url: %s", url); } } private Intent createIntentWith(Context context) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()); return intent; } }
package sword.langbook3.android; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; public class RuleTableView extends View implements Runnable { private static final int TEXT_SIZE_SP = 24; private int _horizontalSpacing = 40; private int _verticalSpacing = 10; private int _textSize; private Paint _textPaint; private int _columnCount; private String[] _texts; private float[] _columnWidths; private float _desiredTableWidth; private float _desiredTableHeight; public RuleTableView(Context context) { super(context); init(context); } public RuleTableView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public RuleTableView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } private void init(Context context) { final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); _textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, TEXT_SIZE_SP, metrics); Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setTextSize(_textSize); paint.setColor(0xFFCC3333); _textPaint = paint; } @Override public void onDraw(Canvas canvas) { final int width = canvas.getWidth(); final int height = canvas.getHeight(); final int length = _texts.length; final int yStep = _textSize + _verticalSpacing; final float startXPos = -_diffX; float yPos = (_textSize * 4) / 5 - _diffY; float xPos = startXPos; int column = 0; for (int i = 0; i < length; i++) { String text = _texts[i]; if (text != null) { canvas.drawText(text, xPos, yPos, _textPaint); } xPos += _columnWidths[column++] + _horizontalSpacing; if (column >= _columnCount || xPos > width) { i += _columnCount - column; xPos = startXPos; yPos += yStep; column = 0; if (yPos > height + yStep) { break; } } } } public void setValues(int columnCount, String[] texts) { _columnCount = columnCount; _texts = texts; final float[] columnWidths = new float[columnCount]; final int length = texts.length; for (int i = 0; i < length; i++) { String text = texts[i]; if (text != null) { float width = _textPaint.measureText(text); final int column = i % columnCount; if (width > columnWidths[column]) { columnWidths[column] = width; } } } float desiredTableWidth = 0; for (float columnWidth : columnWidths) { desiredTableWidth += columnWidth; } if (columnCount > 1) { desiredTableWidth += (columnCount - 1) * _horizontalSpacing; } final int rowCount = (texts.length + columnCount - 1) / columnCount; float desiredTableHeight = rowCount * _textSize; if (rowCount > 1) { desiredTableHeight += (rowCount - 1) * _verticalSpacing; } _columnWidths = columnWidths; _desiredTableWidth = desiredTableWidth; _desiredTableHeight = desiredTableHeight; invalidate(); } private boolean _trackingTouch; private float _touchDownX; private float _touchDownY; private static final int DRAG_SAMPLES = 4; private static final float _speedThreshold = 0.2f; // pixels/millisecond private static final float _speedDeceleration = 0.1f; // pixels/millisecond private static final long _speedUpdateTimeInterval = 5L; // milliseconds private final float[] _lastDragX = new float[DRAG_SAMPLES]; private final float[] _lastDragY = new float[DRAG_SAMPLES]; private final long[] _lastDragTime = new long[DRAG_SAMPLES]; private int _lastDragIndex = 0; private boolean _lastDragBufferCompleted; private float _diffX; private float _diffY; private float _speedX; private float _speedY; private float _accX; private float _accY; private float getDiff(float current, float touchDown, float acc, float max) { float diff = acc + touchDown - current; if (diff < 0) { diff = 0; } if (diff > max) { diff = max; } return diff; } private void applyMove(float x, float y) { final float viewWidth = getWidth(); final float viewHeight = getHeight(); final float maxDiffX = _desiredTableWidth - viewWidth; boolean shouldInvalidate = false; if (maxDiffX > 0) { float diffX = getDiff(x, _touchDownX, _accX, maxDiffX); if (_diffX != diffX) { shouldInvalidate = true; _diffX = diffX; } } final float maxDiffY = _desiredTableHeight - viewHeight; if (maxDiffY > 0) { float diffY = getDiff(y, _touchDownY, _accY, maxDiffY); if (_diffY != diffY) { shouldInvalidate = true; _diffY = diffY; } } if (shouldInvalidate) { invalidate(); } } @Override public boolean onTouchEvent(MotionEvent event) { final float x = event.getX(); final float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: _accX = _diffX; _accY = _diffY; _touchDownX = x; _touchDownY = y; _lastDragBufferCompleted = false; _lastDragIndex = 0; _lastDragX[0] = x; _lastDragY[0] = y; _lastDragTime[0] = System.currentTimeMillis(); removeCallbacks(this); _trackingTouch = true; break; case MotionEvent.ACTION_MOVE: if (++_lastDragIndex == DRAG_SAMPLES) { _lastDragBufferCompleted = true; _lastDragIndex = 0; } _lastDragX[_lastDragIndex] = x; _lastDragY[_lastDragIndex] = y; _lastDragTime[_lastDragIndex] = System.currentTimeMillis(); applyMove(x, y); break; case MotionEvent.ACTION_UP: if (++_lastDragIndex == DRAG_SAMPLES) { _lastDragBufferCompleted = true; _lastDragIndex = 0; } _lastDragX[_lastDragIndex] = x; _lastDragY[_lastDragIndex] = y; _lastDragTime[_lastDragIndex] = System.currentTimeMillis(); applyMove(x, y); _speedX = getSpeed(_lastDragX); _speedY = getSpeed(_lastDragY); if (Math.abs(_speedX) > _speedThreshold || Math.abs(_speedY) > _speedThreshold) { postDelayed(this, _speedUpdateTimeInterval); } _trackingTouch = false; break; } return true; } private float getSpeed(float[] positions) { if (_lastDragBufferCompleted) { final int firstIndex = (_lastDragIndex + 1 == DRAG_SAMPLES)? 0 : _lastDragIndex + 1; final float lastPosition = positions[_lastDragIndex]; final long lastTime = _lastDragTime[_lastDragIndex]; final float firstPosition = positions[firstIndex]; final long firstTime = _lastDragTime[firstIndex]; final float speed = (lastPosition - firstPosition) / (lastTime - firstTime); if (Math.abs(speed) > _speedThreshold) { return speed; } } return 0; } @Override public void run() { if (!_trackingTouch && (Math.abs(_speedX) > _speedThreshold || Math.abs(_speedY) > _speedThreshold)) { final long currentTime = System.currentTimeMillis(); final long interval = currentTime - _lastDragTime[_lastDragIndex]; final float x = _lastDragX[_lastDragIndex] + _speedX * interval; final float y = _lastDragY[_lastDragIndex] + _speedY * interval; if (++_lastDragIndex == DRAG_SAMPLES) { _lastDragIndex = 0; } _lastDragX[_lastDragIndex] = x; _lastDragY[_lastDragIndex] = y; _lastDragTime[_lastDragIndex] = currentTime; applyMove(x, y); if (_speedX > _speedThreshold) { if (_speedX > _speedDeceleration) { _speedX -= _speedDeceleration; } else { _speedX = 0; } } else if (_speedX < -_speedThreshold) { if (_speedX < _speedDeceleration) { _speedX += _speedDeceleration; } else { _speedX = 0; } } if (_speedY > _speedThreshold) { if (_speedY > _speedDeceleration) { _speedY -= _speedDeceleration; } else { _speedY = 0; } } else if (_speedY < -_speedThreshold) { if (_speedY < _speedDeceleration) { _speedY += _speedDeceleration; } else { _speedY = 0; } } if (Math.abs(_speedX) > _speedThreshold || Math.abs(_speedY) > _speedThreshold) { postDelayed(this, _speedUpdateTimeInterval); } } } }
package com.jme3.app; import com.jme3.font.BitmapFont; import com.jme3.font.BitmapText; import com.jme3.input.FlyByCamera; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.queue.RenderQueue.Bucket; import com.jme3.scene.Node; import com.jme3.scene.Spatial.CullHint; import com.jme3.system.AppSettings; import com.jme3.system.JmeContext.Type; import com.jme3.system.JmeSystem; import com.jme3.util.BufferUtils; /** * <code>SimpleApplication</code> extends the {@link com.jme3.app.Application} * class to provide default functionality like a first-person camera, * and an accessible root node that is updated and rendered regularly. * Additionally, <code>SimpleApplication</code> will display a statistics view * using the {@link com.jme3.app.StatsView} class. It will display * the current frames-per-second value on-screen in addition to the statistics. * Several keys have special functionality in <code>SimpleApplication</code>:<br/> * * <table> * <tr><td>Esc</td><td>- Close the application</td></tr> * <tr><td>C</td><td>- Display the camera position and rotation in the console.</td></tr> * <tr><td>M</td><td>- Display memory usage in the console.</td></tr> * </table> */ public abstract class SimpleApplication extends Application { public static final String INPUT_MAPPING_EXIT = "SIMPLEAPP_Exit"; public static final String INPUT_MAPPING_CAMERA_POS = "SIMPLEAPP_CameraPos"; public static final String INPUT_MAPPING_MEMORY = "SIMPLEAPP_Memory"; protected Node rootNode = new Node("Root Node"); protected Node guiNode = new Node("Gui Node"); protected float secondCounter = 0.0f; protected BitmapText fpsText; protected BitmapFont guiFont; protected StatsView statsView; protected FlyByCamera flyCam; protected boolean showSettings = true; private boolean showFps = true; private AppActionListener actionListener = new AppActionListener(); private class AppActionListener implements ActionListener { public void onAction(String name, boolean value, float tpf) { if (!value) { return; } if (name.equals(INPUT_MAPPING_EXIT)) { stop(); } else if (name.equals(INPUT_MAPPING_CAMERA_POS)) { if (cam != null) { Vector3f loc = cam.getLocation(); Quaternion rot = cam.getRotation(); System.out.println("Camera Position: (" + loc.x + ", " + loc.y + ", " + loc.z + ")"); System.out.println("Camera Rotation: " + rot); System.out.println("Camera Direction: " + cam.getDirection()); } } else if (name.equals(INPUT_MAPPING_MEMORY)) { BufferUtils.printCurrentDirectMemory(null); } } } public SimpleApplication() { super(); } @Override public void start() { // set some default settings in-case // settings dialog is not shown boolean loadSettings = false; if (settings == null) { setSettings(new AppSettings(true)); loadSettings = true; } // show settings dialog if (showSettings) { if (!JmeSystem.showSettingsDialog(settings, loadSettings)) { return; } } //re-setting settings they can have been merged from the registry. setSettings(settings); super.start(); } /** * Retrieves flyCam * @return flyCam Camera object * */ public FlyByCamera getFlyByCamera() { return flyCam; } /** * Retrieves guiNode * @return guiNode Node object * */ public Node getGuiNode() { return guiNode; } /** * Retrieves rootNode * @return rootNode Node object * */ public Node getRootNode() { return rootNode; } public boolean isShowSettings() { return showSettings; } /** * Toggles settings window to display at start-up * @param showSettings Sets true/false * */ public void setShowSettings(boolean showSettings) { this.showSettings = showSettings; } /** * Attaches FPS statistics to guiNode and displays it on the screen. * */ public void loadFPSText() { guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt"); fpsText = new BitmapText(guiFont, false); fpsText.setLocalTranslation(0, fpsText.getLineHeight(), 0); fpsText.setText("Frames per second"); guiNode.attachChild(fpsText); } /** * Attaches Statistics View to guiNode and displays it on the screen * above FPS statistics line. * */ public void loadStatsView() { statsView = new StatsView("Statistics View", assetManager, renderer.getStatistics()); // move it up so it appears above fps text statsView.setLocalTranslation(0, fpsText.getLineHeight(), 0); guiNode.attachChild(statsView); } @Override public void initialize() { super.initialize(); guiNode.setQueueBucket(Bucket.Gui); guiNode.setCullHint(CullHint.Never); loadFPSText(); loadStatsView(); viewPort.attachScene(rootNode); guiViewPort.attachScene(guiNode); if (inputManager != null) { flyCam = new FlyByCamera(cam); flyCam.setMoveSpeed(1f); flyCam.registerWithInput(inputManager); if (context.getType() == Type.Display) { inputManager.addMapping(INPUT_MAPPING_EXIT, new KeyTrigger(KeyInput.KEY_ESCAPE)); } inputManager.addMapping(INPUT_MAPPING_CAMERA_POS, new KeyTrigger(KeyInput.KEY_C)); inputManager.addMapping(INPUT_MAPPING_MEMORY, new KeyTrigger(KeyInput.KEY_M)); inputManager.addListener(actionListener, INPUT_MAPPING_EXIT, INPUT_MAPPING_CAMERA_POS, INPUT_MAPPING_MEMORY); } // call user code simpleInitApp(); } @Override public void update() { super.update(); // makes sure to execute AppTasks if (speed == 0 || paused) { return; } float tpf = timer.getTimePerFrame() * speed; if (showFps) { secondCounter += timer.getTimePerFrame(); int fps = (int) timer.getFrameRate(); if (secondCounter >= 1.0f) { fpsText.setText("Frames per second: " + fps); secondCounter = 0.0f; } } // update states stateManager.update(tpf); // simple update and root node simpleUpdate(tpf); rootNode.updateLogicalState(tpf); guiNode.updateLogicalState(tpf); rootNode.updateGeometricState(); guiNode.updateGeometricState(); // render states stateManager.render(renderManager); if (context.isRenderable()){ renderManager.render(tpf); } simpleRender(renderManager); stateManager.postRender(); } public void setDisplayFps(boolean show) { showFps = show; fpsText.setCullHint(show ? CullHint.Never : CullHint.Always); } public void setDisplayStatView(boolean show) { statsView.setEnabled(show); statsView.setCullHint(show ? CullHint.Never : CullHint.Always); } public abstract void simpleInitApp(); public void simpleUpdate(float tpf) { } public void simpleRender(RenderManager rm) { } }
package yuku.alkitab.base.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.SystemClock; import android.util.AttributeSet; import android.util.Log; import android.widget.ImageView; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import yuku.afw.App; import yuku.afw.D; import yuku.afw.rpc.BaseData; import yuku.afw.rpc.ImageData; import yuku.afw.rpc.Response; import yuku.afw.rpc.Response.Validity; import yuku.afw.rpc.UrlLoader; import yuku.alkitab.R; public class UrlImageView extends ImageView { public static final String TAG = UrlImageView.class.getSimpleName(); public static final String DISKCACHE_PREFIX = "UrlImageView/"; //$NON-NLS-1$ public enum State { none, loading, loaded_from_memory, loaded_from_disk, loaded_from_url, /** This may happen if setUrl(null) is called */ loaded_from_default, ; public boolean isLoaded() { return this == loaded_from_disk || this == loaded_from_memory || this == loaded_from_url || this == loaded_from_default; } } public interface OnStateChangeListener { void onStateChange(UrlImageView v, State newState, String url); } public interface DiskCache { byte[] retrieve(String key); void store(String key, byte[] data); } public static class DefaultDiskCache implements DiskCache { private String getPathcode(final String path, final int version) { StringBuilder res = new StringBuilder(); for (int i = path.length() - 1; i >= 0; i char c = path.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')) { res.append(c); } else { res.append(Integer.toHexString(c)); } if (res.length() >= 50) { res.setLength(50); break; } } res.reverse(); res.append('-'); res.append(Integer.toHexString(path.hashCode())); res.append("-v"); //$NON-NLS-1$ res.append(version); res.append(".cache"); //$NON-NLS-1$ return res.toString(); } @Override public byte[] retrieve(String key) { long startTime = 0; if (D.EBUG) startTime = SystemClock.uptimeMillis(); final String pathcode = getPathcode(key, App.getVersionCode()); File cacheDir = new File(App.context.getCacheDir(), "UrlImageView-diskcache"); //$NON-NLS-1$ File cacheFile = new File(cacheDir, pathcode); byte[] buf = null; try { if (cacheFile.exists()) { long length = cacheFile.length(); buf = new byte[(int) length]; FileInputStream fis = new FileInputStream(cacheFile); try { int read = fis.read(buf, 0, buf.length); if (read == length) { return buf; } else { return null; } } finally { fis.close(); } } else { return null; } } catch (Exception e) { Log.d(TAG, "Error when reading disk cache: ", e); //$NON-NLS-1$ return null; } finally { if (D.EBUG) Log.d(TAG, "retrieveFromDiskCache (" + (buf == null? "null": buf.length) + " bytes) took " + (SystemClock.uptimeMillis() - startTime) + " ms. From '" + key + "', thread=" + Thread.currentThread().getId()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ } } @Override public void store(final String key, final byte[] data) { final String pathcode = getPathcode(key, App.getVersionCode()); final long callTime; if (D.EBUG) { callTime = SystemClock.uptimeMillis(); } else { callTime = 0; } new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { long startTime = 0; if (D.EBUG) { startTime = SystemClock.uptimeMillis(); } File cacheDir = new File(App.context.getCacheDir(), "UrlImageView-diskcache"); //$NON-NLS-1$ cacheDir.mkdirs(); File cacheFile = new File(cacheDir, pathcode); if (data == null) { cacheFile.delete(); } else { File cacheFileTmp = new File(cacheDir, pathcode + ".tmp"); //$NON-NLS-1$ try { FileOutputStream os = new FileOutputStream(cacheFileTmp); os.write(data); os.close(); cacheFile.delete(); cacheFileTmp.renameTo(cacheFile); } catch (Exception e) { Log.w(TAG, "exception when writing cache: ", e); //$NON-NLS-1$ } } if (D.EBUG) Log.d(TAG, "storeToDiskCache " + (data == null? "null": data.length + " bytes") + " took " + (SystemClock.uptimeMillis() - startTime) + " ms (delayed " + (startTime - callTime) + " ms). To '" + key + "', thread=" + Thread.currentThread().getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ return null; } }.execute(); } } public class AlwaysSuccessImageData extends ImageData { @Override public boolean isSuccessResponse(Response response) { return response.validity == Validity.Ok; } } String urlToDisplay = null; private Drawable defaultImage; int maxPixels; private static Map<String, Bitmap> memoryCache = Collections.synchronizedMap(new LinkedHashMap<String, Bitmap>(200, 0.75f, true) { static final int maxTotalSize = 4000000; int totalSize = 0; @Override public Bitmap put(String key, Bitmap value) { Bitmap prev = super.put(key, value); if (prev != null) { int size = calcSize(prev); totalSize -= size; if (D.EBUG) Log.d(TAG, "cache put() remove prev: size " + size + " total " + totalSize); //$NON-NLS-1$ //$NON-NLS-2$ } if (value != null) { int size = calcSize(value); totalSize += size; if (D.EBUG) Log.d(TAG, "cache put() add new: size " + size + " total " + totalSize); //$NON-NLS-1$ //$NON-NLS-2$ } return prev; } @Override protected boolean removeEldestEntry(Map.Entry<String,Bitmap> eldest) { if (totalSize >= maxTotalSize) { for (Iterator<Entry<String, Bitmap>> iter = this.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, Bitmap> e = iter.next(); if (e == null) { break; // no more items to remove. Should not happen. } iter.remove(); if (totalSize < maxTotalSize) { break; } else { if (D.EBUG) Log.d(TAG, "cache removeEldestEntry() still needs to remove items"); //$NON-NLS-1$ } } } // always false, because we're removing manually. return false; } @Override public Bitmap remove(Object key) { Bitmap prev = super.remove(key); if (prev != null) { int size = calcSize(prev); totalSize -= size; if (D.EBUG) Log.d(TAG, "cache remove(): size " + size + " total " + totalSize); //$NON-NLS-1$ //$NON-NLS-2$ } return prev; }; @Override public void clear() { totalSize = 0; if (D.EBUG) Log.d(TAG, "cache clear()"); //$NON-NLS-1$ super.clear(); }; private int calcSize(Bitmap b) { int n = 3; Config config = b.getConfig(); if (config == Config.RGB_565) n = 2; else if (config == Config.ARGB_8888) n = 4; else if (config == Config.ALPHA_8) n = 1; else if (config == Config.ARGB_4444) n = 2; int size = b.getWidth() * b.getHeight() * n; return size; } }); static DiskCache diskCache; private State state; private OnStateChangeListener onStateChangeListener; private int lastWidthMeasureSpec = -1; private int lastHeightMeasureSpec = -1; private static UrlLoader urlLoader = new UrlLoader(); public UrlImageView(Context context) { super(context); init(null); } public UrlImageView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public UrlImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); } private void init(AttributeSet attrs) { if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.UrlImageView); defaultImage = a.getDrawable(R.styleable.UrlImageView_defaultImage); setMaxPixels(a.getInt(R.styleable.UrlImageView_maxPixels, 0)); a.recycle(); } setState(State.none, null); if (diskCache == null) { diskCache = new DefaultDiskCache(); } } public void setDefaultImage(Drawable defaultImage) { this.defaultImage = defaultImage; } public Drawable getDefaultImage() { return defaultImage; } public static void clearMemoryCache() { memoryCache.clear(); } public static void setDiskCache(DiskCache diskCache) { UrlImageView.diskCache = diskCache; } public void setUrl(final String url) { setUrl(url, false); } public void setUrl(final String url, boolean forceRefresh) { urlToDisplay = url; setState(State.loading, url); if (url == null) { Log.d(TAG, "class: " + defaultImage.getClass().getName()); //$NON-NLS-1$ if (defaultImage != null) { this.setImageDrawable(defaultImage); if (defaultImage instanceof AnimationDrawable) { ((AnimationDrawable) defaultImage).stop(); ((AnimationDrawable) defaultImage).start(); } setState(State.loaded_from_default, url); } else { this.setImageDrawable(null); } return; } Bitmap bitmapFromMemory = retrieveFromMemoryCache(url); if (bitmapFromMemory != null) { // sync this.setImageBitmap(bitmapFromMemory); setState(State.loaded_from_memory, url); if (forceRefresh) { loadFromServer(url); } } else { // bitmapFromMemory == null if (defaultImage != null) { this.setImageDrawable(defaultImage); if (defaultImage instanceof AnimationDrawable) { ((AnimationDrawable) defaultImage).stop(); ((AnimationDrawable) defaultImage).start(); } setState(State.loaded_from_default, url); } else { this.setImageDrawable(null); } new AsyncTask<Void, Bitmap, Void>() { @Override protected Void doInBackground(Void... params) { byte[] rawFromDisk = diskCache.retrieve(DISKCACHE_PREFIX + url); if (rawFromDisk != null) { Options opts = new Options(); Bitmap bitmapFromDisk = null; if (maxPixels != 0) { opts.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(rawFromDisk, 0, rawFromDisk.length, opts); if (opts.outHeight != -1 && opts.outWidth != -1) { int pixels = opts.outHeight * opts.outWidth; int downscale = 1; while (true) { if (D.EBUG) Log.d(TAG, "maxpixels: " + maxPixels + " pixels: " + pixels + " downscale: " + downscale + " pixels/downscale/downscale: " + (pixels / downscale / downscale)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ if (pixels / downscale / downscale > maxPixels) { downscale++; } else { break; } if (downscale >= 10) { break; } } opts.inJustDecodeBounds = false; opts.inSampleSize = downscale; opts.outHeight = -1; opts.outWidth = -1; bitmapFromDisk = BitmapFactory.decodeByteArray(rawFromDisk, 0, rawFromDisk.length, opts); } } else { bitmapFromDisk = BitmapFactory.decodeByteArray(rawFromDisk, 0, rawFromDisk.length, opts); } if (bitmapFromDisk != null) { storeToMemoryCache(url, bitmapFromDisk); // back to ui thread to update bitmap! publishProgress(bitmapFromDisk); } } return null; } @Override protected void onProgressUpdate(Bitmap... values) { if (url.equals(UrlImageView.this.urlToDisplay)) { UrlImageView.this.setImageBitmap(values[0]); setState(State.loaded_from_disk, url); } }; @Override protected void onPostExecute(Void result) { // this must be called from ui thread loadFromServer(url); }; }.execute(); } } void loadFromServer(final String url) { // the below is executed in async urlLoader.load(getContext(), url, new AlwaysSuccessImageData(), new UrlLoader.Listener() { @Override public void onResponse(String url, Response response, BaseData data_, boolean firstTime) { AlwaysSuccessImageData data = (AlwaysSuccessImageData) data_; if (data != null && data.bitmap != null) { if (firstTime) { storeToMemoryCache(url, data.bitmap); diskCache.store(DISKCACHE_PREFIX + url, response.data); } if (url.equals(UrlImageView.this.urlToDisplay)) { UrlImageView.this.setImageBitmap(data.bitmap); UrlImageView.this.setState(State.loaded_from_url, url); } } } }); } void storeToMemoryCache(String url, Bitmap b) { if (b == null) { memoryCache.remove(url); } else { if (D.EBUG) Log.d(TAG, "storeToMemoryCache " + b.getWidth() + "*" + b.getHeight() + " " + b.getConfig() + " for " + url); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ memoryCache.put(url, b); } } Bitmap retrieveFromMemoryCache(String url) { return memoryCache.get(url); } public String getUrlToDisplay() { return urlToDisplay; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { this.lastWidthMeasureSpec = widthMeasureSpec; this.lastHeightMeasureSpec = heightMeasureSpec; super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public int getLastWidthMeasureSpec() { return lastWidthMeasureSpec; } public int getLastHeightMeasureSpec() { return lastHeightMeasureSpec; } public State getState() { return state; } public void setState(State state, String url) { this.state = state; if (onStateChangeListener != null) { onStateChangeListener.onStateChange(this, state, url); } } public OnStateChangeListener getOnStateChangeListener() { return onStateChangeListener; } public void setOnStateChangeListener(OnStateChangeListener onStateChangeListener) { this.onStateChangeListener = onStateChangeListener; } public int getMaxPixels() { return maxPixels; } public void setMaxPixels(int maxPixels) { this.maxPixels = maxPixels; } }
package org.bimserver.longaction; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import org.bimserver.BimServer; import org.bimserver.database.actions.ProgressListener; import org.bimserver.models.store.ActionState; import org.bimserver.models.store.LongActionState; import org.bimserver.models.store.StoreFactory; import org.bimserver.notifications.ProgressNotification; import org.bimserver.notifications.ProgressTopic; import org.bimserver.plugins.Reporter; import org.bimserver.shared.exceptions.UserException; import org.bimserver.webservices.authorization.Authorization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class LongAction<T extends LongActionKey> implements Reporter, ProgressListener { private static final Logger LOGGER = LoggerFactory.getLogger(LongAction.class); private final GregorianCalendar start; private final AtomicInteger progress = new AtomicInteger(-1); private final CountDownLatch latch = new CountDownLatch(1); private final BimServer bimServer; private final String username; private final String userUsername; private ActionState actionState = ActionState.UNKNOWN; private GregorianCalendar stop; private final List<String> errors = new ArrayList<String>(); private final List<String> warnings = new ArrayList<String>(); private final List<String> infos = new ArrayList<String>(); private final Authorization authorization; private String title = "Unknown"; private int stage = 0; private ProgressTopic progressTopic; public LongAction(BimServer bimServer, String username, String userUsername, Authorization authorization) { start = new GregorianCalendar(); this.authorization = authorization; this.userUsername = userUsername; this.username = username; this.bimServer = bimServer; this.actionState = ActionState.STARTED; } public void init() { } public void setProgressTopic(ProgressTopic progressTopic) { this.progressTopic = progressTopic; } public ProgressTopic getProgressTopic() { return progressTopic; } protected void changeActionState(ActionState actiontState, String title, int progress) { ActionState oldState = this.actionState; if (actiontState == ActionState.FINISHED) { stop = new GregorianCalendar(); } int oldProgress = this.progress.get(); String oldTitle = this.title; this.title = title; this.progress.set(progress); this.actionState = actiontState; if (oldState != actiontState || progress != oldProgress || !oldTitle.equals(title)) { if (title != null && oldTitle != null && !title.equals(oldTitle)) { stage++; } bimServer.getNotificationsManager().notify(new ProgressNotification(bimServer, progressTopic, getState())); } } public GregorianCalendar getStop() { return stop; } public ActionState getActionState() { return this.actionState; } public String getUserUsername() { return userUsername; } public Authorization getAuthorization() { return authorization; } public BimServer getBimServer() { return bimServer; } public abstract String getDescription(); public abstract void execute(); public String getUserName() { return username; } protected void done() { bimServer.getNotificationsManager().notify(new ProgressNotification(bimServer, progressTopic, getState())); latch.countDown(); } public void waitForCompletion() { try { latch.await(); } catch (InterruptedException e) { LOGGER.error("", e); } } public GregorianCalendar getStart() { return start; } public void updateProgress(String title, int progress) { int oldProgress = this.progress.get(); String oldTitle = this.title; this.title = title; this.progress.set(progress); if (progress != oldProgress || !oldTitle.equals(title)) { if (!title.equals(oldTitle)) { stage++; } bimServer.getNotificationsManager().notify(new ProgressNotification(bimServer, progressTopic, getState())); } } public void terminate() { LOGGER.info("Terminating long action with id " + progressTopic.getKey().getId()); // thread.interrupt(); } public int getProgress() { return progress.get(); } public void fillState(LongActionState ds) { ds.setStart(getStart().getTime()); ds.setEnd(getStop() != null ? getStop().getTime() : null); ds.setProgress(getProgress()); ds.setState(getActionState()); ds.setTitle(title); ds.setStage(stage); ds.getErrors().addAll(errors); ds.getInfos().addAll(infos); ds.getWarnings().addAll(warnings); ds.setTopicId(progressTopic.getKey().getId()); if (getActionState() == ActionState.FINISHED) { ds.setProgress(100); } } public synchronized LongActionState getState() { LongActionState ds = StoreFactory.eINSTANCE.createLongActionState(); fillState(ds); return ds; } public List<String> getErrors() { return errors; } @Override public void error(Throwable error) { if (error == null) { LOGGER.error("Unknown error"); changeActionState(ActionState.AS_ERROR, "Unknown Error", 0); } else { if (error instanceof UserException) { LOGGER.error("[" + ((UserException) error).getErrorCode() + "] " + error.getMessage(), error); } else { LOGGER.error("", error); } errors.add(error.getMessage()); stop = new GregorianCalendar(); changeActionState(ActionState.AS_ERROR, error == null ? "Unknown Error" : error.getMessage(), 0); } } @Override public void warning(String warning) { warnings.add(warning); } @Override public void info(String info) { infos.add(info); } public void stop() { progressTopic.remove(); } }