lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
mit
742a66e1565b5fc7caa161edaef758cf39d1aa62
0
prakashraja89/Gooru-Conversion-API
/******************************************************************************* * ConversionServiceImpl.java * conversion-app * Created by Gooru on 2014 * Copyright (c) 2014 Gooru. All rights reserved. * http://www.goorulearning.org/ * * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated * documentation. Any one can use this software without any * restriction and can use without any limitation rights * like copy,modify,merge,publish,distribute,sub-license or * sell copies of the software. * The seller can sell based on the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package org.ednovo.gooru.converter.service; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.artofsolving.jodconverter.OfficeDocumentConverter; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeManager; import org.ednovo.gooru.application.converter.ConversionAppConstants; import org.ednovo.gooru.application.converter.GooruImageUtil; import org.ednovo.gooru.application.converter.PdfToImageRenderer; import org.ednovo.gooru.converter.controllers.Conversion; import org.ednovo.gooru.kafka.KafkaProducer; import org.jets3t.service.acl.AccessControlList; import org.jets3t.service.acl.GroupGrantee; import org.jets3t.service.acl.Permission; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.jets3t.service.model.S3Object; import org.json.CDL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.restlet.resource.ClientResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.code.javascribd.connection.ScribdClient; import com.google.code.javascribd.connection.StreamableData; import com.google.code.javascribd.docs.Upload; import com.google.code.javascribd.type.Access; import com.google.code.javascribd.type.ApiKey; import com.google.code.javascribd.type.FileData; import flexjson.JSONSerializer; @Service public class ConversionServiceImpl implements ConversionService, ConversionAppConstants { private static final Logger logger = LoggerFactory.getLogger(GooruImageUtil.class); @Autowired @javax.annotation.Resource(name = "contentS3Service") private RestS3Service s3Service; @Autowired private KafkaProducer kafkaProducer; @Override public List<String> resizeImageByDimensions(String srcFilePath, String targetFolderPath, String dimensions, String resourceGooruOid, String sessionToken, String thumbnail, String apiEndPoint) { return resizeImageByDimensions(srcFilePath, targetFolderPath, null, dimensions, resourceGooruOid, sessionToken, thumbnail, apiEndPoint); } @Override public void scribdUpload(String apiKey, String dockey, String filepath, String gooruOid, String authXml) { ScribdClient client = new ScribdClient(); ApiKey apikey = new ApiKey(apiKey); File file = new File(filepath); StreamableData uploadData = new FileData(file); // initialize upload method Upload upload = new Upload(apikey, uploadData); upload.setDocType(PDF); upload.setAccess(Access.PRIVATE); upload.setRevId(new Integer(dockey)); try { client.execute(upload); } catch (Exception e) { logger.info("$ Textbook upload failed ", e); } try { File srcFile = new File(filepath); new PdfToImageRenderer().process(filepath, srcFile.getParent(), false, JPG, gooruOid, authXml); } catch (Exception ex) { logger.info("$ Generation of pdf slides failed ", ex); } } @Override public void resizeImage(String command, String logFile) { logger.info("Runtime Executor .... Initializing..."); try { command = StringUtils.replace(command, "/usr/bin/convert", "/usr/bin/gm@convert"); String cmdArgs[] = applyTemporaryFixForPath(command.split("@")); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); String line; StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); logger.info("output : {} - Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(), thumsProcess.exitValue() + ""); if (logFile != null) { FileUtils.writeStringToFile(new File(logFile), "Completed"); } } catch (Exception e) { logger.error("something went wrong while converting image", e); } } private static String[] applyTemporaryFixForPath(String[] cmdArgs) { if (cmdArgs.length > 0) { String[] fileTypes = { ".jpeg", ".JPEG", ".jpg", ".JPG", ".png", ".PNG", ".gif", ".GIF" }; for (int argIndex = 0; argIndex < cmdArgs.length; argIndex++) { String part = cmdArgs[argIndex]; if (containsIgnoreCaseInArray(part, fileTypes)) { String filePath = null; String repoPath = StringUtils.substringBeforeLast(part, "/"); String remainingPart = StringUtils.substringAfter(part, "/"); for (String fileType : fileTypes) { filePath = StringUtils.substringAfter(remainingPart, fileType); if (!filePath.isEmpty()) { break; } } if (!filePath.isEmpty()) { if (!repoPath.isEmpty()) { filePath = repoPath + "/" + filePath; } cmdArgs[argIndex] = filePath; } } } } return cmdArgs; } private static boolean containsIgnoreCaseInArray(String haystack, String[] containsArray) { for (String key : containsArray) { if (haystack.contains(key)) { return true; } } return false; } @Override public void convertPdfToImage(String resourceFilePath, String gooruOid, String authXml) { logger.warn("$ Processing pdf slides conversion request for : " + resourceFilePath); try { File srcFile = new File(resourceFilePath); new PdfToImageRenderer().process(resourceFilePath, srcFile.getParent(), false, JPG, gooruOid, authXml); } catch (Exception ex) { logger.info("$ Generation of pdf slides failed ", ex); } } public List<String> resizeImageByDimensions(String srcFilePath, String targetFolderPath, String filenamePrefix, String dimensions, String resourceGooruOid, String sessionToken, String thumbnail, String apiEndPoint) { String imagePath = null; List<String> list = new ArrayList<String>(); try { logger.debug(" src : {} /= target : {}", srcFilePath, targetFolderPath); String[] imageDimensions = dimensions.split(","); if (filenamePrefix == null) { filenamePrefix = StringUtils.substringAfterLast(srcFilePath, "/"); if (filenamePrefix.contains(".")) { filenamePrefix = StringUtils.substringBeforeLast(filenamePrefix, "."); } } for (String dimension : imageDimensions) { String[] xy = dimension.split(X); int width = Integer.valueOf(xy[0]); int height = Integer.valueOf(xy[1]); imagePath = resizeImageByDimensions(srcFilePath, width, height, targetFolderPath + filenamePrefix + "-" + dimension + "." + getFileExtenstion(srcFilePath)); list.add(imagePath); } try { JSONObject json = new JSONObject(); json.put(RESOURCE_GOORU_OID, resourceGooruOid); json.put(THUMBNAIL, thumbnail); JSONObject jsonAlias = new JSONObject(); jsonAlias.put(MEDIA, json); String jsonString = jsonAlias.toString(); StringRequestEntity requestEntity = new StringRequestEntity(jsonString, APP_JSON, "UTF-8"); HttpClient client = new HttpClient(); PostMethod postmethod = new PostMethod(apiEndPoint + "/media/resource/thumbnail?sessionToken=" + sessionToken); postmethod.setRequestEntity(requestEntity); client.executeMethod(postmethod); } catch (Exception ex) { logger.error("rest api call failed!", ex.getMessage()); } } catch (Exception ex) { logger.error("Multiple scaling of image failed for src : " + srcFilePath + " : ", ex); } return list; } public String resizeImageByDimensions(String srcFilePath, int width, int height, String destFilePath) throws Exception { String imagePath = null; try { logger.debug(" src : {} /= target : {}", srcFilePath, destFilePath); File destFile = new File(destFilePath); if (new File(srcFilePath).exists() && destFile.exists()) { destFile.delete(); } scaleImageUsingImageMagick(srcFilePath, width, height, destFilePath); imagePath = destFile.getPath(); } catch (Exception ex) { logger.error("Error while scaling image", ex); throw ex; } return imagePath; } public void scaleImageUsingImageMagick(String srcFilePath, int width, int height, String destFilePath) throws Exception { try { String resizeCommand = new String("/usr/bin/gm@convert@" + srcFilePath + "@-resize@" + width + X + height + "@" + destFilePath); String cmdArgs[] = resizeCommand.split("@"); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); String line; StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); logger.info("output : {} - Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(), thumsProcess.exitValue() + ""); } catch (Exception e) { logger.error("something went wrong while converting image", e); } } @Override public String convertHtmlToPdf(String htmlContent, String targetPath, String sourceHtmlUrl, String filename) { File targetDir = new File(targetPath); if (!targetDir.exists()) { targetDir.mkdirs(); } if (filename == null) { filename = String.valueOf(System.currentTimeMillis()); } else { File file = new File(targetPath + filename + DOT_PDF); if (file.exists()) { filename = filename + "-" + System.currentTimeMillis(); } } if (htmlContent != null) { if (saveAsHtml(targetPath + filename + DOT_HTML, htmlContent) != null) { convertHtmlToPdf(targetPath + filename + DOT_HTML, targetPath + filename + DOT_PDF, 0); File file = new File(targetPath + filename + DOT_HTML); file.delete(); return filename + DOT_PDF; } } else if (sourceHtmlUrl != null) { convertHtmlToPdf(sourceHtmlUrl, targetPath + filename + DOT_PDF, 30000); return filename + DOT_PDF; } return null; } private static String saveAsHtml(String fileName, String content) { File file = new File(fileName); try { FileOutputStream fop = new FileOutputStream(file); if (!file.exists()) { file.createNewFile(); } byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); return fileName; } catch (IOException e) { e.printStackTrace(); } return null; } private static void convertHtmlToPdf(String srcFileName, String destFileName, long delayInMillsec) { try { String resizeCommand = new String("/usr/bin/wkhtmltopdf@" + srcFileName + "@--redirect-delay@" + delayInMillsec + "@" + destFileName); String cmdArgs[] = resizeCommand.split("@"); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); } catch (Exception e) { logger.error("something went wrong while converting pdf", e); } } public static String getFileExtenstion(String filePath) { return StringUtils.substringAfterLast(filePath, "."); } public String convertJsonToCsv(String jsonString, String targetFolderPath, String filename) { try { JSONArray docs = new JSONArray(jsonString); File file = new File(targetFolderPath + filename + DOT_CSV); String csv = CDL.toString(docs); if (file.exists()) { filename = filename + "-" + System.currentTimeMillis() + DOT_CSV; } else { filename = filename + DOT_CSV; file = new File(targetFolderPath + filename); } FileUtils.writeStringToFile(file, csv); return filename; } catch (Exception ex) { logger.info("$ Conversion of Csv file failed ", ex); } return null; } @Override public void resourceImageUpload(String folderInBucket, String gooruBucket, String fileName, String callBackUrl, String sourceFilePath) throws Exception { Integer s3UploadFlag = 0; if (folderInBucket != null) { fileName = folderInBucket + fileName; } File file = new File(sourceFilePath + fileName); if (!file.isDirectory()) { byte[] data = FileUtils.readFileToByteArray(file); S3Object fileObject = new S3Object(fileName, data); fileObject = getS3Service().putObject(gooruBucket, fileObject); setPublicACL(fileName, gooruBucket); s3UploadFlag = 1; } else { listFilesForFolder(file, gooruBucket, fileName); s3UploadFlag = 1; } try { if (callBackUrl != null) { final JSONObject data = new JSONObject(); final JSONObject resource = new JSONObject(); resource.put("s3UploadFlag", s3UploadFlag); data.put("resource", resource); System.out.println(callBackUrl); new ClientResource(callBackUrl).put(data.toString()); } } catch (Exception e) { e.printStackTrace(); } } public void setPublicACL(String objectKey, String gooruBucket) throws Exception { S3Object fileObject = getS3Service().getObject(gooruBucket, objectKey); AccessControlList objectAcl = getS3Service().getObjectAcl(gooruBucket, fileObject.getKey()); objectAcl.grantPermission(GroupGrantee.ALL_USERS, Permission.PERMISSION_READ); fileObject.setAcl(objectAcl); getS3Service().putObject(gooruBucket, fileObject); } public void listFilesForFolder(final File folder, String gooruBucket, String fileName) throws Exception { for (final File file : folder.listFiles()) { if (file.isDirectory()) { listFilesForFolder(file, gooruBucket, fileName); } else { byte[] data = FileUtils.readFileToByteArray(file); S3Object fileObject = new S3Object(fileName + file.getName(), data); fileObject = getS3Service().putObject(gooruBucket, fileObject); setPublicACL(fileName + file.getName(), gooruBucket); } } } public RestS3Service getS3Service() { return s3Service; } @Override public void convertDocumentToPdf(Conversion conversion) { JSONObject data; try { data = new JSONObject(new JSONSerializer().serialize(conversion)); data.put("eventName", "convert.docToPdf"); try { if (conversion != null) { OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager(); officeManager.start(); if (conversion.getSourceFilePath() != null) { OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(new File(conversion.getSourceFilePath()), new File(conversion.getTargetFolderPath() + "/" + conversion.getFileName())); data.put("status", "completed"); convertPdfToImage(conversion.getTargetFolderPath() + "/" + conversion.getFileName(), conversion.getResourceGooruOid(), conversion.getAuthXml()); File file = new File(conversion.getSourceFilePath()); file.renameTo(new File(conversion.getTargetFolderPath() + "/" + StringUtils.substringBeforeLast(conversion.getFileName(), ".") + ".ppt")); } officeManager.stop(); } } catch (Exception e) { data.put("status", "failed"); } this.getKafkaProducer().send(data.toString()); } catch (JSONException jsonException) { logger.error("Failed to parse json : " + jsonException); } } public KafkaProducer getKafkaProducer() { return kafkaProducer; } }
conversion-app/src/main/java/org/ednovo/gooru/converter/service/ConversionServiceImpl.java
/******************************************************************************* * ConversionServiceImpl.java * conversion-app * Created by Gooru on 2014 * Copyright (c) 2014 Gooru. All rights reserved. * http://www.goorulearning.org/ * * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated * documentation. Any one can use this software without any * restriction and can use without any limitation rights * like copy,modify,merge,publish,distribute,sub-license or * sell copies of the software. * The seller can sell based on the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package org.ednovo.gooru.converter.service; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.artofsolving.jodconverter.OfficeDocumentConverter; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeManager; import org.ednovo.gooru.application.converter.ConversionAppConstants; import org.ednovo.gooru.application.converter.GooruImageUtil; import org.ednovo.gooru.application.converter.PdfToImageRenderer; import org.ednovo.gooru.converter.controllers.Conversion; import org.ednovo.gooru.kafka.KafkaProducer; import org.jets3t.service.acl.AccessControlList; import org.jets3t.service.acl.GroupGrantee; import org.jets3t.service.acl.Permission; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.jets3t.service.model.S3Object; import org.json.CDL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.restlet.resource.ClientResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.code.javascribd.connection.ScribdClient; import com.google.code.javascribd.connection.StreamableData; import com.google.code.javascribd.docs.Upload; import com.google.code.javascribd.type.Access; import com.google.code.javascribd.type.ApiKey; import com.google.code.javascribd.type.FileData; import flexjson.JSONSerializer; @Service public class ConversionServiceImpl implements ConversionService, ConversionAppConstants { private static final Logger logger = LoggerFactory.getLogger(GooruImageUtil.class); @Autowired @javax.annotation.Resource(name = "contentS3Service") private RestS3Service s3Service; @Autowired private KafkaProducer kafkaProducer; @Override public List<String> resizeImageByDimensions(String srcFilePath, String targetFolderPath, String dimensions, String resourceGooruOid, String sessionToken, String thumbnail, String apiEndPoint) { return resizeImageByDimensions(srcFilePath, targetFolderPath, null, dimensions, resourceGooruOid, sessionToken, thumbnail, apiEndPoint); } @Override public void scribdUpload(String apiKey, String dockey, String filepath, String gooruOid, String authXml) { ScribdClient client = new ScribdClient(); ApiKey apikey = new ApiKey(apiKey); File file = new File(filepath); StreamableData uploadData = new FileData(file); // initialize upload method Upload upload = new Upload(apikey, uploadData); upload.setDocType(PDF); upload.setAccess(Access.PRIVATE); upload.setRevId(new Integer(dockey)); try { client.execute(upload); } catch (Exception e) { logger.info("$ Textbook upload failed ", e); } try { File srcFile = new File(filepath); new PdfToImageRenderer().process(filepath, srcFile.getParent(), false, JPG, gooruOid, authXml); } catch (Exception ex) { logger.info("$ Generation of pdf slides failed ", ex); } } @Override public void resizeImage(String command, String logFile) { logger.info("Runtime Executor .... Initializing..."); try { command = StringUtils.replace(command, "/usr/bin/convert", "/usr/bin/gm@convert"); String cmdArgs[] = applyTemporaryFixForPath(command.split("@")); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); String line; StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); logger.info("output : {} - Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(), thumsProcess.exitValue() + ""); if (logFile != null) { FileUtils.writeStringToFile(new File(logFile), "Completed"); } } catch (Exception e) { logger.error("something went wrong while converting image", e); } } private static String[] applyTemporaryFixForPath(String[] cmdArgs) { if (cmdArgs.length > 0) { String[] fileTypes = { ".jpeg", ".JPEG", ".jpg", ".JPG", ".png", ".PNG", ".gif", ".GIF" }; for (int argIndex = 0; argIndex < cmdArgs.length; argIndex++) { String part = cmdArgs[argIndex]; if (containsIgnoreCaseInArray(part, fileTypes)) { String filePath = null; String repoPath = StringUtils.substringBeforeLast(part, "/"); String remainingPart = StringUtils.substringAfter(part, "/"); for (String fileType : fileTypes) { filePath = StringUtils.substringAfter(remainingPart, fileType); if (!filePath.isEmpty()) { break; } } if (!filePath.isEmpty()) { if (!repoPath.isEmpty()) { filePath = repoPath + "/" + filePath; } cmdArgs[argIndex] = filePath; } } } } return cmdArgs; } private static boolean containsIgnoreCaseInArray(String haystack, String[] containsArray) { for (String key : containsArray) { if (haystack.contains(key)) { return true; } } return false; } @Override public void convertPdfToImage(String resourceFilePath, String gooruOid, String authXml) { logger.warn("$ Processing pdf slides conversion request for : " + resourceFilePath); try { File srcFile = new File(resourceFilePath); new PdfToImageRenderer().process(resourceFilePath, srcFile.getParent(), false, JPG, gooruOid, authXml); } catch (Exception ex) { logger.info("$ Generation of pdf slides failed ", ex); } } public List<String> resizeImageByDimensions(String srcFilePath, String targetFolderPath, String filenamePrefix, String dimensions, String resourceGooruOid, String sessionToken, String thumbnail, String apiEndPoint) { String imagePath = null; List<String> list = new ArrayList<String>(); try { logger.debug(" src : {} /= target : {}", srcFilePath, targetFolderPath); String[] imageDimensions = dimensions.split(","); if (filenamePrefix == null) { filenamePrefix = StringUtils.substringAfterLast(srcFilePath, "/"); if (filenamePrefix.contains(".")) { filenamePrefix = StringUtils.substringBeforeLast(filenamePrefix, "."); } } for (String dimension : imageDimensions) { String[] xy = dimension.split(X); int width = Integer.valueOf(xy[0]); int height = Integer.valueOf(xy[1]); imagePath = resizeImageByDimensions(srcFilePath, width, height, targetFolderPath + filenamePrefix + "-" + dimension + "." + getFileExtenstion(srcFilePath)); list.add(imagePath); } try { JSONObject json = new JSONObject(); json.put(RESOURCE_GOORU_OID, resourceGooruOid); json.put(THUMBNAIL, thumbnail); JSONObject jsonAlias = new JSONObject(); jsonAlias.put(MEDIA, json); String jsonString = jsonAlias.toString(); StringRequestEntity requestEntity = new StringRequestEntity(jsonString, APP_JSON, "UTF-8"); HttpClient client = new HttpClient(); PostMethod postmethod = new PostMethod(apiEndPoint + "/media/resource/thumbnail?sessionToken=" + sessionToken); postmethod.setRequestEntity(requestEntity); client.executeMethod(postmethod); } catch (Exception ex) { logger.error("rest api call failed!", ex.getMessage()); } } catch (Exception ex) { logger.error("Multiple scaling of image failed for src : " + srcFilePath + " : ", ex); } return list; } public String resizeImageByDimensions(String srcFilePath, int width, int height, String destFilePath) throws Exception { String imagePath = null; try { logger.debug(" src : {} /= target : {}", srcFilePath, destFilePath); File destFile = new File(destFilePath); if (new File(srcFilePath).exists() && destFile.exists()) { destFile.delete(); } scaleImageUsingImageMagick(srcFilePath, width, height, destFilePath); imagePath = destFile.getPath(); } catch (Exception ex) { logger.error("Error while scaling image", ex); throw ex; } return imagePath; } public void scaleImageUsingImageMagick(String srcFilePath, int width, int height, String destFilePath) throws Exception { try { String resizeCommand = new String("/usr/bin/gm@convert@" + srcFilePath + "@-resize@" + width + X + height + "@" + destFilePath); String cmdArgs[] = resizeCommand.split("@"); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); String line; StringBuffer sb = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(thumsProcess.getInputStream())); while ((line = in.readLine()) != null) { sb.append(line).append("\n"); } in.close(); logger.info("output : {} - Status : {} - Command : " + StringUtils.join(cmdArgs, " "), sb.toString(), thumsProcess.exitValue() + ""); } catch (Exception e) { logger.error("something went wrong while converting image", e); } } @Override public String convertHtmlToPdf(String htmlContent, String targetPath, String sourceHtmlUrl, String filename) { File targetDir = new File(targetPath); if (!targetDir.exists()) { targetDir.mkdirs(); } if (filename == null) { filename = String.valueOf(System.currentTimeMillis()); } else { File file = new File(targetPath + filename + DOT_PDF); if (file.exists()) { filename = filename + "-" + System.currentTimeMillis(); } } if (htmlContent != null) { if (saveAsHtml(targetPath + filename + DOT_HTML, htmlContent) != null) { convertHtmlToPdf(targetPath + filename + DOT_HTML, targetPath + filename + DOT_PDF, 0); File file = new File(targetPath + filename + DOT_HTML); file.delete(); return filename + DOT_PDF; } } else if (sourceHtmlUrl != null) { convertHtmlToPdf(sourceHtmlUrl, targetPath + filename + DOT_PDF, 30000); return filename + DOT_PDF; } return null; } private static String saveAsHtml(String fileName, String content) { File file = new File(fileName); try { FileOutputStream fop = new FileOutputStream(file); if (!file.exists()) { file.createNewFile(); } byte[] contentInBytes = content.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); return fileName; } catch (IOException e) { e.printStackTrace(); } return null; } private static void convertHtmlToPdf(String srcFileName, String destFileName, long delayInMillsec) { try { String resizeCommand = new String("/usr/bin/wkhtmltopdf@" + srcFileName + "@--redirect-delay@" + delayInMillsec + "@" + destFileName); String cmdArgs[] = resizeCommand.split("@"); Process thumsProcess = Runtime.getRuntime().exec(cmdArgs); thumsProcess.waitFor(); } catch (Exception e) { logger.error("something went wrong while converting pdf", e); } } public static String getFileExtenstion(String filePath) { return StringUtils.substringAfterLast(filePath, "."); } public String convertJsonToCsv(String jsonString, String targetFolderPath, String filename) { try { JSONArray docs = new JSONArray(jsonString); File file = new File(targetFolderPath + filename + DOT_CSV); String csv = CDL.toString(docs); if (file.exists()) { filename = filename + "-" + System.currentTimeMillis() + DOT_CSV; } else { filename = filename + DOT_CSV; file = new File(targetFolderPath + filename); } FileUtils.writeStringToFile(file, csv); return filename; } catch (Exception ex) { logger.info("$ Conversion of Csv file failed ", ex); } return null; } @Override public void resourceImageUpload(String folderInBucket, String gooruBucket, String fileName, String callBackUrl, String sourceFilePath) throws Exception { Integer s3UploadFlag = 0; if (folderInBucket != null) { fileName = folderInBucket + fileName; } File file = new File(sourceFilePath + fileName); if (!file.isDirectory()) { byte[] data = FileUtils.readFileToByteArray(file); S3Object fileObject = new S3Object(fileName, data); fileObject = getS3Service().putObject(gooruBucket, fileObject); setPublicACL(fileName, gooruBucket); s3UploadFlag = 1; } else { listFilesForFolder(file, gooruBucket, fileName); s3UploadFlag = 1; } try { if (callBackUrl != null) { final JSONObject data = new JSONObject(); final JSONObject resource = new JSONObject(); resource.put("s3UploadFlag", s3UploadFlag); data.put("resource", resource); System.out.println(callBackUrl); new ClientResource(callBackUrl).put(data.toString()); } } catch (Exception e) { e.printStackTrace(); } } public void setPublicACL(String objectKey, String gooruBucket) throws Exception { S3Object fileObject = getS3Service().getObject(gooruBucket, objectKey); AccessControlList objectAcl = getS3Service().getObjectAcl(gooruBucket, fileObject.getKey()); objectAcl.grantPermission(GroupGrantee.ALL_USERS, Permission.PERMISSION_READ); fileObject.setAcl(objectAcl); getS3Service().putObject(gooruBucket, fileObject); } public void listFilesForFolder(final File folder, String gooruBucket, String fileName) throws Exception { for (final File file : folder.listFiles()) { if (file.isDirectory()) { listFilesForFolder(file, gooruBucket, fileName); } else { byte[] data = FileUtils.readFileToByteArray(file); S3Object fileObject = new S3Object(fileName + file.getName(), data); fileObject = getS3Service().putObject(gooruBucket, fileObject); setPublicACL(fileName + file.getName(), gooruBucket); } } } public RestS3Service getS3Service() { return s3Service; } @Override public void convertDocumentToPdf(Conversion conversion) { JSONObject data; try { data = new JSONObject(new JSONSerializer().serialize(conversion)); data.put("eventName", "convert.docToPdf"); try { if (conversion != null) { OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager(); officeManager.start(); if (conversion.getSourceFilePath() != null) { OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(new File(conversion.getSourceFilePath()), new File(conversion.getTargetFolderPath() + "/" + conversion.getFileName())); data.put("status", "completed"); convertPdfToImage(conversion.getTargetFolderPath() + "/" + conversion.getFileName(), conversion.getResourceGooruOid(), conversion.getAuthXml()); } officeManager.stop(); } } catch (Exception e) { data.put("status", "failed"); } this.getKafkaProducer().send(data.toString()); } catch (JSONException jsonException) { logger.error("Failed to parse json : " + jsonException); } } public KafkaProducer getKafkaProducer() { return kafkaProducer; } }
Resolved in file move another directory
conversion-app/src/main/java/org/ednovo/gooru/converter/service/ConversionServiceImpl.java
Resolved in file move another directory
<ide><path>onversion-app/src/main/java/org/ednovo/gooru/converter/service/ConversionServiceImpl.java <ide> try { <ide> data = new JSONObject(new JSONSerializer().serialize(conversion)); <ide> data.put("eventName", "convert.docToPdf"); <add> <ide> try { <ide> if (conversion != null) { <ide> OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager(); <ide> converter.convert(new File(conversion.getSourceFilePath()), new File(conversion.getTargetFolderPath() + "/" + conversion.getFileName())); <ide> data.put("status", "completed"); <ide> convertPdfToImage(conversion.getTargetFolderPath() + "/" + conversion.getFileName(), conversion.getResourceGooruOid(), conversion.getAuthXml()); <add> File file = new File(conversion.getSourceFilePath()); <add> file.renameTo(new File(conversion.getTargetFolderPath() + "/" + StringUtils.substringBeforeLast(conversion.getFileName(), ".") + ".ppt")); <ide> } <add> <ide> officeManager.stop(); <ide> } <ide> } catch (Exception e) { <ide> logger.error("Failed to parse json : " + jsonException); <ide> } <ide> } <del> <add> <ide> public KafkaProducer getKafkaProducer() { <ide> return kafkaProducer; <ide> }
Java
apache-2.0
fda567b4e2a36b5f537b73835aaa4c87c21acf02
0
vibur/vibur-dbcp
/** * Copyright 2013 Simeon Malchev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vibur.dbcp; import org.slf4j.LoggerFactory; import org.vibur.dbcp.cache.StatementCache; import org.vibur.dbcp.jmx.ViburDBCPMonitoring; import org.vibur.dbcp.pool.ConnHolder; import org.vibur.dbcp.pool.ConnectionFactory; import org.vibur.dbcp.pool.PoolOperations; import org.vibur.dbcp.pool.VersionedObjectFactory; import org.vibur.objectpool.ConcurrentLinkedPool; import org.vibur.objectpool.PoolService; import org.vibur.objectpool.listener.TakenListener; import org.vibur.objectpool.reducer.ThreadedPoolReducer; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Field; import java.net.URL; import java.net.URLConnection; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.*; import java.util.logging.Logger; import static org.vibur.dbcp.util.FormattingUtils.getPoolName; import static org.vibur.dbcp.util.ViburUtils.getStackTraceAsString; /** * The main DataSource which needs to be configured/instantiated by the calling application and from * which the JDBC Connections will be obtained via calling the {@link #getConnection()} method. The * lifecycle operations of this DataSource are defined by the {@link DataSourceLifecycle} interface. * * @see DataSource * @see org.vibur.dbcp.pool.ConnectionFactory * * @author Simeon Malchev */ public class ViburDBCPDataSource extends ViburDBCPConfig implements DataSource, DataSourceLifecycle { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ViburDBCPDataSource.class); private static final int CACHE_MAX_SIZE = 1000; public static final String DEFAULT_PROPERTIES_CONFIG_FILE_NAME = "vibur-dbcp-config.properties"; public static final String DEFAULT_XML_CONFIG_FILE_NAME = "vibur-dbcp-config.xml"; private State state = State.NEW; private ConnectionFactory connectionFactory; private ThreadedPoolReducer poolReducer = null; private PrintWriter logWriter; /** * Default constructor for programmatic configuration via the {@code ViburDBCPConfig} * setter methods. */ public ViburDBCPDataSource() { } /** * Initialization via properties file name. Must be either standard properties file * or XML file which is complaint with "http://java.sun.com/dtd/properties.dtd". * * <p>{@code configFileName} can be {@code null} in which case the default resource * file names {@link #DEFAULT_XML_CONFIG_FILE_NAME} or {@link #DEFAULT_PROPERTIES_CONFIG_FILE_NAME} * will be loaded, in this order. * * @param configFileName the properties config file name * @throws ViburDBCPException if cannot configure successfully */ public ViburDBCPDataSource(String configFileName) throws ViburDBCPException { this(); URL config; if (configFileName != null) { config = getURL(configFileName); if (config == null) throw new ViburDBCPException("Unable to load resource " + configFileName); } else { config = getURL(DEFAULT_XML_CONFIG_FILE_NAME); if (config == null) { config = getURL(DEFAULT_PROPERTIES_CONFIG_FILE_NAME); if (config == null) throw new ViburDBCPException("Unable to load default resources " + DEFAULT_XML_CONFIG_FILE_NAME + " or " + DEFAULT_PROPERTIES_CONFIG_FILE_NAME); } } configureFromURL(config); } private URL getURL(String configFileName) { URL config = Thread.currentThread().getContextClassLoader().getResource(configFileName); if (config == null) { config = getClass().getClassLoader().getResource(configFileName); if (config == null) config = ClassLoader.getSystemResource(configFileName); } return config; } /** * Initialization via the given properties. * * @param properties the given properties * @throws ViburDBCPException if cannot configure successfully */ public ViburDBCPDataSource(Properties properties) throws ViburDBCPException { this(); configureFromProperties(properties); } private void configureFromURL(URL config) throws ViburDBCPException { InputStream inputStream = null; try { URLConnection uConn = config.openConnection(); uConn.setUseCaches(false); inputStream = uConn.getInputStream(); Properties properties = new Properties(); if (config.getFile().endsWith(".xml")) properties.loadFromXML(inputStream); else properties.load(inputStream); configureFromProperties(properties); } catch (IOException e) { throw new ViburDBCPException(config.toString(), e); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ignored) { logger.warn("Couldn't close configuration URL " + config, ignored); } } } private void configureFromProperties(Properties properties) throws ViburDBCPException { Set<String> fields = new HashSet<String>(); for (Field field : ViburDBCPConfig.class.getDeclaredFields()) fields.add(field.getName()); for (Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); String val = (String) entry.getValue(); try { if (!fields.contains(key)) { logger.warn("Unknown configuration property: " + key); continue; } Field field = ViburDBCPConfig.class.getDeclaredField(key); Class<?> type = field.getType(); if (type == int.class || type == Integer.class) set(field, Integer.parseInt(val)); else if (type == long.class || type == Long.class) set(field, Long.parseLong(val)); else if (type == float.class || type == Float.class) set(field, Float.parseFloat(val)); else if (type == boolean.class || type == Boolean.class) set(field, Boolean.parseBoolean(val)); else if (type == String.class) set(field, val); else throw new ViburDBCPException("Unexpected type for configuration property: " + key); } catch (NoSuchFieldException e) { throw new ViburDBCPException("Error calling getDeclaredField() for: " + key); } catch (NumberFormatException e) { throw new ViburDBCPException("Wrong value for configuration property: " + key, e); } catch (IllegalAccessException e) { throw new ViburDBCPException(key, e); } } } private void set(Field field, Object value) throws IllegalAccessException { field.setAccessible(true); field.set(this, value); } /** * {@inheritDoc} * * @throws ViburDBCPException if cannot start this DataSource successfully, that is, if cannot successfully * initialize/configure the underlying SQL system, or if cannot create the underlying SQL connections, * or if cannot create the configured pool reducer, or if cannot initialize JMX */ public void start() throws ViburDBCPException { synchronized (this) { if (state != State.NEW) throw new IllegalStateException(); state = State.WORKING; } validateConfig(); connectionFactory = new ConnectionFactory(this); PoolService<ConnHolder> pool = new ConcurrentLinkedPool<ConnHolder>(connectionFactory, getPoolInitialSize(), getPoolMaxSize(), isPoolFair(), isPoolEnableConnectionTracking() ? new TakenListener<ConnHolder>(getPoolInitialSize()) : null); setPool(pool); initPoolReducer(); setPoolOperations(new PoolOperations(this)); initStatementCache(); initJMX(); logger.info("Started {}", this); } /** {@inheritDoc} */ public void terminate() { synchronized (this) { if (state == State.TERMINATED) return; State oldState = state; state = State.TERMINATED; if (oldState == State.NEW) return; } terminateStatementCache(); if (poolReducer != null) poolReducer.terminate(); if (getPool() != null) getPool().terminate(); logger.info("Terminated {}", this); } /** {@inheritDoc} */ public synchronized State getState() { return state; } private void validateConfig() { if (getExternalDataSource() == null && getJdbcUrl() == null) throw new IllegalArgumentException(); if (getAcquireRetryDelayInMs() < 0) throw new IllegalArgumentException(); if (getAcquireRetryAttempts() < 0) throw new IllegalArgumentException(); if (getConnectionTimeoutInMs() < 0) throw new IllegalArgumentException(); if (getLoginTimeoutInSeconds() < 0) throw new IllegalArgumentException(); if (getStatementCacheMaxSize() < 0) throw new IllegalArgumentException(); if (getReducerTimeIntervalInSeconds() < 0) throw new IllegalArgumentException(); if (getReducerSamples() <= 0) throw new IllegalArgumentException(); if (getConnectionIdleLimitInSeconds() >= 0 && getTestConnectionQuery() == null) throw new IllegalArgumentException(); if (getValidateTimeoutInSeconds() < 0) throw new IllegalArgumentException(); if (getPassword() == null) logger.warn("JDBC password is not specified."); if (getUsername() == null) logger.warn("JDBC username is not specified."); if (getLogConnectionLongerThanMs() > getConnectionTimeoutInMs()) { logger.warn("Setting logConnectionLongerThanMs to " + getConnectionTimeoutInMs()); setLogConnectionLongerThanMs(getConnectionTimeoutInMs()); } if (getStatementCacheMaxSize() > CACHE_MAX_SIZE) { logger.warn("Setting statementCacheMaxSize to " + CACHE_MAX_SIZE); setStatementCacheMaxSize(CACHE_MAX_SIZE); } if (getDefaultTransactionIsolation() != null) { String defaultTransactionIsolation = getDefaultTransactionIsolation().toUpperCase(); if (defaultTransactionIsolation.equals("NONE")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_NONE); else if (defaultTransactionIsolation.equals("READ_COMMITTED")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_READ_COMMITTED); else if (defaultTransactionIsolation.equals("REPEATABLE_READ")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_REPEATABLE_READ); else if (defaultTransactionIsolation.equals("READ_UNCOMMITTED")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_READ_UNCOMMITTED); else if (defaultTransactionIsolation.equals("SERIALIZABLE")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_SERIALIZABLE); else logger.warn("Unknown defaultTransactionIsolation {}. Will use the driver's default.", getDefaultTransactionIsolation()); } } private void initPoolReducer() throws ViburDBCPException { if (getReducerTimeIntervalInSeconds() > 0) try { Object reducer = Class.forName(getPoolReducerClass()).getConstructor(ViburDBCPConfig.class) .newInstance(this); if (!(reducer instanceof ThreadedPoolReducer)) throw new ViburDBCPException(getPoolReducerClass() + " is not an instance of ThreadedPoolReducer"); poolReducer = (ThreadedPoolReducer) reducer; poolReducer.start(); } catch (ReflectiveOperationException e) { throw new ViburDBCPException(e); } } private void initStatementCache() { int statementCacheMaxSize = getStatementCacheMaxSize(); if (statementCacheMaxSize > 0) setStatementCache(new StatementCache(statementCacheMaxSize)); } private void terminateStatementCache() { StatementCache statementCache = getStatementCache(); if (statementCache != null) { statementCache.clear(); setStatementCache(null); } } private void initJMX() throws ViburDBCPException { if (isEnableJMX()) new ViburDBCPMonitoring(this); } /** {@inheritDoc} */ public Connection getConnection() throws SQLException { return getConnection(getConnectionTimeoutInMs()); } /** * {@inheritDoc} * * This method will return a <b>raw (non-pooled)</b> JDBC Connection when called with credentials different * than the configured default credentials. * */ public Connection getConnection(String username, String password) throws SQLException { if (defaultCredentials(username, password)) return getConnection(); else { logger.warn("Calling getConnection with different than the default credentials. Will create and return a non-pooled Connection."); return connectionFactory.create(username, password).value(); } } private boolean defaultCredentials(String username, String password) { if (getUsername() != null ? !getUsername().equals(username) : username != null) return false; return !(getPassword() != null ? !getPassword().equals(password) : password != null); } /** * Mainly exists to provide getConnection() method timing logging. */ private Connection getConnection(long timeout) throws SQLException { boolean logSlowConn = getLogConnectionLongerThanMs() >= 0; long startTime = logSlowConn ? System.currentTimeMillis() : 0L; Connection connProxy = null; try { return connProxy = getPoolOperations().getConnection(timeout); } finally { if (logSlowConn) logGetConnection(timeout, startTime, connProxy); } } private void logGetConnection(long timeout, long startTime, Connection connProxy) { long timeTaken = System.currentTimeMillis() - startTime; if (timeTaken >= getLogConnectionLongerThanMs()) { StringBuilder log = new StringBuilder(4096) .append(String.format("Call to getConnection(%d) from pool %s took %d ms, connProxy = %s", timeout, getPoolName(this), timeTaken, connProxy)); if (isLogStackTraceForLongConnection()) log.append('\n').append(getStackTraceAsString(new Throwable().getStackTrace())); logger.warn(log.toString()); } } /** {@inheritDoc} */ public PrintWriter getLogWriter() throws SQLException { return logWriter; } /** {@inheritDoc} */ public void setLogWriter(PrintWriter out) throws SQLException { this.logWriter = out; } /** {@inheritDoc} */ public void setLoginTimeout(int seconds) throws SQLException { setLoginTimeoutInSeconds(seconds); } /** {@inheritDoc} */ public int getLoginTimeout() throws SQLException { return getLoginTimeoutInSeconds(); } /** {@inheritDoc} */ public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } /** {@inheritDoc} */ public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("not a wrapper"); } /** {@inheritDoc} */ public boolean isWrapperFor(Class<?> iface) { return false; } public VersionedObjectFactory<ConnHolder> getConnectionFactory() { return connectionFactory; } }
src/main/java/org/vibur/dbcp/ViburDBCPDataSource.java
/** * Copyright 2013 Simeon Malchev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vibur.dbcp; import org.slf4j.LoggerFactory; import org.vibur.dbcp.cache.StatementCache; import org.vibur.dbcp.jmx.ViburDBCPMonitoring; import org.vibur.dbcp.pool.ConnHolder; import org.vibur.dbcp.pool.ConnectionFactory; import org.vibur.dbcp.pool.PoolOperations; import org.vibur.dbcp.pool.VersionedObjectFactory; import org.vibur.objectpool.ConcurrentLinkedPool; import org.vibur.objectpool.PoolService; import org.vibur.objectpool.listener.TakenListener; import org.vibur.objectpool.reducer.ThreadedPoolReducer; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.lang.reflect.Field; import java.net.URL; import java.net.URLConnection; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; import static org.vibur.dbcp.util.FormattingUtils.getPoolName; import static org.vibur.dbcp.util.ViburUtils.getStackTraceAsString; /** * The main DataSource which needs to be configured/instantiated by the calling application and from * which the JDBC Connections will be obtained via calling the {@link #getConnection()} method. The * lifecycle operations of this DataSource are defined by the {@link DataSourceLifecycle} interface. * * @see DataSource * @see org.vibur.dbcp.pool.ConnectionFactory * * @author Simeon Malchev */ public class ViburDBCPDataSource extends ViburDBCPConfig implements DataSource, DataSourceLifecycle { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ViburDBCPDataSource.class); private static final int CACHE_MAX_SIZE = 1000; public static final String DEFAULT_PROPERTIES_CONFIG_FILE_NAME = "vibur-dbcp-config.properties"; public static final String DEFAULT_XML_CONFIG_FILE_NAME = "vibur-dbcp-config.xml"; private State state = State.NEW; private ConnectionFactory connectionFactory; private ThreadedPoolReducer poolReducer = null; private PrintWriter logWriter; /** * Default constructor for programmatic configuration via the {@code ViburDBCPConfig} * setter methods. */ public ViburDBCPDataSource() { } /** * Initialization via properties file name. Must be either standard properties file * or XML file which is complaint with "http://java.sun.com/dtd/properties.dtd". * * <p>{@code configFileName} can be {@code null} in which case the default resource * file names {@link #DEFAULT_XML_CONFIG_FILE_NAME} or {@link #DEFAULT_PROPERTIES_CONFIG_FILE_NAME} * will be loaded, in this order. * * @param configFileName the properties config file name * @throws ViburDBCPException if cannot configure successfully */ public ViburDBCPDataSource(String configFileName) throws ViburDBCPException { this(); URL config; if (configFileName != null) { config = getURL(configFileName); if (config == null) throw new ViburDBCPException("Unable to load resource " + configFileName); } else { config = getURL(DEFAULT_XML_CONFIG_FILE_NAME); if (config == null) { config = getURL(DEFAULT_PROPERTIES_CONFIG_FILE_NAME); if (config == null) throw new ViburDBCPException("Unable to load default resources " + DEFAULT_XML_CONFIG_FILE_NAME + " or " + DEFAULT_PROPERTIES_CONFIG_FILE_NAME); } } configureFromURL(config); } private URL getURL(String configFileName) { URL config = Thread.currentThread().getContextClassLoader().getResource(configFileName); if (config == null) { config = getClass().getClassLoader().getResource(configFileName); if (config == null) config = ClassLoader.getSystemResource(configFileName); } return config; } /** * Initialization via the given properties. * * @param properties the given properties * @throws ViburDBCPException if cannot configure successfully */ public ViburDBCPDataSource(Properties properties) throws ViburDBCPException { this(); configureFromProperties(properties); } private void configureFromURL(URL config) throws ViburDBCPException { InputStream inputStream = null; try { URLConnection uConn = config.openConnection(); uConn.setUseCaches(false); inputStream = uConn.getInputStream(); Properties properties = new Properties(); if (config.getFile().endsWith(".xml")) properties.loadFromXML(inputStream); else properties.load(inputStream); configureFromProperties(properties); } catch (IOException e) { throw new ViburDBCPException(config.toString(), e); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ignored) { logger.warn("Couldn't close configuration URL " + config, ignored); } } } private void configureFromProperties(Properties properties) throws ViburDBCPException { for (Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); String val = (String) entry.getValue(); try { Field field = ViburDBCPConfig.class.getDeclaredField(key); Class<?> type = field.getType(); if (type == int.class || type == Integer.class) set(field, Integer.parseInt(val)); else if (type == long.class || type == Long.class) set(field, Long.parseLong(val)); else if (type == float.class || type == Float.class) set(field, Float.parseFloat(val)); else if (type == boolean.class || type == Boolean.class) set(field, Boolean.parseBoolean(val)); else if (type == String.class) set(field, val); else throw new ViburDBCPException("Unexpected configuration property: " + key); } catch (NoSuchFieldException e) { throw new ViburDBCPException("Unexpected configuration property: " + key); } catch (NumberFormatException e) { throw new ViburDBCPException("Wrong value for configuration property: " + key, e); } catch (IllegalAccessException e) { throw new ViburDBCPException(key, e); } } } private void set(Field field, Object value) throws IllegalAccessException { field.setAccessible(true); field.set(this, value); } /** * {@inheritDoc} * * @throws ViburDBCPException if cannot start this DataSource successfully, that is, if cannot successfully * initialize/configure the underlying SQL system, or if cannot create the underlying SQL connections, * or if cannot create the configured pool reducer, or if cannot initialize JMX */ public void start() throws ViburDBCPException { synchronized (this) { if (state != State.NEW) throw new IllegalStateException(); state = State.WORKING; } validateConfig(); connectionFactory = new ConnectionFactory(this); PoolService<ConnHolder> pool = new ConcurrentLinkedPool<ConnHolder>(connectionFactory, getPoolInitialSize(), getPoolMaxSize(), isPoolFair(), isPoolEnableConnectionTracking() ? new TakenListener<ConnHolder>(getPoolInitialSize()) : null); setPool(pool); initPoolReducer(); setPoolOperations(new PoolOperations(this)); initStatementCache(); initJMX(); logger.info("Started {}", this); } /** {@inheritDoc} */ public void terminate() { synchronized (this) { if (state == State.TERMINATED) return; State oldState = state; state = State.TERMINATED; if (oldState == State.NEW) return; } terminateStatementCache(); if (poolReducer != null) poolReducer.terminate(); if (getPool() != null) getPool().terminate(); logger.info("Terminated {}", this); } /** {@inheritDoc} */ public synchronized State getState() { return state; } private void validateConfig() { if (getExternalDataSource() == null && getJdbcUrl() == null) throw new IllegalArgumentException(); if (getAcquireRetryDelayInMs() < 0) throw new IllegalArgumentException(); if (getAcquireRetryAttempts() < 0) throw new IllegalArgumentException(); if (getConnectionTimeoutInMs() < 0) throw new IllegalArgumentException(); if (getLoginTimeoutInSeconds() < 0) throw new IllegalArgumentException(); if (getStatementCacheMaxSize() < 0) throw new IllegalArgumentException(); if (getReducerTimeIntervalInSeconds() < 0) throw new IllegalArgumentException(); if (getReducerSamples() <= 0) throw new IllegalArgumentException(); if (getConnectionIdleLimitInSeconds() >= 0 && getTestConnectionQuery() == null) throw new IllegalArgumentException(); if (getValidateTimeoutInSeconds() < 0) throw new IllegalArgumentException(); if (getPassword() == null) logger.warn("JDBC password is not specified."); if (getUsername() == null) logger.warn("JDBC username is not specified."); if (getLogConnectionLongerThanMs() > getConnectionTimeoutInMs()) { logger.warn("Setting logConnectionLongerThanMs to " + getConnectionTimeoutInMs()); setLogConnectionLongerThanMs(getConnectionTimeoutInMs()); } if (getStatementCacheMaxSize() > CACHE_MAX_SIZE) { logger.warn("Setting statementCacheMaxSize to " + CACHE_MAX_SIZE); setStatementCacheMaxSize(CACHE_MAX_SIZE); } if (getDefaultTransactionIsolation() != null) { String defaultTransactionIsolation = getDefaultTransactionIsolation().toUpperCase(); if (defaultTransactionIsolation.equals("NONE")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_NONE); else if (defaultTransactionIsolation.equals("READ_COMMITTED")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_READ_COMMITTED); else if (defaultTransactionIsolation.equals("REPEATABLE_READ")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_REPEATABLE_READ); else if (defaultTransactionIsolation.equals("READ_UNCOMMITTED")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_READ_UNCOMMITTED); else if (defaultTransactionIsolation.equals("SERIALIZABLE")) setDefaultTransactionIsolationValue(Connection.TRANSACTION_SERIALIZABLE); else logger.warn("Unknown defaultTransactionIsolation {}. Will use the driver's default.", getDefaultTransactionIsolation()); } } private void initPoolReducer() throws ViburDBCPException { if (getReducerTimeIntervalInSeconds() > 0) try { Object reducer = Class.forName(getPoolReducerClass()).getConstructor(ViburDBCPConfig.class) .newInstance(this); if (!(reducer instanceof ThreadedPoolReducer)) throw new ViburDBCPException(getPoolReducerClass() + " is not an instance of ThreadedPoolReducer"); poolReducer = (ThreadedPoolReducer) reducer; poolReducer.start(); } catch (ReflectiveOperationException e) { throw new ViburDBCPException(e); } } private void initStatementCache() { int statementCacheMaxSize = getStatementCacheMaxSize(); if (statementCacheMaxSize > 0) setStatementCache(new StatementCache(statementCacheMaxSize)); } private void terminateStatementCache() { StatementCache statementCache = getStatementCache(); if (statementCache != null) { statementCache.clear(); setStatementCache(null); } } private void initJMX() throws ViburDBCPException { if (isEnableJMX()) new ViburDBCPMonitoring(this); } /** {@inheritDoc} */ public Connection getConnection() throws SQLException { return getConnection(getConnectionTimeoutInMs()); } /** * {@inheritDoc} * * This method will return a <b>raw (non-pooled)</b> JDBC Connection when called with credentials different * than the configured default credentials. * */ public Connection getConnection(String username, String password) throws SQLException { if (defaultCredentials(username, password)) return getConnection(); else { logger.warn("Calling getConnection with different than the default credentials. Will create and return a non-pooled Connection."); return connectionFactory.create(username, password).value(); } } private boolean defaultCredentials(String username, String password) { if (getUsername() != null ? !getUsername().equals(username) : username != null) return false; return !(getPassword() != null ? !getPassword().equals(password) : password != null); } /** * Mainly exists to provide getConnection() method timing logging. */ private Connection getConnection(long timeout) throws SQLException { boolean logSlowConn = getLogConnectionLongerThanMs() >= 0; long startTime = logSlowConn ? System.currentTimeMillis() : 0L; Connection connProxy = null; try { return connProxy = getPoolOperations().getConnection(timeout); } finally { if (logSlowConn) logGetConnection(timeout, startTime, connProxy); } } private void logGetConnection(long timeout, long startTime, Connection connProxy) { long timeTaken = System.currentTimeMillis() - startTime; if (timeTaken >= getLogConnectionLongerThanMs()) { StringBuilder log = new StringBuilder(4096) .append(String.format("Call to getConnection(%d) from pool %s took %d ms, connProxy = %s", timeout, getPoolName(this), timeTaken, connProxy)); if (isLogStackTraceForLongConnection()) log.append('\n').append(getStackTraceAsString(new Throwable().getStackTrace())); logger.warn(log.toString()); } } /** {@inheritDoc} */ public PrintWriter getLogWriter() throws SQLException { return logWriter; } /** {@inheritDoc} */ public void setLogWriter(PrintWriter out) throws SQLException { this.logWriter = out; } /** {@inheritDoc} */ public void setLoginTimeout(int seconds) throws SQLException { setLoginTimeoutInSeconds(seconds); } /** {@inheritDoc} */ public int getLoginTimeout() throws SQLException { return getLoginTimeoutInSeconds(); } /** {@inheritDoc} */ public Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } /** {@inheritDoc} */ public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("not a wrapper"); } /** {@inheritDoc} */ public boolean isWrapperFor(Class<?> iface) { return false; } public VersionedObjectFactory<ConnHolder> getConnectionFactory() { return connectionFactory; } }
fixing issue #5, configureFromProperties throws Exception when configured as JNDI resource.
src/main/java/org/vibur/dbcp/ViburDBCPDataSource.java
fixing issue #5, configureFromProperties throws Exception when configured as JNDI resource.
<ide><path>rc/main/java/org/vibur/dbcp/ViburDBCPDataSource.java <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import java.sql.SQLFeatureNotSupportedException; <del>import java.util.Map; <del>import java.util.Properties; <add>import java.util.*; <ide> import java.util.logging.Logger; <ide> <ide> import static org.vibur.dbcp.util.FormattingUtils.getPoolName; <ide> } <ide> <ide> private void configureFromProperties(Properties properties) throws ViburDBCPException { <add> Set<String> fields = new HashSet<String>(); <add> for (Field field : ViburDBCPConfig.class.getDeclaredFields()) <add> fields.add(field.getName()); <add> <ide> for (Map.Entry<Object, Object> entry : properties.entrySet()) { <ide> String key = (String) entry.getKey(); <ide> String val = (String) entry.getValue(); <ide> try { <add> if (!fields.contains(key)) { <add> logger.warn("Unknown configuration property: " + key); <add> continue; <add> } <ide> Field field = ViburDBCPConfig.class.getDeclaredField(key); <ide> Class<?> type = field.getType(); <ide> if (type == int.class || type == Integer.class) <ide> else if (type == String.class) <ide> set(field, val); <ide> else <del> throw new ViburDBCPException("Unexpected configuration property: " + key); <add> throw new ViburDBCPException("Unexpected type for configuration property: " + key); <ide> } catch (NoSuchFieldException e) { <del> throw new ViburDBCPException("Unexpected configuration property: " + key); <add> throw new ViburDBCPException("Error calling getDeclaredField() for: " + key); <ide> } catch (NumberFormatException e) { <ide> throw new ViburDBCPException("Wrong value for configuration property: " + key, e); <ide> } catch (IllegalAccessException e) {
JavaScript
bsd-3-clause
22a7a9cb368ad5d6132115f85f5ce1bf8f134110
0
kitsonk/delite,Sam-Cummins/delite,Sam-Cummins/delite,harbalk/delite,kitsonk/delite,harbalk/delite
dojo.provide("dijit._base.manager"); dojo.declare("dijit.WidgetSet", null, { // summary: // A set of widgets indexed by id. A default instance of this class is // available as `dijit.registry` // // example: // Create a small list of widgets: // | var ws = new dijit.WidgetSet(); // | ws.add(dijit.byId("one")); // | ws.add(dijit.byId("two")); // | // destroy both: // | ws.forEach(function(w){ w.destroy(); }); // // example: // Using dijit.registry: // | dijit.registry.forEach(function(w){ /* do something */ }); constructor: function(){ this._hash = {}; this.length = 0; }, add: function(/*dijit._Widget*/ widget){ // summary: // Add a widget to this list. If a duplicate ID is detected, a error is thrown. // // widget: dijit._Widget // Any dijit._Widget subclass. if(this._hash[widget.id]){ throw new Error("Tried to register widget with id==" + widget.id + " but that id is already registered"); } this._hash[widget.id] = widget; this.length++; }, remove: function(/*String*/ id){ // summary: // Remove a widget from this WidgetSet. Does not destroy the widget; simply // removes the reference. if(this._hash[id]){ delete this._hash[id]; this.length--; } }, forEach: function(/*Function*/ func, /* Object? */thisObj){ // summary: // Call specified function for each widget in this set. // // func: // A callback function to run for each item. Is passed the widget, the index // in the iteration, and the full hash, similar to `dojo.forEach`. // // thisObj: // An optional scope parameter // // example: // Using the default `dijit.registry` instance: // | dijit.registry.forEach(function(widget){ // | console.log(widget.declaredClass); // | }); // // returns: // Returns self, in order to allow for further chaining. thisObj = thisObj || dojo.global; var i = 0, id; for(id in this._hash){ func.call(thisObj, this._hash[id], i++, this._hash); } return this; // dijit.WidgetSet }, filter: function(/*Function*/ filter, /* Object? */thisObj){ // summary: // Filter down this WidgetSet to a smaller new WidgetSet // Works the same as `dojo.filter` and `dojo.NodeList.filter` // // filter: // Callback function to test truthiness. Is passed the widget // reference and the pseudo-index in the object. // // thisObj: Object? // Option scope to use for the filter function. // // example: // Arbitrary: select the odd widgets in this list // | dijit.registry.filter(function(w, i){ // | return i % 2 == 0; // | }).forEach(function(w){ /* odd ones */ }); thisObj = thisObj || dojo.global; var res = new dijit.WidgetSet(), i = 0, id; for(id in this._hash){ var w = this._hash[id]; if(filter.call(thisObj, w, i++, this._hash)){ res.add(w); } } return res; // dijit.WidgetSet }, byId: function(/*String*/ id){ // summary: // Find a widget in this list by it's id. // example: // Test if an id is in a particular WidgetSet // | var ws = new dijit.WidgetSet(); // | ws.add(dijit.byId("bar")); // | var t = ws.byId("bar") // returns a widget // | var x = ws.byId("foo"); // returns undefined return this._hash[id]; // dijit._Widget }, byClass: function(/*String*/ cls){ // summary: // Reduce this widgetset to a new WidgetSet of a particular `declaredClass` // // cls: String // The Class to scan for. Full dot-notated string. // // example: // Find all `dijit.TitlePane`s in a page: // | dijit.registry.byClass("dijit.TitlePane").forEach(function(tp){ tp.close(); }); var res = new dijit.WidgetSet(), id, widget; for(id in this._hash){ widget = this._hash[id]; if(widget.declaredClass == cls){ res.add(widget); } } return res; // dijit.WidgetSet }, toArray: function(){ // summary: // Convert this WidgetSet into a true Array // // example: // Work with the widget .domNodes in a real Array // | dojo.map(dijit.registry.toArray(), function(w){ return w.domNode; }); var ar = []; for(var id in this._hash){ ar.push(this._hash[id]); } return ar; // dijit._Widget[] }, map: function(/* Function */func, /* Object? */thisObj){ // summary: // Create a new Array from this WidgetSet, following the same rules as `dojo.map` // example: // | var nodes = dijit.registry.map(function(w){ return w.domNode; }); // // returns: // A new array of the returned values. return dojo.map(this.toArray(), func, thisObj); // Array }, every: function(func, thisObj){ // summary: // A synthetic clone of `dojo.every` acting explictly on this WidgetSet // // func: Function // A callback function run for every widget in this list. Exits loop // when the first false return is encountered. // // thisObj: Object? // Optional scope parameter to use for the callback thisObj = thisObj || dojo.global; var x = 0, i; for(i in this._hash){ if(!func.call(thisObj, this._hash[i], x++, this._hash)){ return false; // Boolean } } return true; // Boolean }, some: function(func, thisObj){ // summary: // A synthetic clone of `dojo.some` acting explictly on this WidgetSet // // func: Function // A callback function run for every widget in this list. Exits loop // when the first true return is encountered. // // thisObj: Object? // Optional scope parameter to use for the callback thisObj = thisObj || dojo.global; var x = 0, i; for(i in this._hash){ if(func.call(thisObj, this._hash[i], x++, this._hash)){ return true; // Boolean } } return false; // Boolean } }); (function(dojo, dijit){ /*===== dijit.registry = { // summary: // A list of widgets on a page. // description: // Is an instance of `dijit.WidgetSet` }; =====*/ dijit.registry = new dijit.WidgetSet(); var hash = dijit.registry._hash; dijit.byId = function(/*String|dijit._Widget*/ id){ // summary: // Returns a widget by it's id, or if passed a widget, no-op (like dojo.byId()) return typeof id == "string" ? hash[id] : id; // dijit._Widget }; var _widgetTypeCtr = {}; dijit.getUniqueId = function(/*String*/widgetType){ // summary: // Generates a unique id for a given widgetType var id; do{ id = widgetType + "_" + (widgetType in _widgetTypeCtr ? ++_widgetTypeCtr[widgetType] : _widgetTypeCtr[widgetType] = 0); }while(hash[id]); return id; // String }; dijit.findWidgets = function(/*DomNode*/ root){ // summary: // Search subtree under root returning widgets found. // Doesn't search for nested widgets (ie, widgets inside other widgets). var outAry = []; function getChildrenHelper(root){ for(var node = root.firstChild; node; node = node.nextSibling){ if(node.nodeType == 1){ var widgetId = node.getAttribute("widgetId"); if(widgetId){ outAry.push(hash[widgetId]); }else{ getChildrenHelper(node); } } } } getChildrenHelper(root); return outAry; }; dijit._destroyAll = function(){ // summary: // Code to destroy all widgets and do other cleanup on page unload // Clean up focus manager lingering references to widgets and nodes dijit._curFocus = null; dijit._prevFocus = null; dijit._activeStack = []; // Destroy all the widgets, top down dojo.forEach(dijit.findWidgets(dojo.body()), function(widget){ // Avoid double destroy of widgets like Menu that are attached to <body> // even though they are logically children of other widgets. if(!widget._destroyed){ if(widget.destroyRecursive){ widget.destroyRecursive(); }else if(widget.destroy){ widget.destroy(); } } }); }; if(dojo.isIE){ // Only run _destroyAll() for IE because we think it's only necessary in that case, // and because it causes problems on FF. See bug #3531 for details. dojo.addOnWindowUnload(function(){ dijit._destroyAll(); }); } dijit.byNode = function(/*DOMNode*/ node){ // summary: // Returns the widget corresponding to the given DOMNode return hash[node.getAttribute("widgetId")]; // dijit._Widget }; dijit.getEnclosingWidget = function(/*DOMNode*/ node){ // summary: // Returns the widget whose DOM tree contains the specified DOMNode, or null if // the node is not contained within the DOM tree of any widget while(node){ var id = node.getAttribute && node.getAttribute("widgetId"); if(id){ return hash[id]; } node = node.parentNode; } return null; }; dijit._isElementShown = function(/*Element*/ elem){ var style = dojo.style(elem); return (style.visibility != "hidden") && (style.visibility != "collapsed") && (style.display != "none") && (dojo.attr(elem, "type") != "hidden"); } dijit.isTabNavigable = function(/*Element*/ elem){ // summary: // Tests if an element is tab-navigable // TODO: convert (and rename method) to return effectivite tabIndex; will save time in _getTabNavigable() if(dojo.attr(elem, "disabled")){ return false; }else if(dojo.hasAttr(elem, "tabIndex")){ // Explicit tab index setting return dojo.attr(elem, "tabIndex") >= 0; // boolean }else{ // No explicit tabIndex setting, need to investigate node type switch(elem.nodeName.toLowerCase()){ case "a": // An <a> w/out a tabindex is only navigable if it has an href return dojo.hasAttr(elem, "href"); case "area": case "button": case "input": case "object": case "select": case "textarea": // These are navigable by default return true; case "iframe": // If it's an editor <iframe> then it's tab navigable. if(dojo.isMoz){ return elem.contentDocument.designMode == "on"; }else if(dojo.isWebKit){ var doc = elem.contentDocument, body = doc && doc.body; return body && body.contentEditable == 'true'; }else{ doc = elem.contentWindow.document; body = doc && doc.body; return body && body.firstChild && body.firstChild.contentEditable == 'true'; } default: return elem.contentEditable == 'true'; } } }; dijit._getTabNavigable = function(/*DOMNode*/ root){ // summary: // Finds descendants of the specified root node. // // description: // Finds the following descendants of the specified root node: // * the first tab-navigable element in document order // without a tabIndex or with tabIndex="0" // * the last tab-navigable element in document order // without a tabIndex or with tabIndex="0" // * the first element in document order with the lowest // positive tabIndex value // * the last element in document order with the highest // positive tabIndex value var first, last, lowest, lowestTabindex, highest, highestTabindex; var walkTree = function(/*DOMNode*/parent){ dojo.query("> *", parent).forEach(function(child){ var isShown = dijit._isElementShown(child); if(isShown && dijit.isTabNavigable(child)){ var tabindex = dojo.attr(child, "tabIndex"); if(!dojo.hasAttr(child, "tabIndex") || tabindex == 0){ if(!first){ first = child; } last = child; }else if(tabindex > 0){ if(!lowest || tabindex < lowestTabindex){ lowestTabindex = tabindex; lowest = child; } if(!highest || tabindex >= highestTabindex){ highestTabindex = tabindex; highest = child; } } } if(isShown && child.nodeName.toUpperCase() != 'SELECT'){ walkTree(child) } }); }; if(dijit._isElementShown(root)){ walkTree(root) } return { first: first, last: last, lowest: lowest, highest: highest }; } dijit.getFirstInTabbingOrder = function(/*String|DOMNode*/ root){ // summary: // Finds the descendant of the specified root node // that is first in the tabbing order var elems = dijit._getTabNavigable(dojo.byId(root)); return elems.lowest ? elems.lowest : elems.first; // DomNode }; dijit.getLastInTabbingOrder = function(/*String|DOMNode*/ root){ // summary: // Finds the descendant of the specified root node // that is last in the tabbing order var elems = dijit._getTabNavigable(dojo.byId(root)); return elems.last ? elems.last : elems.highest; // DomNode }; /*===== dojo.mixin(dijit, { // defaultDuration: Integer // The default animation speed (in ms) to use for all Dijit // transitional animations, unless otherwise specified // on a per-instance basis. Defaults to 200, overrided by // `djConfig.defaultDuration` defaultDuration: 200 }); =====*/ dijit.defaultDuration = dojo.config["defaultDuration"] || 200; })(dojo, dijit);
_base/manager.js
dojo.provide("dijit._base.manager"); dojo.declare("dijit.WidgetSet", null, { // summary: // A set of widgets indexed by id. A default instance of this class is // available as `dijit.registry` // // example: // Create a small list of widgets: // | var ws = new dijit.WidgetSet(); // | ws.add(dijit.byId("one")); // | ws.add(dijit.byId("two")); // | // destroy both: // | ws.forEach(function(w){ w.destroy(); }); // // example: // Using dijit.registry: // | dijit.registry.forEach(function(w){ /* do something */ }); constructor: function(){ this._hash = {}; this.length = 0; }, add: function(/*dijit._Widget*/ widget){ // summary: // Add a widget to this list. If a duplicate ID is detected, a error is thrown. // // widget: dijit._Widget // Any dijit._Widget subclass. if(this._hash[widget.id]){ throw new Error("Tried to register widget with id==" + widget.id + " but that id is already registered"); } this._hash[widget.id] = widget; this.length++; }, remove: function(/*String*/ id){ // summary: // Remove a widget from this WidgetSet. Does not destroy the widget; simply // removes the reference. if(this._hash[id]){ delete this._hash[id]; this.length--; } }, forEach: function(/*Function*/ func, /* Object? */thisObj){ // summary: // Call specified function for each widget in this set. // // func: // A callback function to run for each item. Is passed the widget, the index // in the iteration, and the full hash, similar to `dojo.forEach`. // // thisObj: // An optional scope parameter // // example: // Using the default `dijit.registry` instance: // | dijit.registry.forEach(function(widget){ // | console.log(widget.declaredClass); // | }); // // returns: // Returns self, in order to allow for further chaining. thisObj = thisObj || dojo.global; var i = 0, id; for(id in this._hash){ func.call(thisObj, this._hash[id], i++, this._hash); } return this; // dijit.WidgetSet }, filter: function(/*Function*/ filter, /* Object? */thisObj){ // summary: // Filter down this WidgetSet to a smaller new WidgetSet // Works the same as `dojo.filter` and `dojo.NodeList.filter` // // filter: // Callback function to test truthiness. Is passed the widget // reference and the pseudo-index in the object. // // thisObj: Object? // Option scope to use for the filter function. // // example: // Arbitrary: select the odd widgets in this list // | dijit.registry.filter(function(w, i){ // | return i % 2 == 0; // | }).forEach(function(w){ /* odd ones */ }); thisObj = thisObj || dojo.global; var res = new dijit.WidgetSet(), i = 0, id; for(id in this._hash){ var w = this._hash[id]; if(filter.call(thisObj, w, i++, this._hash)){ res.add(w); } } return res; // dijit.WidgetSet }, byId: function(/*String*/ id){ // summary: // Find a widget in this list by it's id. // example: // Test if an id is in a particular WidgetSet // | var ws = new dijit.WidgetSet(); // | ws.add(dijit.byId("bar")); // | var t = ws.byId("bar") // returns a widget // | var x = ws.byId("foo"); // returns undefined return this._hash[id]; // dijit._Widget }, byClass: function(/*String*/ cls){ // summary: // Reduce this widgetset to a new WidgetSet of a particular `declaredClass` // // cls: String // The Class to scan for. Full dot-notated string. // // example: // Find all `dijit.TitlePane`s in a page: // | dijit.registry.byClass("dijit.TitlePane").forEach(function(tp){ tp.close(); }); var res = new dijit.WidgetSet(), id, widget; for(id in this._hash){ widget = this._hash[id]; if(widget.declaredClass == cls){ res.add(widget); } } return res; // dijit.WidgetSet }, toArray: function(){ // summary: // Convert this WidgetSet into a true Array // // example: // Work with the widget .domNodes in a real Array // | dojo.map(dijit.registry.toArray(), function(w){ return w.domNode; }); var ar = []; for(var id in this._hash){ ar.push(this._hash[id]); } return ar; // dijit._Widget[] }, map: function(/* Function */func, /* Object? */thisObj){ // summary: // Create a new Array from this WidgetSet, following the same rules as `dojo.map` // example: // | var nodes = dijit.registry.map(function(w){ return w.domNode; }); // // returns: // A new array of the returned values. return dojo.map(this.toArray(), func, thisObj); // Array }, every: function(func, thisObj){ // summary: // A synthetic clone of `dojo.every` acting explictly on this WidgetSet // // func: Function // A callback function run for every widget in this list. Exits loop // when the first false return is encountered. // // thisObj: Object? // Optional scope parameter to use for the callback thisObj = thisObj || dojo.global; var x = 0, i; for(i in this._hash){ if(!func.call(thisObj, this._hash[i], x++, this._hash)){ return false; // Boolean } } return true; // Boolean }, some: function(func, thisObj){ // summary: // A synthetic clone of `dojo.some` acting explictly on this WidgetSet // // func: Function // A callback function run for every widget in this list. Exits loop // when the first true return is encountered. // // thisObj: Object? // Optional scope parameter to use for the callback thisObj = thisObj || dojo.global; var x = 0, i; for(i in this._hash){ if(func.call(thisObj, this._hash[i], x++, this._hash)){ return true; // Boolean } } return false; // Boolean } }); /*===== dijit.registry = { // summary: // A list of widgets on a page. // description: // Is an instance of `dijit.WidgetSet` }; =====*/ dijit.registry= new dijit.WidgetSet(); dijit._widgetTypeCtr = {}; dijit.getUniqueId = function(/*String*/widgetType){ // summary: // Generates a unique id for a given widgetType var id; do{ id = widgetType + "_" + (widgetType in dijit._widgetTypeCtr ? ++dijit._widgetTypeCtr[widgetType] : dijit._widgetTypeCtr[widgetType] = 0); }while(dijit.byId(id)); return id; // String }; dijit.findWidgets = function(/*DomNode*/ root){ // summary: // Search subtree under root returning widgets found. // Doesn't search for nested widgets (ie, widgets inside other widgets). var outAry = []; function getChildrenHelper(root){ for(var node = root.firstChild; node; node = node.nextSibling){ if(node.nodeType == 1){ var widgetId = node.getAttribute("widgetId"); if(widgetId){ var widget = dijit.byId(widgetId); outAry.push(widget); }else{ getChildrenHelper(node); } } } } getChildrenHelper(root); return outAry; }; dijit._destroyAll = function(){ // summary: // Code to destroy all widgets and do other cleanup on page unload // Clean up focus manager lingering references to widgets and nodes dijit._curFocus = null; dijit._prevFocus = null; dijit._activeStack = []; // Destroy all the widgets, top down dojo.forEach(dijit.findWidgets(dojo.body()), function(widget){ // Avoid double destroy of widgets like Menu that are attached to <body> // even though they are logically children of other widgets. if(!widget._destroyed){ if(widget.destroyRecursive){ widget.destroyRecursive(); }else if(widget.destroy){ widget.destroy(); } } }); }; if(dojo.isIE){ // Only run _destroyAll() for IE because we think it's only necessary in that case, // and because it causes problems on FF. See bug #3531 for details. dojo.addOnWindowUnload(function(){ dijit._destroyAll(); }); } dijit.byId = function(/*String|Widget*/id){ // summary: // Returns a widget by it's id, or if passed a widget, no-op (like dojo.byId()) return typeof id == "string" ? dijit.registry._hash[id] : id; // dijit._Widget }; dijit.byNode = function(/* DOMNode */ node){ // summary: // Returns the widget corresponding to the given DOMNode return dijit.registry.byId(node.getAttribute("widgetId")); // dijit._Widget }; dijit.getEnclosingWidget = function(/* DOMNode */ node){ // summary: // Returns the widget whose DOM tree contains the specified DOMNode, or null if // the node is not contained within the DOM tree of any widget while(node){ var id = node.getAttribute && node.getAttribute("widgetId"); if(id){ return dijit.byId(id); } node = node.parentNode; } return null; }; dijit._isElementShown = function(/*Element*/elem){ var style = dojo.style(elem); return (style.visibility != "hidden") && (style.visibility != "collapsed") && (style.display != "none") && (dojo.attr(elem, "type") != "hidden"); } dijit.isTabNavigable = function(/*Element*/elem){ // summary: // Tests if an element is tab-navigable // TODO: convert (and rename method) to return effectivite tabIndex; will save time in _getTabNavigable() if(dojo.attr(elem, "disabled")){ return false; }else if(dojo.hasAttr(elem, "tabIndex")){ // Explicit tab index setting return dojo.attr(elem, "tabIndex") >= 0; // boolean }else{ // No explicit tabIndex setting, need to investigate node type switch(elem.nodeName.toLowerCase()){ case "a": // An <a> w/out a tabindex is only navigable if it has an href return dojo.hasAttr(elem, "href"); case "area": case "button": case "input": case "object": case "select": case "textarea": // These are navigable by default return true; case "iframe": // If it's an editor <iframe> then it's tab navigable. if(dojo.isMoz){ return elem.contentDocument.designMode == "on"; }else if(dojo.isWebKit){ var doc = elem.contentDocument, body = doc && doc.body; return body && body.contentEditable == 'true'; }else{ doc = elem.contentWindow.document; body = doc && doc.body; return body && body.firstChild && body.firstChild.contentEditable == 'true'; } default: return elem.contentEditable == 'true'; } } }; dijit._getTabNavigable = function(/*DOMNode*/root){ // summary: // Finds descendants of the specified root node. // // description: // Finds the following descendants of the specified root node: // * the first tab-navigable element in document order // without a tabIndex or with tabIndex="0" // * the last tab-navigable element in document order // without a tabIndex or with tabIndex="0" // * the first element in document order with the lowest // positive tabIndex value // * the last element in document order with the highest // positive tabIndex value var first, last, lowest, lowestTabindex, highest, highestTabindex; var walkTree = function(/*DOMNode*/parent){ dojo.query("> *", parent).forEach(function(child){ var isShown = dijit._isElementShown(child); if(isShown && dijit.isTabNavigable(child)){ var tabindex = dojo.attr(child, "tabIndex"); if(!dojo.hasAttr(child, "tabIndex") || tabindex == 0){ if(!first){ first = child; } last = child; }else if(tabindex > 0){ if(!lowest || tabindex < lowestTabindex){ lowestTabindex = tabindex; lowest = child; } if(!highest || tabindex >= highestTabindex){ highestTabindex = tabindex; highest = child; } } } if(isShown && child.nodeName.toUpperCase() != 'SELECT'){ walkTree(child) } }); }; if(dijit._isElementShown(root)){ walkTree(root) } return { first: first, last: last, lowest: lowest, highest: highest }; } dijit.getFirstInTabbingOrder = function(/*String|DOMNode*/root){ // summary: // Finds the descendant of the specified root node // that is first in the tabbing order var elems = dijit._getTabNavigable(dojo.byId(root)); return elems.lowest ? elems.lowest : elems.first; // DomNode }; dijit.getLastInTabbingOrder = function(/*String|DOMNode*/root){ // summary: // Finds the descendant of the specified root node // that is last in the tabbing order var elems = dijit._getTabNavigable(dojo.byId(root)); return elems.last ? elems.last : elems.highest; // DomNode }; /*===== dojo.mixin(dijit, { // defaultDuration: Integer // The default animation speed (in ms) to use for all Dijit // transitional animations, unless otherwise specified // on a per-instance basis. Defaults to 200, overrided by // `djConfig.defaultDuration` defaultDuration: 300 }); =====*/ dijit.defaultDuration = dojo.config["defaultDuration"] || 200;
More performance tweaks for manager.js, fixes #9915 !strict. Needed to tweak robot too so that dijit.byId() in the robot test files will still find widgets w/in the iframe (that loads the URL). git-svn-id: 674a2d6b1e32e53f607eb824547723f32280967e@20981 560b804f-0ae3-0310-86f3-f6aa0a117693
_base/manager.js
More performance tweaks for manager.js, fixes #9915 !strict.
<ide><path>base/manager.js <ide> <ide> }); <ide> <del>/*===== <del>dijit.registry = { <del> // summary: <del> // A list of widgets on a page. <del> // description: <del> // Is an instance of `dijit.WidgetSet` <del>}; <del>=====*/ <del>dijit.registry= new dijit.WidgetSet(); <del> <del>dijit._widgetTypeCtr = {}; <del> <del>dijit.getUniqueId = function(/*String*/widgetType){ <del> // summary: <del> // Generates a unique id for a given widgetType <del> <del> var id; <del> do{ <del> id = widgetType + "_" + <del> (widgetType in dijit._widgetTypeCtr ? <del> ++dijit._widgetTypeCtr[widgetType] : dijit._widgetTypeCtr[widgetType] = 0); <del> }while(dijit.byId(id)); <del> return id; // String <del>}; <del> <del>dijit.findWidgets = function(/*DomNode*/ root){ <del> // summary: <del> // Search subtree under root returning widgets found. <del> // Doesn't search for nested widgets (ie, widgets inside other widgets). <del> <del> var outAry = []; <del> <del> function getChildrenHelper(root){ <del> for(var node = root.firstChild; node; node = node.nextSibling){ <del> if(node.nodeType == 1){ <del> var widgetId = node.getAttribute("widgetId"); <del> if(widgetId){ <del> var widget = dijit.byId(widgetId); <del> outAry.push(widget); <del> }else{ <del> getChildrenHelper(node); <del> } <del> } <del> } <del> } <del> <del> getChildrenHelper(root); <del> return outAry; <del>}; <del> <del>dijit._destroyAll = function(){ <del> // summary: <del> // Code to destroy all widgets and do other cleanup on page unload <del> <del> // Clean up focus manager lingering references to widgets and nodes <del> dijit._curFocus = null; <del> dijit._prevFocus = null; <del> dijit._activeStack = []; <del> <del> // Destroy all the widgets, top down <del> dojo.forEach(dijit.findWidgets(dojo.body()), function(widget){ <del> // Avoid double destroy of widgets like Menu that are attached to <body> <del> // even though they are logically children of other widgets. <del> if(!widget._destroyed){ <del> if(widget.destroyRecursive){ <del> widget.destroyRecursive(); <del> }else if(widget.destroy){ <del> widget.destroy(); <del> } <del> } <del> }); <del>}; <del> <del>if(dojo.isIE){ <del> // Only run _destroyAll() for IE because we think it's only necessary in that case, <del> // and because it causes problems on FF. See bug #3531 for details. <del> dojo.addOnWindowUnload(function(){ <del> dijit._destroyAll(); <del> }); <del>} <del> <del>dijit.byId = function(/*String|Widget*/id){ <del> // summary: <del> // Returns a widget by it's id, or if passed a widget, no-op (like dojo.byId()) <del> return typeof id == "string" ? dijit.registry._hash[id] : id; // dijit._Widget <del>}; <del> <del>dijit.byNode = function(/* DOMNode */ node){ <del> // summary: <del> // Returns the widget corresponding to the given DOMNode <del> return dijit.registry.byId(node.getAttribute("widgetId")); // dijit._Widget <del>}; <del> <del>dijit.getEnclosingWidget = function(/* DOMNode */ node){ <del> // summary: <del> // Returns the widget whose DOM tree contains the specified DOMNode, or null if <del> // the node is not contained within the DOM tree of any widget <del> while(node){ <del> var id = node.getAttribute && node.getAttribute("widgetId"); <del> if(id){ <del> return dijit.byId(id); <del> } <del> node = node.parentNode; <del> } <del> return null; <del>}; <del> <del>dijit._isElementShown = function(/*Element*/elem){ <del> var style = dojo.style(elem); <del> return (style.visibility != "hidden") <del> && (style.visibility != "collapsed") <del> && (style.display != "none") <del> && (dojo.attr(elem, "type") != "hidden"); <del>} <del> <del>dijit.isTabNavigable = function(/*Element*/elem){ <del> // summary: <del> // Tests if an element is tab-navigable <del> <del> // TODO: convert (and rename method) to return effectivite tabIndex; will save time in _getTabNavigable() <del> if(dojo.attr(elem, "disabled")){ <del> return false; <del> }else if(dojo.hasAttr(elem, "tabIndex")){ <del> // Explicit tab index setting <del> return dojo.attr(elem, "tabIndex") >= 0; // boolean <del> }else{ <del> // No explicit tabIndex setting, need to investigate node type <del> switch(elem.nodeName.toLowerCase()){ <del> case "a": <del> // An <a> w/out a tabindex is only navigable if it has an href <del> return dojo.hasAttr(elem, "href"); <del> case "area": <del> case "button": <del> case "input": <del> case "object": <del> case "select": <del> case "textarea": <del> // These are navigable by default <del> return true; <del> case "iframe": <del> // If it's an editor <iframe> then it's tab navigable. <del> if(dojo.isMoz){ <del> return elem.contentDocument.designMode == "on"; <del> }else if(dojo.isWebKit){ <del> var doc = elem.contentDocument, <del> body = doc && doc.body; <del> return body && body.contentEditable == 'true'; <del> }else{ <del> doc = elem.contentWindow.document; <del> body = doc && doc.body; <del> return body && body.firstChild && body.firstChild.contentEditable == 'true'; <del> } <del> default: <del> return elem.contentEditable == 'true'; <del> } <del> } <del>}; <del> <del>dijit._getTabNavigable = function(/*DOMNode*/root){ <del> // summary: <del> // Finds descendants of the specified root node. <del> // <del> // description: <del> // Finds the following descendants of the specified root node: <del> // * the first tab-navigable element in document order <del> // without a tabIndex or with tabIndex="0" <del> // * the last tab-navigable element in document order <del> // without a tabIndex or with tabIndex="0" <del> // * the first element in document order with the lowest <del> // positive tabIndex value <del> // * the last element in document order with the highest <del> // positive tabIndex value <del> var first, last, lowest, lowestTabindex, highest, highestTabindex; <del> var walkTree = function(/*DOMNode*/parent){ <del> dojo.query("> *", parent).forEach(function(child){ <del> var isShown = dijit._isElementShown(child); <del> if(isShown && dijit.isTabNavigable(child)){ <del> var tabindex = dojo.attr(child, "tabIndex"); <del> if(!dojo.hasAttr(child, "tabIndex") || tabindex == 0){ <del> if(!first){ first = child; } <del> last = child; <del> }else if(tabindex > 0){ <del> if(!lowest || tabindex < lowestTabindex){ <del> lowestTabindex = tabindex; <del> lowest = child; <del> } <del> if(!highest || tabindex >= highestTabindex){ <del> highestTabindex = tabindex; <del> highest = child; <add>(function(dojo, dijit){ <add> <add> /*===== <add> dijit.registry = { <add> // summary: <add> // A list of widgets on a page. <add> // description: <add> // Is an instance of `dijit.WidgetSet` <add> }; <add> =====*/ <add> dijit.registry = new dijit.WidgetSet(); <add> <add> var hash = dijit.registry._hash; <add> <add> dijit.byId = function(/*String|dijit._Widget*/ id){ <add> // summary: <add> // Returns a widget by it's id, or if passed a widget, no-op (like dojo.byId()) <add> return typeof id == "string" ? hash[id] : id; // dijit._Widget <add> }; <add> <add> var _widgetTypeCtr = {}; <add> dijit.getUniqueId = function(/*String*/widgetType){ <add> // summary: <add> // Generates a unique id for a given widgetType <add> <add> var id; <add> do{ <add> id = widgetType + "_" + <add> (widgetType in _widgetTypeCtr ? <add> ++_widgetTypeCtr[widgetType] : _widgetTypeCtr[widgetType] = 0); <add> }while(hash[id]); <add> return id; // String <add> }; <add> <add> dijit.findWidgets = function(/*DomNode*/ root){ <add> // summary: <add> // Search subtree under root returning widgets found. <add> // Doesn't search for nested widgets (ie, widgets inside other widgets). <add> <add> var outAry = []; <add> <add> function getChildrenHelper(root){ <add> for(var node = root.firstChild; node; node = node.nextSibling){ <add> if(node.nodeType == 1){ <add> var widgetId = node.getAttribute("widgetId"); <add> if(widgetId){ <add> outAry.push(hash[widgetId]); <add> }else{ <add> getChildrenHelper(node); <ide> } <ide> } <ide> } <del> if(isShown && child.nodeName.toUpperCase() != 'SELECT'){ walkTree(child) } <add> } <add> <add> getChildrenHelper(root); <add> return outAry; <add> }; <add> <add> dijit._destroyAll = function(){ <add> // summary: <add> // Code to destroy all widgets and do other cleanup on page unload <add> <add> // Clean up focus manager lingering references to widgets and nodes <add> dijit._curFocus = null; <add> dijit._prevFocus = null; <add> dijit._activeStack = []; <add> <add> // Destroy all the widgets, top down <add> dojo.forEach(dijit.findWidgets(dojo.body()), function(widget){ <add> // Avoid double destroy of widgets like Menu that are attached to <body> <add> // even though they are logically children of other widgets. <add> if(!widget._destroyed){ <add> if(widget.destroyRecursive){ <add> widget.destroyRecursive(); <add> }else if(widget.destroy){ <add> widget.destroy(); <add> } <add> } <ide> }); <ide> }; <del> if(dijit._isElementShown(root)){ walkTree(root) } <del> return { first: first, last: last, lowest: lowest, highest: highest }; <del>} <del>dijit.getFirstInTabbingOrder = function(/*String|DOMNode*/root){ <del> // summary: <del> // Finds the descendant of the specified root node <del> // that is first in the tabbing order <del> var elems = dijit._getTabNavigable(dojo.byId(root)); <del> return elems.lowest ? elems.lowest : elems.first; // DomNode <del>}; <del> <del>dijit.getLastInTabbingOrder = function(/*String|DOMNode*/root){ <del> // summary: <del> // Finds the descendant of the specified root node <del> // that is last in the tabbing order <del> var elems = dijit._getTabNavigable(dojo.byId(root)); <del> return elems.last ? elems.last : elems.highest; // DomNode <del>}; <del> <del>/*===== <del>dojo.mixin(dijit, { <del> // defaultDuration: Integer <del> // The default animation speed (in ms) to use for all Dijit <del> // transitional animations, unless otherwise specified <del> // on a per-instance basis. Defaults to 200, overrided by <del> // `djConfig.defaultDuration` <del> defaultDuration: 300 <del>}); <del>=====*/ <del> <del>dijit.defaultDuration = dojo.config["defaultDuration"] || 200; <add> <add> if(dojo.isIE){ <add> // Only run _destroyAll() for IE because we think it's only necessary in that case, <add> // and because it causes problems on FF. See bug #3531 for details. <add> dojo.addOnWindowUnload(function(){ <add> dijit._destroyAll(); <add> }); <add> } <add> <add> dijit.byNode = function(/*DOMNode*/ node){ <add> // summary: <add> // Returns the widget corresponding to the given DOMNode <add> return hash[node.getAttribute("widgetId")]; // dijit._Widget <add> }; <add> <add> dijit.getEnclosingWidget = function(/*DOMNode*/ node){ <add> // summary: <add> // Returns the widget whose DOM tree contains the specified DOMNode, or null if <add> // the node is not contained within the DOM tree of any widget <add> while(node){ <add> var id = node.getAttribute && node.getAttribute("widgetId"); <add> if(id){ <add> return hash[id]; <add> } <add> node = node.parentNode; <add> } <add> return null; <add> }; <add> <add> dijit._isElementShown = function(/*Element*/ elem){ <add> var style = dojo.style(elem); <add> return (style.visibility != "hidden") <add> && (style.visibility != "collapsed") <add> && (style.display != "none") <add> && (dojo.attr(elem, "type") != "hidden"); <add> } <add> <add> dijit.isTabNavigable = function(/*Element*/ elem){ <add> // summary: <add> // Tests if an element is tab-navigable <add> <add> // TODO: convert (and rename method) to return effectivite tabIndex; will save time in _getTabNavigable() <add> if(dojo.attr(elem, "disabled")){ <add> return false; <add> }else if(dojo.hasAttr(elem, "tabIndex")){ <add> // Explicit tab index setting <add> return dojo.attr(elem, "tabIndex") >= 0; // boolean <add> }else{ <add> // No explicit tabIndex setting, need to investigate node type <add> switch(elem.nodeName.toLowerCase()){ <add> case "a": <add> // An <a> w/out a tabindex is only navigable if it has an href <add> return dojo.hasAttr(elem, "href"); <add> case "area": <add> case "button": <add> case "input": <add> case "object": <add> case "select": <add> case "textarea": <add> // These are navigable by default <add> return true; <add> case "iframe": <add> // If it's an editor <iframe> then it's tab navigable. <add> if(dojo.isMoz){ <add> return elem.contentDocument.designMode == "on"; <add> }else if(dojo.isWebKit){ <add> var doc = elem.contentDocument, <add> body = doc && doc.body; <add> return body && body.contentEditable == 'true'; <add> }else{ <add> doc = elem.contentWindow.document; <add> body = doc && doc.body; <add> return body && body.firstChild && body.firstChild.contentEditable == 'true'; <add> } <add> default: <add> return elem.contentEditable == 'true'; <add> } <add> } <add> }; <add> <add> dijit._getTabNavigable = function(/*DOMNode*/ root){ <add> // summary: <add> // Finds descendants of the specified root node. <add> // <add> // description: <add> // Finds the following descendants of the specified root node: <add> // * the first tab-navigable element in document order <add> // without a tabIndex or with tabIndex="0" <add> // * the last tab-navigable element in document order <add> // without a tabIndex or with tabIndex="0" <add> // * the first element in document order with the lowest <add> // positive tabIndex value <add> // * the last element in document order with the highest <add> // positive tabIndex value <add> var first, last, lowest, lowestTabindex, highest, highestTabindex; <add> var walkTree = function(/*DOMNode*/parent){ <add> dojo.query("> *", parent).forEach(function(child){ <add> var isShown = dijit._isElementShown(child); <add> if(isShown && dijit.isTabNavigable(child)){ <add> var tabindex = dojo.attr(child, "tabIndex"); <add> if(!dojo.hasAttr(child, "tabIndex") || tabindex == 0){ <add> if(!first){ first = child; } <add> last = child; <add> }else if(tabindex > 0){ <add> if(!lowest || tabindex < lowestTabindex){ <add> lowestTabindex = tabindex; <add> lowest = child; <add> } <add> if(!highest || tabindex >= highestTabindex){ <add> highestTabindex = tabindex; <add> highest = child; <add> } <add> } <add> } <add> if(isShown && child.nodeName.toUpperCase() != 'SELECT'){ walkTree(child) } <add> }); <add> }; <add> if(dijit._isElementShown(root)){ walkTree(root) } <add> return { first: first, last: last, lowest: lowest, highest: highest }; <add> } <add> dijit.getFirstInTabbingOrder = function(/*String|DOMNode*/ root){ <add> // summary: <add> // Finds the descendant of the specified root node <add> // that is first in the tabbing order <add> var elems = dijit._getTabNavigable(dojo.byId(root)); <add> return elems.lowest ? elems.lowest : elems.first; // DomNode <add> }; <add> <add> dijit.getLastInTabbingOrder = function(/*String|DOMNode*/ root){ <add> // summary: <add> // Finds the descendant of the specified root node <add> // that is last in the tabbing order <add> var elems = dijit._getTabNavigable(dojo.byId(root)); <add> return elems.last ? elems.last : elems.highest; // DomNode <add> }; <add> <add> /*===== <add> dojo.mixin(dijit, { <add> // defaultDuration: Integer <add> // The default animation speed (in ms) to use for all Dijit <add> // transitional animations, unless otherwise specified <add> // on a per-instance basis. Defaults to 200, overrided by <add> // `djConfig.defaultDuration` <add> defaultDuration: 200 <add> }); <add> =====*/ <add> <add> dijit.defaultDuration = dojo.config["defaultDuration"] || 200; <add> <add>})(dojo, dijit);
Java
apache-2.0
165ded8ac6d1e544f3254d531e91f2c19265f5d0
0
GoogleCloudPlatform/appengine-java-standard,GoogleCloudPlatform/appengine-java-standard,GoogleCloudPlatform/appengine-java-standard,GoogleCloudPlatform/appengine-java-standard
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.appengine.tools.development; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link URLStreamHandlerFactory} which installs * {@link URLStreamHandler URLStreamHandlers} that App Engine needs to support. * (For example, the "http" and "https" protocols). This factory returns * handlers that delegate to the * {@link com.google.appengine.api.urlfetch.URLFetchService} when running in an * App Engine container, and returns the default handlers when running outside * an App Engine container. * */ public class StreamHandlerFactory implements URLStreamHandlerFactory { private static boolean factoryIsInstalled; /** Need to access this method via reflection because it is protected on {@link URL}. */ @Nullable private static final Method GET_URL_STREAM_HANDLER; private static void trySetAccessible(AccessibleObject o) { try { AccessibleObject.class.getMethod("trySetAccessible").invoke(o); } catch (NoSuchMethodException e) { o.setAccessible(true); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } static { Method m = null; try { m = URL.class.getDeclaredMethod("getURLStreamHandler", String.class); trySetAccessible(m); } catch (NoSuchMethodException e) { // Don't want to completely hose people if the jvm they're running // locally doesn't have this method. Logger.getLogger(StreamHandlerFactory.class.getName()).info( "Unable to register default URLStreamHandlers. You will be unable to " + "access http and https URLs outside the App Engine environment."); } GET_URL_STREAM_HANDLER = m; } private Map<String, URLStreamHandler> handlers = new HashMap<String, URLStreamHandler>(); /** * Installs this StreamHandlerFactory. * * @throws IllegalStateException if a factory has already been installed, and * it is not a StreamHandlerFactory. * @throws RuntimeException if an unexpected, catastrophic failure occurs * while installing the handler. */ public static void install() { synchronized (StreamHandlerFactory.class) { if (!factoryIsInstalled) { StreamHandlerFactory factory = new StreamHandlerFactory(); try { URL.setURLStreamHandlerFactory(factory); } catch (Error e) { // Yes, URL.setURLStreamHandlerFactory() does in fact throw Error. // That's Java 1.0 code for you. // It's possible that we were already installed for this JVM, but in a // different ClassLoader. Object currentFactory; try { Field f = URL.class.getDeclaredField("factory"); trySetAccessible(f); currentFactory = f.get(null); } catch (Exception ex) { throw new RuntimeException("Failed to find the currently installed factory", ex); } if (currentFactory == null) { throw new RuntimeException("The current factory is null, but we were unable " + "to set a new factory", e); } String currentFactoryType = currentFactory.getClass().getName(); if (currentFactoryType.equals(StreamHandlerFactory.class.getName())) { factoryIsInstalled = true; return; } throw new IllegalStateException("A factory of type " + currentFactoryType + " has already been installed"); } } } } private StreamHandlerFactory() { for (String protocol : Arrays.asList("http", "https")) { URLStreamHandler fallbackHandler = getFallbackStreamHandler(protocol); handlers.put(protocol, new LocalURLFetchServiceStreamHandler(fallbackHandler)); } } @Override public URLStreamHandler createURLStreamHandler(String protocol) { return handlers.get(protocol); } /** * All calls to this method must take place before we register the * stream handler factory with URL. */ private static URLStreamHandler getFallbackStreamHandler(String protocol) { if (GET_URL_STREAM_HANDLER == null) { return null; } // See what handler gets returned before we customize the stream handler // factory. We'll use that as our fallback for this protocol when the url // fetch service is not available. URLStreamHandler existingHandler = (URLStreamHandler) invoke(null, GET_URL_STREAM_HANDLER, protocol); if (existingHandler.getClass().getName().equals( LocalURLFetchServiceStreamHandler.class.getName())) { // Looks like the handler was already registered via a different // classloader. We'll just reuse their fallback handler as our own. Method getFallbackHandler = getDeclaredMethod(existingHandler.getClass(), "getFallbackHandler"); return (URLStreamHandler) invoke(existingHandler, getFallbackHandler); } // We're the first classloader to register a custom stream handler, so the // existing handler is the one we want to fall back to. return existingHandler; } // Reflection utilities static Object invoke(Object target, Method m, Object... args) { try { return m.invoke(target, args); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } throw new RuntimeException(e.getTargetException()); } } static Method getDeclaredMethod(Class<?> cls, String methodName, Class<?>... args) { try { Method m = cls.getDeclaredMethod(methodName, args); trySetAccessible(m); return m; } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } }
api_dev/src/main/java/com/google/appengine/tools/development/StreamHandlerFactory.java
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.appengine.tools.development; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link URLStreamHandlerFactory} which installs * {@link URLStreamHandler URLStreamHandlers} that App Engine needs to support. * (For example, the "http" and "https" protocols). This factory returns * handlers that delegate to the * {@link com.google.appengine.api.urlfetch.URLFetchService} when running in an * App Engine container, and returns the default handlers when running outside * an App Engine container. * */ public class StreamHandlerFactory implements URLStreamHandlerFactory { private static boolean factoryIsInstalled; /** Need to access this method via reflection because it is protected on {@link URL}. */ @Nullable private static final Method GET_URL_STREAM_HANDLER; static { Method m = null; try { m = URL.class.getDeclaredMethod("getURLStreamHandler", String.class); m.setAccessible(true); } catch (NoSuchMethodException e) { // Don't want to completely hose people if the jvm they're running // locally doesn't have this method. Logger.getLogger(StreamHandlerFactory.class.getName()).info( "Unable to register default URLStreamHandlers. You will be unable to " + "access http and https URLs outside the App Engine environment."); } GET_URL_STREAM_HANDLER = m; } private Map<String, URLStreamHandler> handlers = new HashMap<String, URLStreamHandler>(); /** * Installs this StreamHandlerFactory. * * @throws IllegalStateException if a factory has already been installed, and * it is not a StreamHandlerFactory. * @throws RuntimeException if an unexpected, catastrophic failure occurs * while installing the handler. */ public static void install() { synchronized (StreamHandlerFactory.class) { if (!factoryIsInstalled) { StreamHandlerFactory factory = new StreamHandlerFactory(); try { URL.setURLStreamHandlerFactory(factory); } catch (Error e) { // Yes, URL.setURLStreamHandlerFactory() does in fact throw Error. // That's Java 1.0 code for you. // It's possible that we were already installed for this JVM, but in a // different ClassLoader. Object currentFactory; try { Field f = URL.class.getDeclaredField("factory"); f.setAccessible(true); currentFactory = f.get(null); } catch (Exception ex) { throw new RuntimeException("Failed to find the currently installed factory", ex); } if (currentFactory == null) { throw new RuntimeException("The current factory is null, but we were unable " + "to set a new factory", e); } String currentFactoryType = currentFactory.getClass().getName(); if (currentFactoryType.equals(StreamHandlerFactory.class.getName())) { factoryIsInstalled = true; return; } throw new IllegalStateException("A factory of type " + currentFactoryType + " has already been installed"); } } } } private StreamHandlerFactory() { for (String protocol : Arrays.asList("http", "https")) { URLStreamHandler fallbackHandler = getFallbackStreamHandler(protocol); handlers.put(protocol, new LocalURLFetchServiceStreamHandler(fallbackHandler)); } } @Override public URLStreamHandler createURLStreamHandler(String protocol) { return handlers.get(protocol); } /** * All calls to this method must take place before we register the * stream handler factory with URL. */ private static URLStreamHandler getFallbackStreamHandler(String protocol) { if (GET_URL_STREAM_HANDLER == null) { return null; } // See what handler gets returned before we customize the stream handler // factory. We'll use that as our fallback for this protocol when the url // fetch service is not available. URLStreamHandler existingHandler = (URLStreamHandler) invoke(null, GET_URL_STREAM_HANDLER, protocol); if (existingHandler.getClass().getName().equals( LocalURLFetchServiceStreamHandler.class.getName())) { // Looks like the handler was already registered via a different // classloader. We'll just reuse their fallback handler as our own. Method getFallbackHandler = getDeclaredMethod(existingHandler.getClass(), "getFallbackHandler"); return (URLStreamHandler) invoke(existingHandler, getFallbackHandler); } // We're the first classloader to register a custom stream handler, so the // existing handler is the one we want to fall back to. return existingHandler; } // Reflection utilities static Object invoke(Object target, Method m, Object... args) { try { return m.invoke(target, args); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof RuntimeException) { throw (RuntimeException) e.getTargetException(); } throw new RuntimeException(e.getTargetException()); } } static Method getDeclaredMethod(Class<?> cls, String methodName, Class<?>... args) { try { Method m = cls.getDeclaredMethod(methodName, args); m.setAccessible(true); return m; } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } }
Internal change PiperOrigin-RevId: 473134154 Change-Id: I53279c9206e5f0149fae7b79354b9c2afcc45461
api_dev/src/main/java/com/google/appengine/tools/development/StreamHandlerFactory.java
Internal change
<ide><path>pi_dev/src/main/java/com/google/appengine/tools/development/StreamHandlerFactory.java <ide> <ide> package com.google.appengine.tools.development; <ide> <add>import java.lang.reflect.AccessibleObject; <ide> import java.lang.reflect.Field; <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <ide> import org.checkerframework.checker.nullness.qual.Nullable; <ide> <ide> /** <del> * A {@link URLStreamHandlerFactory} which installs <add> * A {@link URLStreamHandlerFactory} which installs <ide> * {@link URLStreamHandler URLStreamHandlers} that App Engine needs to support. <ide> * (For example, the "http" and "https" protocols). This factory returns <ide> * handlers that delegate to the <ide> /** Need to access this method via reflection because it is protected on {@link URL}. */ <ide> @Nullable private static final Method GET_URL_STREAM_HANDLER; <ide> <add> private static void trySetAccessible(AccessibleObject o) { <add> try { <add> AccessibleObject.class.getMethod("trySetAccessible").invoke(o); <add> } catch (NoSuchMethodException e) { <add> o.setAccessible(true); <add> } catch (ReflectiveOperationException e) { <add> throw new LinkageError(e.getMessage(), e); <add> } <add> } <add> <ide> static { <ide> Method m = null; <ide> try { <ide> m = URL.class.getDeclaredMethod("getURLStreamHandler", String.class); <del> m.setAccessible(true); <add> trySetAccessible(m); <ide> } catch (NoSuchMethodException e) { <ide> // Don't want to completely hose people if the jvm they're running <ide> // locally doesn't have this method. <ide> private Map<String, URLStreamHandler> handlers = new HashMap<String, URLStreamHandler>(); <ide> <ide> /** <del> * Installs this StreamHandlerFactory. <add> * Installs this StreamHandlerFactory. <ide> * <ide> * @throws IllegalStateException if a factory has already been installed, and <ide> * it is not a StreamHandlerFactory. <del> * @throws RuntimeException if an unexpected, catastrophic failure occurs <del> * while installing the handler. <add> * @throws RuntimeException if an unexpected, catastrophic failure occurs <add> * while installing the handler. <ide> */ <ide> public static void install() { <ide> synchronized (StreamHandlerFactory.class) { <del> if (!factoryIsInstalled) { <add> if (!factoryIsInstalled) { <ide> StreamHandlerFactory factory = new StreamHandlerFactory(); <del> <add> <ide> try { <ide> URL.setURLStreamHandlerFactory(factory); <ide> } catch (Error e) { <ide> // Yes, URL.setURLStreamHandlerFactory() does in fact throw Error. <ide> // That's Java 1.0 code for you. <del> <add> <ide> // It's possible that we were already installed for this JVM, but in a <ide> // different ClassLoader. <ide> Object currentFactory; <del> <add> <ide> try { <ide> Field f = URL.class.getDeclaredField("factory"); <del> f.setAccessible(true); <add> trySetAccessible(f); <ide> currentFactory = f.get(null); <ide> } catch (Exception ex) { <ide> throw new RuntimeException("Failed to find the currently installed factory", ex); <ide> } <ide> <ide> if (currentFactory == null) { <del> throw new RuntimeException("The current factory is null, but we were unable " <add> throw new RuntimeException("The current factory is null, but we were unable " <ide> + "to set a new factory", e); <ide> } <del> <add> <ide> String currentFactoryType = currentFactory.getClass().getName(); <ide> if (currentFactoryType.equals(StreamHandlerFactory.class.getName())) { <ide> factoryIsInstalled = true; <ide> return; <ide> } <del> <del> throw new IllegalStateException("A factory of type " + currentFactoryType + <add> <add> throw new IllegalStateException("A factory of type " + currentFactoryType + <ide> " has already been installed"); <ide> } <ide> } <ide> static Method getDeclaredMethod(Class<?> cls, String methodName, Class<?>... args) { <ide> try { <ide> Method m = cls.getDeclaredMethod(methodName, args); <del> m.setAccessible(true); <add> trySetAccessible(m); <ide> return m; <ide> } catch (NoSuchMethodException e) { <ide> throw new RuntimeException(e);
Java
mit
f41dc700328c752bfed345c2a4aeedb11b19e27e
0
pgentile/zucchini-ui,jeremiemarc/zucchini-ui,pgentile/zucchini-ui,jeremiemarc/zucchini-ui,pgentile/zucchini-ui,pgentile/zucchini-ui,pgentile/tests-cucumber,jeremiemarc/zucchini-ui,pgentile/tests-cucumber,pgentile/tests-cucumber,jeremiemarc/zucchini-ui,pgentile/tests-cucumber,pgentile/zucchini-ui
package io.testscucumber.capsule; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.server.AbstractServerFactory; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.testscucumber.backend.BackendBundle; import io.testscucumber.backend.support.exceptionhandler.ExitExceptionHandler; import org.eclipse.jetty.servlet.ServletHolder; public class TestsCucumberApplication extends Application<TestsCucumberConfiguration> { public static void main(final String... args) throws Exception { final TestsCucumberApplication application = new TestsCucumberApplication(); Thread.setDefaultUncaughtExceptionHandler(new ExitExceptionHandler()); application.run(args); } @Override public void initialize(final Bootstrap<TestsCucumberConfiguration> bootstrap) { bootstrap.addBundle(new BackendBundle()); bootstrap.addBundle(new AssetsBundle("/ui", "/ui", "index.html", "ui")); } @Override public void run(final TestsCucumberConfiguration configuration, final Environment environment) throws Exception { // Register the servlet that generates the UI Javascript config file final String apiRootPath = ((AbstractServerFactory) configuration.getServerFactory()).getJerseyRootPath(); final ServletHolder uiConfigServletHolder = new ServletHolder(new UIConfigServlet(environment.getObjectMapper(), apiRootPath)); environment.getApplicationContext().addServlet(uiConfigServletHolder, "/ui/scripts/config.js"); // Redirect to UI final ServletHolder redirectServletHolder = new ServletHolder(new RedirectServlet("/ui/")); environment.getApplicationContext().addServlet(redirectServletHolder, "/"); environment.getApplicationContext().addServlet(redirectServletHolder, "/ui"); } }
tests-cucumber-capsule/src/main/java/io/testscucumber/capsule/TestsCucumberApplication.java
package io.testscucumber.capsule; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.server.AbstractServerFactory; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.testscucumber.backend.BackendBundle; import io.testscucumber.backend.support.exceptionhandler.ExitExceptionHandler; import org.eclipse.jetty.servlet.ServletHolder; public class TestsCucumberApplication extends Application<TestsCucumberConfiguration> { public static void main(final String... args) throws Exception { final TestsCucumberApplication application = new TestsCucumberApplication(); Thread.setDefaultUncaughtExceptionHandler(new ExitExceptionHandler()); application.run(args); } @Override public void initialize(final Bootstrap<TestsCucumberConfiguration> bootstrap) { bootstrap.addBundle(new BackendBundle()); bootstrap.addBundle(new AssetsBundle("/ui", "/ui", "index.html", "ui")); } @Override public void run(final TestsCucumberConfiguration configuration, final Environment environment) throws Exception { // Register the servlet that generates the UI Javascript config file final String apiRootPath = ((AbstractServerFactory) configuration.getServerFactory()).getJerseyRootPath(); final ServletHolder uiConfigServletHolder = new ServletHolder(new UIConfigServlet(environment.getObjectMapper(), apiRootPath)); environment.getApplicationContext().addServlet(uiConfigServletHolder, "/ui/scripts/config.js"); // Redirect to UI final ServletHolder redirectServletHolder = new ServletHolder(new RedirectServlet("/ui/")); environment.getApplicationContext().addServlet(redirectServletHolder, "/"); } }
Redirect to "/ui/" when calling "/ui"
tests-cucumber-capsule/src/main/java/io/testscucumber/capsule/TestsCucumberApplication.java
Redirect to "/ui/" when calling "/ui"
<ide><path>ests-cucumber-capsule/src/main/java/io/testscucumber/capsule/TestsCucumberApplication.java <ide> // Redirect to UI <ide> final ServletHolder redirectServletHolder = new ServletHolder(new RedirectServlet("/ui/")); <ide> environment.getApplicationContext().addServlet(redirectServletHolder, "/"); <add> environment.getApplicationContext().addServlet(redirectServletHolder, "/ui"); <ide> } <ide> <ide> }
JavaScript
apache-2.0
a6c972d1ebd4db0464963b2bfd32863fcac985ed
0
implydata/laborer,implydata/laborer
'use strict'; var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var autoprefixer = require('autoprefixer'); var merge = require('merge-stream'); var del = require('del'); var typescript = require('typescript'); var tsLintConfig = require('./tslint-rules'); var sassLintRules = require('./sasslint-rules'); var gr = require('./gulp-reporters'); var webpack = require("webpack"); // Modifiers ============== var globalShowStats = false; exports.showStats = function() { globalShowStats = true; }; exports.hideStats = function() { globalShowStats = false; }; var globalFailOnError = false; exports.failOnError = function() { globalFailOnError = true; }; // TASKS ============== exports.taskStyle = function(opt) { opt = opt || {}; var rules = opt.rules || sassLintRules; return function() { var errorTexts = []; return gulp.src('./src/client/**/*.scss') .pipe($.sassLint({ rules: rules })) .pipe(gr.sassLintReporterFactory({ errorTexts: errorTexts })) .pipe($.sass({ outputStyle: 'compressed' }).on('error', gr.sassErrorFactory({ errorTexts: errorTexts }))) .pipe($.postcss([ autoprefixer({ browsers: ['> 1%', 'last 3 versions', 'Firefox ESR', 'Opera 12.1'], remove: false // If you have no legacy code, this option will make Autoprefixer about 10% faster. }) ])) .pipe(gulp.dest('./build/client')) .on('finish', function() { gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); }); }; }; exports.taskIcons = function() { return function() { return gulp.src('./src/client/**/*.svg') // Just copy for now .pipe(gulp.dest('./build/client')) }; }; exports.taskHtml = function() { return function() { return gulp.src('./src/client/**/*.html') // Just copy for now .pipe(gulp.dest('./build/client')) }; }; exports.taskClientTypeScript = function(opt) { opt = opt || {}; var declaration = opt.declaration || false; var tsProject = $.typescript.createProject({ typescript: typescript, noImplicitAny: true, noFallthroughCasesInSwitch: true, noImplicitReturns: true, noEmitOnError: true, target: 'ES5', module: 'commonjs', declaration: declaration, jsx: 'react' }); return function() { var errorTexts = []; function fixPath(str) { return str.replace('/build/tmp/', '/src/'); } var sourceFiles = gulp.src(['./src/{client,common}/**/*.{ts,tsx}']) .pipe($.cached('client')) .pipe($.tslint({configuration: tsLintConfig})) .pipe($.tslint.report( gr.tscLintReporterFactory({ errorTexts: errorTexts, fixPath: fixPath }), { emitError: false } )); var typeFiles = gulp.src(['./typings/**/*.d.ts']); var compiled = merge(sourceFiles, typeFiles) .pipe($.typescript( tsProject, undefined, gr.tscReporterFactory({ errorTexts: errorTexts, fixPath: fixPath, onFinish: function() { gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); } }) )); if (declaration) { return merge([ compiled.dts.pipe(gulp.dest('./build')), compiled.js.pipe(gulp.dest('./build')) ]) } else { return compiled.pipe(gulp.dest('./build')); } }; }; exports.taskServerTypeScript = function(opt) { opt = opt || {}; var declaration = opt.declaration || false; var tsProject = $.typescript.createProject({ typescript: typescript, noImplicitAny: true, noFallthroughCasesInSwitch: true, noImplicitReturns: true, noEmitOnError: true, target: 'ES5', module: 'commonjs', declaration: declaration }); return function() { var errorTexts = []; var sourceFiles = gulp.src(['./src/{server,common}/**/*.ts']) .pipe($.cached('server')) .pipe($.tslint({configuration: tsLintConfig})) .pipe($.tslint.report( gr.tscLintReporterFactory({ errorTexts: errorTexts }), { emitError: false } )); var typeFiles = gulp.src(['./typings/**/*.d.ts']); var compiled = merge(sourceFiles, typeFiles) .pipe($.typescript( tsProject, undefined, gr.tscReporterFactory({ errorTexts: errorTexts, onFinish: function() { gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); } }) )); if (declaration) { return merge([ compiled.dts.pipe(gulp.dest('./build')), compiled.js.pipe(gulp.dest('./build')) ]) } else { return compiled.pipe(gulp.dest('./build')); } }; }; var mochaParams = { reporter: 'spec' }; exports.taskUtilsTest = function() { return function() { return gulp.src('./build/utils/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe($.mocha(mochaParams)); }; }; exports.taskModelsTest = function() { return function() { return gulp.src('./build/models/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe($.mocha(mochaParams)); }; }; exports.taskClientTest = function() { return function() { return gulp.src('./build/client/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe($.mocha(mochaParams)); }; }; exports.taskServerTest = function() { return function() { return gulp.src('./build/server/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe(mocha(mochaParams)); }; }; function webpackCompilerFactory(opt) { opt = opt || {}; var cwd = process.cwd(); var files = fs.readdirSync(path.join(cwd, '/build/client')); var entryFiles = files.filter(function(file) { return /-entry\.js$/.test(file) }); if (!entryFiles.length) return null; var entry = {}; entryFiles.forEach(function(entryFile) { entry[entryFile.substr(0, entryFile.length - 9)] = './build/client/' + entryFile; }); //{ // pivot: './build/client/pivot-entry.js' //} return webpack({ context: cwd, entry: entry, target: opt.target || 'web', output: { path: path.join(cwd, "/build/public"), filename: "[name].js", chunkFilename: "[name].[hash].js" }, resolveLoader: { root: path.join(__dirname, "node_modules") }, module: { loaders: [ { test: /\.svg$/, loaders: ['raw-loader', 'svgo-loader?useConfig=svgoConfig1'] }, { test: /\.css$/, loaders: ['style-loader', 'css-loader'] } ] }, svgoConfig1: { plugins: [ // https://github.com/svg/svgo { removeTitle: true }, { removeDimensions: true }, { convertColors: { shorthex: false } }, { convertPathData: false } ] } }); } function webpackResultHandler(showStats, err, stats) { var errorTexts = []; if (err) { errorTexts.push('Fatal webpack error: ' + err.message); } else { var jsonStats = stats.toJson(); if(jsonStats.errors.length > 0 || jsonStats.warnings.length > 0) { errorTexts = jsonStats.errors.concat(jsonStats.warnings); } if (showStats || globalShowStats) { $.util.log("[webpack]", stats.toString({ colors: true })); } } if (errorTexts.length) console.error(errorTexts.join('\n')); gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); } exports.taskClientPack = function(opt) { opt = opt || {}; var showStats = opt.showStats; return function(callback) { var webpackCompiler = webpackCompilerFactory(opt); if (!webpackCompiler) return callback(); webpackCompiler.run(function(err, stats) { webpackResultHandler(showStats, err, stats); callback(); }); }; }; exports.clientPackWatch = function(opt) { opt = opt || {}; var showStats = opt.showStats; var webpackCompiler = webpackCompilerFactory(opt); if (!webpackCompiler) throw new Error('no entry files found'); webpackCompiler.watch({ // watch options: aggregateTimeout: 300 // wait so long for more changes //poll: true // use polling instead of native watchers }, function(err, stats) { webpackResultHandler(showStats, err, stats); $.util.log("[webpack]", 'done'); }); }; exports.taskClean = function() { return function() { del.sync(['./build/**']) } };
laborer.js
'use strict'; var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var autoprefixer = require('autoprefixer'); var merge = require('merge-stream'); var del = require('del'); var typescript = require('typescript'); var tsLintConfig = require('./tslint-rules'); var sassLintRules = require('./sasslint-rules'); var gr = require('./gulp-reporters'); var webpack = require("webpack"); // Modifiers ============== var globalShowStats = false; exports.showStats = function() { globalShowStats = true; }; exports.hideStats = function() { globalShowStats = false; }; var globalFailOnError = false; exports.failOnError = function() { globalFailOnError = true; }; // TASKS ============== exports.taskStyle = function(opt) { opt = opt || {}; var rules = opt.rules || sassLintRules; return function() { var errorTexts = []; return gulp.src('./src/client/**/*.scss') .pipe($.sassLint({ rules: rules })) .pipe(gr.sassLintReporterFactory({ errorTexts: errorTexts })) .pipe($.sass({ outputStyle: 'compressed' }).on('error', gr.sassErrorFactory({ errorTexts: errorTexts }))) .pipe($.postcss([ autoprefixer({ browsers: ['> 1%', 'last 3 versions', 'Firefox ESR', 'Opera 12.1'], remove: false // If you have no legacy code, this option will make Autoprefixer about 10% faster. }) ])) .pipe(gulp.dest('./build/client')) .on('finish', function() { gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); }); }; }; exports.taskIcons = function() { return function() { return gulp.src('./src/client/**/*.svg') // Just copy for now .pipe(gulp.dest('./build/client')) }; }; exports.taskHtml = function() { return function() { return gulp.src('./src/client/**/*.html') // Just copy for now .pipe(gulp.dest('./build/client')) }; }; exports.taskClientTypeScript = function(opt) { opt = opt || {}; var declaration = opt.declaration || false; var tsProject = $.typescript.createProject({ typescript: typescript, noImplicitAny: true, noFallthroughCasesInSwitch: true, noImplicitReturns: true, noEmitOnError: true, target: 'ES5', module: 'commonjs', declaration: declaration, jsx: 'react' }); return function() { var errorTexts = []; function fixPath(str) { return str.replace('/build/tmp/', '/src/'); } var sourceFiles = gulp.src(['./src/{client,common}/**/*.{ts,tsx}']) .pipe($.cached('client')) .pipe($.tslint({configuration: tsLintConfig})) .pipe($.tslint.report( gr.tscLintReporterFactory({ errorTexts: errorTexts, fixPath: fixPath }), { emitError: false } )); var typeFiles = gulp.src(['./typings/**/*.d.ts']); var compiled = merge(sourceFiles, typeFiles) .pipe($.typescript( tsProject, undefined, gr.tscReporterFactory({ errorTexts: errorTexts, fixPath: fixPath, onFinish: function() { gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); } }) )); if (declaration) { return merge([ compiled.dts.pipe(gulp.dest('./build')), compiled.js.pipe(gulp.dest('./build')) ]) } else { return compiled.pipe(gulp.dest('./build')); } }; }; exports.taskServerTypeScript = function(opt) { opt = opt || {}; var declaration = opt.declaration || false; var tsProject = $.typescript.createProject({ typescript: typescript, noImplicitAny: true, noFallthroughCasesInSwitch: true, noImplicitReturns: true, noEmitOnError: true, target: 'ES5', module: 'commonjs', declaration: declaration }); return function() { var errorTexts = []; var sourceFiles = gulp.src(['./src/{server,common}/**/*.ts']) .pipe($.cached('server')) .pipe($.tslint({configuration: tsLintConfig})) .pipe($.tslint.report( gr.tscLintReporterFactory({ errorTexts: errorTexts }), { emitError: false } )); var typeFiles = gulp.src(['./typings/**/*.d.ts']); var compiled = merge(sourceFiles, typeFiles) .pipe($.typescript( tsProject, undefined, gr.tscReporterFactory({ errorTexts: errorTexts, onFinish: function() { gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); } }) )); if (declaration) { return merge([ compiled.dts.pipe(gulp.dest('./build')), compiled.js.pipe(gulp.dest('./build')) ]) } else { return compiled.pipe(gulp.dest('./build')); } }; }; var mochaParams = { reporter: 'spec' }; exports.taskUtilsTest = function() { return function() { return gulp.src('./build/utils/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe(mocha(mochaParams)); }; }; exports.taskModelsTest = function() { return function() { return gulp.src('./build/models/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe(mocha(mochaParams)); }; }; exports.taskClientTest = function() { return function() { return gulp.src('./build/client/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe(mocha(mochaParams)); }; }; exports.taskServerTest = function() { return function() { return gulp.src('./build/server/**/*.mocha.js', {read: false}) // gulp-mocha needs filepaths so you can't have any plugins before it .pipe(mocha(mochaParams)); }; }; function webpackCompilerFactory(opt) { opt = opt || {}; var cwd = process.cwd(); var files = fs.readdirSync(path.join(cwd, '/build/client')); var entryFiles = files.filter(function(file) { return /-entry\.js$/.test(file) }); if (!entryFiles.length) return null; var entry = {}; entryFiles.forEach(function(entryFile) { entry[entryFile.substr(0, entryFile.length - 9)] = './build/client/' + entryFile; }); //{ // pivot: './build/client/pivot-entry.js' //} return webpack({ context: cwd, entry: entry, target: opt.target || 'web', output: { path: path.join(cwd, "/build/public"), filename: "[name].js", chunkFilename: "[name].[hash].js" }, resolveLoader: { root: path.join(__dirname, "node_modules") }, module: { loaders: [ { test: /\.svg$/, loaders: ['raw-loader', 'svgo-loader?useConfig=svgoConfig1'] }, { test: /\.css$/, loaders: ['style-loader', 'css-loader'] } ] }, svgoConfig1: { plugins: [ // https://github.com/svg/svgo { removeTitle: true }, { removeDimensions: true }, { convertColors: { shorthex: false } }, { convertPathData: false } ] } }); } function webpackResultHandler(showStats, err, stats) { var errorTexts = []; if (err) { errorTexts.push('Fatal webpack error: ' + err.message); } else { var jsonStats = stats.toJson(); if(jsonStats.errors.length > 0 || jsonStats.warnings.length > 0) { errorTexts = jsonStats.errors.concat(jsonStats.warnings); } if (showStats || globalShowStats) { $.util.log("[webpack]", stats.toString({ colors: true })); } } if (errorTexts.length) console.error(errorTexts.join('\n')); gr.writeErrors('./webstorm/errors', errorTexts); if (globalFailOnError && errorTexts.length) process.exit(1); } exports.taskClientPack = function(opt) { opt = opt || {}; var showStats = opt.showStats; return function(callback) { var webpackCompiler = webpackCompilerFactory(opt); if (!webpackCompiler) return callback(); webpackCompiler.run(function(err, stats) { webpackResultHandler(showStats, err, stats); callback(); }); }; }; exports.clientPackWatch = function(opt) { opt = opt || {}; var showStats = opt.showStats; var webpackCompiler = webpackCompilerFactory(opt); if (!webpackCompiler) throw new Error('no entry files found'); webpackCompiler.watch({ // watch options: aggregateTimeout: 300 // wait so long for more changes //poll: true // use polling instead of native watchers }, function(err, stats) { webpackResultHandler(showStats, err, stats); $.util.log("[webpack]", 'done'); }); }; exports.taskClean = function() { return function() { del.sync(['./build/**']) } };
Fixed missing $
laborer.js
Fixed missing $
<ide><path>aborer.js <ide> return function() { <ide> return gulp.src('./build/utils/**/*.mocha.js', {read: false}) <ide> // gulp-mocha needs filepaths so you can't have any plugins before it <del> .pipe(mocha(mochaParams)); <add> .pipe($.mocha(mochaParams)); <ide> }; <ide> }; <ide> <ide> return function() { <ide> return gulp.src('./build/models/**/*.mocha.js', {read: false}) <ide> // gulp-mocha needs filepaths so you can't have any plugins before it <del> .pipe(mocha(mochaParams)); <add> .pipe($.mocha(mochaParams)); <ide> }; <ide> }; <ide> <ide> return function() { <ide> return gulp.src('./build/client/**/*.mocha.js', {read: false}) <ide> // gulp-mocha needs filepaths so you can't have any plugins before it <del> .pipe(mocha(mochaParams)); <add> .pipe($.mocha(mochaParams)); <ide> }; <ide> }; <ide>
Java
apache-2.0
0a3c2e19db7e6b6dd33fcbbcb6c3c10096907691
0
hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,Whiley/WhileyCompiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler
// Copyright (c) 2011, David J. Pearce (David J. [email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyil.lang; import java.util.*; import wyil.util.*; /** * Represents a WYIL bytecode. The Whiley Intermediate Language (WYIL) employs * stack-based bytecodes, similar to the Java Virtual Machine. The frame of each * function/method consists of zero or more <i>local variables</i> (a.k.a * registers) and a <i>stack of unbounded depth</i>. Bytecodes may push/pop * values from the stack, and store/load them from local variables. Like Java * bytecode, WYIL uses unstructured control-flow and allows variables to take on * different types at different points. For example: * * <pre> * int sum([int] data): * r = 0 * for item in data: * r = r + item * return r * </pre> * * This function is compiled into the following WYIL bytecode: * * <pre> * int sum([int] data): * body: * var r, $2, item * const 0 : int * store r : int * move data : [int] * forall item [r] : [int] * move r : int * load item : int * add : int * store r : int * move r : int * return : int * </pre> * * Here, we can see that every bytecode is associated with one (or more) types. * These types are inferred by the compiler during type propagation. * * @author David J. Pearce * */ public abstract class Code { public final static int THIS_SLOT = 0; // =============================================================== // Bytecode Constructors // =============================================================== /** * Construct an <code>assert</code> bytecode which identifies a sequence of * bytecodes which represent a runtime assertion. * * @param label * --- end of block. * @return */ public static Assert Assert(String label) { return get(new Assert(label)); } public static BinOp BinOp(Type type, BOp op) { return get(new BinOp(type,op)); } /** * Construct a <code>const</code> bytecode which loads a given constant * onto the stack. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Const Const(Value constant) { return get(new Const(constant)); } public static Convert Convert(Type from, Type to) { return get(new Convert(from,to)); } public static final Debug debug = new Debug(); public static Destructure Destructure(Type from) { return get(new Destructure(from)); } public static DictLength DictLength(Type.Dictionary type) { return get(new DictLength(type)); } /** * Construct a <code>dictload</code> bytecode which reads the value * associated with a given key in a dictionary. * * @param type * --- dictionary type. * @return */ public static DictLoad DictLoad(Type.Dictionary type) { return get(new DictLoad(type)); } public static LoopEnd End(String label) { return get(new LoopEnd(label)); } /** * Construct a <code>fail</code> bytecode which indicates a runtime failure. * * @param label * --- end of block. * @return */ public static Fail Fail(String label) { return get(new Fail(label)); } /** * Construct a <code>fieldload</code> bytecode which reads a given field * from a record of a given type. * * @param type * --- record type. * @param field * --- field to load. * @return */ public static FieldLoad FieldLoad(Type.Record type, String field) { return get(new FieldLoad(type,field)); } /** * Construct a <code>goto</code> bytecode which branches unconditionally to * a given label. * * @param label * --- destination label. * @return */ public static Goto Goto(String label) { return get(new Goto(label)); } /** * Construct an <code>invoke</code> bytecode which invokes a method. * * @param label * --- destination label. * @return */ public static Invoke Invoke(Type.Function fun, NameID name, boolean retval) { return get(new Invoke(fun,name,retval)); } public static Not Not() { return get(new Not()); } /** * Construct a <code>load</code> bytecode which pushes a given register onto * the stack. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Load Load(Type type, int reg) { return get(new Load(type,reg)); } public static ListLength ListLength(Type.List type) { return get(new ListLength(type)); } /** * Construct a <code>move</code> bytecode which moves a given register onto * the stack. The register contents of the register are voided after this * operation. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Move Move(Type type, int reg) { return get(new Move(type,reg)); } public static SubList SubList(Type.List type) { return get(new SubList(type)); } public static ListAppend ListAppend(Type.List type, OpDir dir) { return get(new ListAppend(type,dir)); } /** * Construct a <code>listload</code> bytecode which reads a value from a * given index in a given list. * * @param type * --- list type. * @return */ public static ListLoad ListLoad(Type.List type) { return get(new ListLoad(type)); } /** * Construct a <code>loop</code> bytecode which iterates the sequence of * bytecodes upto the exit label. * * @param label * --- exit label. * @return */ public static Loop Loop(String label, Collection<Integer> modifies) { return get(new Loop(label,modifies)); } /** * Construct a <code>forall</code> bytecode which iterates over a given * source collection stored on top of the stack. The supplied variable * <code>var</code> is used as the iterator. The exit label denotes the end * of the loop block. * * * @param label * --- exit label. * @return */ public static ForAll ForAll(Type type, int var, String label, Collection<Integer> modifies) { return get(new ForAll(type, var, label, modifies)); } /** * Construct a <code>newdict</code> bytecode which constructs a new dictionary * and puts it on the stack. * * @param type * @return */ public static NewDict NewDict(Type.Dictionary type, int nargs) { return get(new NewDict(type,nargs)); } /** * Construct a <code>newset</code> bytecode which constructs a new set * and puts it on the stack. * * @param type * @return */ public static NewSet NewSet(Type.Set type, int nargs) { return get(new NewSet(type,nargs)); } /** * Construct a <code>newlist</code> bytecode which constructs a new list * and puts it on the stack. * * @param type * @return */ public static NewList NewList(Type.List type, int nargs) { return get(new NewList(type,nargs)); } /** * Construct a <code>newtuple</code> bytecode which constructs a new tuple * and puts it on the stack. * * @param type * @return */ public static NewTuple NewTuple(Type.Tuple type, int nargs) { return get(new NewTuple(type, nargs)); } /** * Construct a <code>newrecord</code> bytecode which constructs a new record * and puts it on the stack. * * @param type * @return */ public static NewRecord NewRecord(Type.Record type) { return get(new NewRecord(type)); } public static Return Return(Type t) { return get(new Return(t)); } public static IfGoto IfGoto(Type type, COp cop, String label) { return get(new IfGoto(type,cop,label)); } public static IfType IfType(Type type, int slot, Type test, String label) { return get(new IfType(type,slot,test,label)); } /** * Construct an <code>indirectsend</code> bytecode which sends an indirect * message to an actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static IndirectSend IndirectSend(Type.Method meth, boolean synchronous, boolean retval) { return get(new IndirectSend(meth,synchronous,retval)); } /** * Construct an <code>indirectinvoke</code> bytecode which sends an indirect * message to an actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static IndirectInvoke IndirectInvoke(Type.Function fun, boolean retval) { return get(new IndirectInvoke(fun,retval)); } public static Invert Invert(Type type) { return get(new Invert(type)); } public static Label Label(String label) { return get(new Label(label)); } public static final Skip Skip = new Skip(); public static SetLength SetLength(Type.Set type) { return get(new SetLength(type)); } public static SetUnion SetUnion(Type.Set type, OpDir dir) { return get(new SetUnion(type,dir)); } public static SetIntersect SetIntersect(Type.Set type, OpDir dir) { return get(new SetIntersect(type,dir)); } public static SetDifference SetDifference(Type.Set type, OpDir dir) { return get(new SetDifference(type,dir)); } public static StringAppend StringAppend(OpDir dir) { return get(new StringAppend(dir)); } public static SubString SubString() { return get(new SubString()); } public static StringLength StringLength() { return get(new StringLength()); } public static StringLoad StringLoad() { return get(new StringLoad()); } /** * Construct an <code>send</code> bytecode which sends a message to an * actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static Send Send(Type.Method meth, NameID name, boolean synchronous, boolean retval) { return get(new Send(meth,name,synchronous,retval)); } /** * Construct a <code>store</code> bytecode which writes a given register. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Store Store(Type type, int reg) { return get(new Store(type,reg)); } /** * Construct a <code>switch</code> bytecode which pops a value off the * stack, and switches to a given label based on it. * * @param type * --- value type to switch on. * @param defaultLabel * --- target for the default case. * @param cases * --- map from values to destination labels. * @return */ public static Switch Switch(Type type, String defaultLabel, Collection<Pair<Value, String>> cases) { return get(new Switch(type,defaultLabel,cases)); } /** * Construct a <code>throw</code> bytecode which pops a value off the * stack and throws it. * * @param afterType * --- value type to throw * @return */ public static Throw Throw(Type t) { return get(new Throw(t)); } /** * Construct a <code>trycatch</code> bytecode which defines a region of * bytecodes which are covered by one or more catch handles. * * @param target * --- identifies end-of-block label. * @param catches * --- map from types to destination labels. * @return */ public static TryCatch TryCatch(String target, Collection<Pair<Type, String>> catches) { return get(new TryCatch(target, catches)); } public static TryEnd TryEnd(String label) { return get(new TryEnd(label)); } /** * Construct a <code>tupleload</code> bytecode which reads the value * at a given index in a tuple * * @param type * --- dictionary type. * @return */ public static TupleLoad TupleLoad(Type.Tuple type, int index) { return get(new TupleLoad(type,index)); } public static Negate Negate(Type type) { return get(new Negate(type)); } public static Spawn Spawn(Type.Process type) { return get(new Spawn(type)); } public static ProcLoad ProcLoad(Type.Process type) { return get(new ProcLoad(type)); } /** * Construct a <code>update</code> bytecode which writes a value into a * compound structure, as determined by a given access path. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Update Update(Type beforeType, Type afterType, int slot, int level, Collection<String> fields) { return get(new Update(beforeType, afterType, slot, level, fields)); } public static Void Void(Type type, int slot) { return get(new Void(type,slot)); } // =============================================================== // Abstract Methods // =============================================================== // The following method adds any slots used by a given bytecode public void slots(Set<Integer> slots) { // default implementation does nothing } /** * The remap method remaps all slots according to a given binding. Slots not * mentioned in the binding retain their original value. * * @param binding * @return */ public Code remap(Map<Integer,Integer> binding) { return this; } /** * Relabel all labels according to the given map. * * @param labels * @return */ public Code relabel(Map<String,String> labels) { return this; } // =============================================================== // Bytecode Implementations // =============================================================== /** * Indicates the start of a code block representing an assertion. This * includes assertions arising from type invariants, as well as * method/function pre- and post-conditions. The target identifies the label * terminating this block. */ public static final class Assert extends Code { public final String target; private Assert(String target) { this.target = target; } public Assert relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return Assert(nlabel); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Assert) { return target.equals(((Assert)o).target); } return false; } public String toString() { return "assert " + target; } } /** * Represents a binary operator (e.g. '+','-',etc) that is provided to a * <code>BinOp</code> bytecode. * * @author David J. Pearce * */ public enum BOp { ADD{ public String toString() { return "add"; } }, SUB{ public String toString() { return "sub"; } }, MUL{ public String toString() { return "mul"; } }, DIV{ public String toString() { return "div"; } }, REM{ public String toString() { return "rem"; } }, RANGE{ public String toString() { return "range"; } }, BITWISEOR{ public String toString() { return "or"; } }, BITWISEXOR{ public String toString() { return "xor"; } }, BITWISEAND{ public String toString() { return "and"; } }, LEFTSHIFT{ public String toString() { return "shl"; } }, RIGHTSHIFT{ public String toString() { return "shr"; } }, }; /** * <p> * A binary operation takes two items off the stack and pushes a single * result. The binary operators are: * </p> * <ul> * <li><i>add, subtract, multiply, divide, remainder</i>. Both operands must * be either integers or reals (but not one or the other). A value of the * same type is produced.</li> * <li><i>range</i></li> * <li><i>bitwiseor, bitwisexor, bitwiseand</i></li> * <li><i>leftshift,rightshift</i></li> * </ul> * * @author David J. Pearce * */ public static final class BinOp extends Code { public final BOp bop; public final Type type; private BinOp(Type type, BOp bop) { if(bop == null) { throw new IllegalArgumentException("BinOp bop argument cannot be null"); } this.bop = bop; this.type = type; } public int hashCode() { if(type == null) { return bop.hashCode(); } else { return type.hashCode() + bop.hashCode(); } } public boolean equals(Object o) { if(o instanceof BinOp) { BinOp bo = (BinOp) o; return (type == bo.type || (type != null && type .equals(bo.type))) && bop.equals(bo.bop); } return false; } public String toString() { return toString(bop.toString(),type); } } /** * <p> * Pops a value from the stack, converts it to a given type and pushes it * back on. This bytecode is the only way to change the type of a value. * It's purpose is to simplify implementations which have different * representations of data types. * </p> * * <p> * In many cases, this bytecode may correspond to a nop on the hardware. * Consider converting from <code>[any]</code> to <code>any</code>. On the * JVM, <code>any</code> translates to <code>Object</code>, whilst * <code>[any]</code> translates to <code>List</code> (which is an instance * of <code>Object</code>). Thus, no conversion is necessary since * <code>List</code> can safely flow into <code>Object</code>. * </p> * * <p> * A convert bytecode must be inserted whenever the type of a register * changes. This includes at control-flow meet points, when the value is * passed as a parameter, assigned to a field, etc. * </p> */ public static final class Convert extends Code { public final Type from; public final Type to; private Convert(Type from, Type to) { if(to == null) { throw new IllegalArgumentException("Convert to argument cannot be null"); } this.from = from; this.to = to; } public int hashCode() { if(from == null) { return to.hashCode(); } else { return from.hashCode() + to.hashCode(); } } public boolean equals(Object o) { if(o instanceof Convert) { Convert c = (Convert) o; return (from == c.from || (from != null && from.equals(c.from))) && to.equals(c.to); } return false; } public String toString() { return "convert " + from + " to " + to; } } /** * Pushes a constant value onto the stack. This includes integer constants, * rational constants, list constants, set constants, dictionary constants, * function constants, etc. * * @author David J. Pearce * */ public static final class Const extends Code { public final Value constant; private Const(Value constant) { this.constant = constant; } public int hashCode() { return constant.hashCode(); } public boolean equals(Object o) { if(o instanceof Const) { Const c = (Const) o; return constant.equals(c.constant); } return false; } public String toString() { return toString("const " + constant,constant.type()); } } /** * Pops a string from the stack and writes it to the debug console. This * bytecode is not intended to form part of the programs operation. Rather, * it is to facilitate debugging within functions (since they cannot have * side-effects). Furthermore, if debugging is disabled, this bytecode is a * nop. * * @author David J. Pearce * */ public static final class Debug extends Code { Debug() {} public int hashCode() { return 101; } public boolean equals(Object o) { return o instanceof Debug; } public String toString() { return "debug"; } } /** * Pops a compound value from the stack "destructures" it into multiple * values which are pushed back on the stack. For example, a rational can be * destructured into two integers (the <i>numerator</i> and * <i>denominator</i>). Or, an n-tuple can be destructured into n values. * * Probably should be deprecated in favour of tupeload bytecode. */ public static final class Destructure extends Code { public final Type type; private Destructure(Type from) { this.type = from; } public int hashCode() { if(type == null) { return 12345; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Destructure) { Destructure c = (Destructure) o; return (type == c.type || (type != null && type.equals(c.type))); } return false; } public String toString() { return "destructure " + type; } } /** * Pops a dictionary value from stack, and pushes it's length back on. * * @author David J. Pearce * */ public static final class DictLength extends Code { public final Type.Dictionary type; private DictLength(Type.Dictionary type) { this.type = type; } public int hashCode() { if(type == null) { return 558723; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof DictLength) { DictLength setop = (DictLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("dictlength",type); } } /** * Pops a key and dictionary from the stack, and looks up the value for that * key in the dictionary. If no value exists, a dictionary fault is raised. * Otherwise, the value is pushed onto the stack. * * @author David J. Pearce * */ public static final class DictLoad extends Code { public final Type.Dictionary type; private DictLoad(Type.Dictionary type) { this.type = type; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof DictLoad) { DictLoad i = (DictLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("dictload",type); } } /** * Marks the end of a loop block. * @author David J. Pearce * */ public static final class LoopEnd extends Label { LoopEnd(String label) { super(label); } public LoopEnd relabel(Map<String,String> labels) { String nlabel = labels.get(label); if(nlabel == null) { return this; } else { return End(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if(o instanceof LoopEnd) { LoopEnd e = (LoopEnd) o; return e.label.equals(label); } return false; } public String toString() { return "end " + label; } } /** * Raises an assertion failure fault with the given message. Fail bytecodes * may only appear within assertion blocks. * * @author David J. Pearce * */ public static final class Fail extends Code { public final String msg; private Fail(String msg) { this.msg = msg; } public int hashCode() { return msg.hashCode(); } public boolean equals(Object o) { if(o instanceof Fail) { return msg.equals(((Fail)o).msg); } return false; } public String toString() { return "fail \"" + msg + "\""; } } /** * Pops a record from the stack and pushes the value from the given * field back on. * * @author David J. Pearce * */ public static final class FieldLoad extends Code { public final Type.Record type; public final String field; private FieldLoad(Type.Record type, String field) { if (field == null) { throw new IllegalArgumentException( "FieldLoad field argument cannot be null"); } this.type = type; this.field = field; } public int hashCode() { if(type != null) { return type.hashCode() + field.hashCode(); } else { return field.hashCode(); } } public Type fieldType() { return type.fields().get(field); } public boolean equals(Object o) { if(o instanceof FieldLoad) { FieldLoad i = (FieldLoad) o; return (i.type == type || (type != null && type.equals(i.type))) && field.equals(i.field); } return false; } public String toString() { return toString("fieldload " + field,type); } } /** * <p> * Branches unconditionally to the given label. * </p> * * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, a <code>goto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author David J. Pearce * */ public static final class Goto extends Code { public final String target; private Goto(String target) { this.target = target; } public Goto relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return Goto(nlabel); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Goto) { return target.equals(((Goto)o).target); } return false; } public String toString() { return "goto " + target; } } /** * <p> * Branches conditionally to the given label by popping two operands from * the stack and comparing them. The possible comparators are: * </p> * <ul> * <li><i>equals (eq) and not-equals (ne)</i>. Both operands must have the * given type.</li> * <li><i>less-than (lt), less-than-or-equals (le), greater-than (gt) and * great-than-or-equals (ge).</i> Both operands must have the given type, * which additionally must by either <code>char</code>, <code>int</code> or * <code>real</code>.</li> * <li><i>element of (in).</i> The second operand must be a set whose * element type is that of the first.</li> * <li><i>subset (ss) and subset-equals (sse)</i>. Both operands must have * the given type, which additionally must be a set.</li> * </ul> * * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>ifgoto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author David J. Pearce * */ public static final class IfGoto extends Code { public final Type type; public final COp op; public final String target; private IfGoto(Type type, COp op, String target) { if(op == null) { throw new IllegalArgumentException("IfGoto op argument cannot be null"); } if(target == null) { throw new IllegalArgumentException("IfGoto target argument cannot be null"); } this.type = type; this.op = op; this.target = target; } public IfGoto relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return IfGoto(type,op,nlabel); } } public int hashCode() { if(type == null) { return op.hashCode() + target.hashCode(); } else { return type.hashCode() + op.hashCode() + target.hashCode(); } } public boolean equals(Object o) { if(o instanceof IfGoto) { IfGoto ig = (IfGoto) o; return op == ig.op && target.equals(ig.target) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { return toString("if" + op + " goto " + target,type); } } /** * Represents a comparison operator (e.g. '==','!=',etc) that is provided to a * <code>IfGoto</code> bytecode. * * @author David J. Pearce * */ public enum COp { EQ() { public String toString() { return "eq"; } }, NEQ{ public String toString() { return "ne"; } }, LT{ public String toString() { return "lt"; } }, LTEQ{ public String toString() { return "le"; } }, GT{ public String toString() { return "gt"; } }, GTEQ{ public String toString() { return "ge"; } }, ELEMOF{ public String toString() { return "in"; } }, SUBSET{ public String toString() { return "sb"; } }, SUBSETEQ{ public String toString() { return "sbe"; } } }; /** * <p> * Branches conditionally to the given label based on the result of a * runtime type test against a given value. More specifically, it checks * whether the value is a subtype of the type test. The value in question is * either loaded directly from a register, or popped off the stack. * </p> * <p> * In the case that the value is obtained from a register, then that * variable is automatically <i>retyped</i> as a result of the type test. On * the true branch, its type is intersected with type test. On the false * branch, its type is intersected with the <i>negation</i> of the type * test. * </p> * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>iftype</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author David J. Pearce * */ public static final class IfType extends Code { public final Type type; public final int slot; public final Type test; public final String target; private IfType(Type type, int slot, Type test, String target) { if(test == null) { throw new IllegalArgumentException("IfGoto op argument cannot be null"); } if(target == null) { throw new IllegalArgumentException("IfGoto target argument cannot be null"); } this.type = type; this.slot = slot; this.test = test; this.target = target; } public IfType relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return IfType(type,slot,test,nlabel); } } public void slots(Set<Integer> slots) { if(slot >= 0) { slots.add(slot); } } public Code remap(Map<Integer, Integer> binding) { if (slot >= 0) { Integer nslot = binding.get(slot); if (nslot != null) { return Code.IfType(type, nslot, test, target); } } return this; } public int hashCode() { if(type == null) { return test.hashCode() + target.hashCode(); } else { return type.hashCode() + test.hashCode() + target.hashCode(); } } public boolean equals(Object o) { if(o instanceof IfType) { IfType ig = (IfType) o; return test.equals(ig.test) && slot == ig.slot && target.equals(ig.target) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { if(slot >= 0) { return toString("if " + slot + " is " + test + " goto " + target,type); } else { return toString("if " + test + " goto " + target,type); } } } /** * Represents an indirect function call. For example, consider the * following: * * <pre> * int function(int(int) f, int x): * return f(x) * </pre> * * Here, the function call <code>f(x)</code> is indirect as the called * function is determined by the variable <code>f</code>. * * @author David J. Pearce * */ public static final class IndirectInvoke extends Code { public final Type.Function type; public final boolean retval; private IndirectInvoke(Type.Function type, boolean retval) { this.type = type; this.retval = retval; } public int hashCode() { if(type != null) { return type.hashCode(); } else { return 123; } } public boolean equals(Object o) { if(o instanceof IndirectInvoke) { IndirectInvoke i = (IndirectInvoke) o; return retval == i.retval && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { if(retval) { return toString("indirectinvoke",type); } else { return toString("vindirectinvoke",type); } } } /** * Represents an indirect message send (either synchronous or asynchronous). * For example, consider the following: * * <pre> * int ::method(Rec::int(int) m, Rec r, int x): * return r.m(x) * </pre> * * Here, the message send <code>r.m(x)</code> is indirect as the message * sent is determined by the variable <code>m</code>. * * @author David J. Pearce * */ public static final class IndirectSend extends Code { public final boolean synchronous; public final boolean retval; public final Type.Method type; private IndirectSend(Type.Method type, boolean synchronous, boolean retval) { this.type = type; this.synchronous = synchronous; this.retval = retval; } public int hashCode() { if(type != null) { return type.hashCode(); } else { return 123; } } public boolean equals(Object o) { if(o instanceof IndirectSend) { IndirectSend i = (IndirectSend) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { if(synchronous) { if(retval) { return toString("isend",type); } else { return toString("ivsend",type); } } else { return toString("iasend",type); } } } public static final class Not extends Code { private Not() { } public int hashCode() { return 12875; } public boolean equals(Object o) { return o instanceof Not; } public String toString() { return toString("not",Type.T_BYTE); } } /** * Corresponds to a direct function call whose parameters are found on the * stack in the order corresponding to the function type. If a return value * is required, this is pushed onto the stack after the function call. * * @author David J. Pearce * */ public static final class Invoke extends Code { public final Type.Function type; public final NameID name; public final boolean retval; private Invoke(Type.Function type, NameID name, boolean retval) { this.type = type; this.name = name; this.retval = retval; } public int hashCode() { if(type == null) { return name.hashCode(); } else { return type.hashCode() + name.hashCode(); } } public boolean equals(Object o) { if (o instanceof Invoke) { Invoke i = (Invoke) o; return name.equals(i.name) && retval == i.retval && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { if(retval) { return toString("invoke " + name,type); } else { return toString("vinvoke " + name,type); } } } /** * Represents the labelled destination of a branch or loop statement. * * @author David J. Pearce * */ public static class Label extends Code { public final String label; private Label(String label) { this.label = label; } public Label relabel(Map<String,String> labels) { String nlabel = labels.get(label); if(nlabel == null) { return this; } else { return Label(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof Label) { return label.equals(((Label) o).label); } return false; } public String toString() { return "." + label; } } /** * Pops two lists from the stack, appends them together and pushes the * result back onto the stack. * * @author David J. Pearce * */ public static final class ListAppend extends Code { public final OpDir dir; public final Type.List type; private ListAppend(Type.List type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("ListAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof ListAppend) { ListAppend setop = (ListAppend) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("listappend" + dir.toString(),type); } } /** * Pops a list from the stack and pushes its length back on. * * @author David J. Pearce * */ public static final class ListLength extends Code { public final Type.List type; private ListLength(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 124987; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof ListLength) { ListLength setop = (ListLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("listlength",type); } } public static final class SubList extends Code { public final Type.List type; private SubList(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 124987; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof SubList) { SubList setop = (SubList) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("sublist",type); } } /** * Pops am integer index from the stack, followed by a list and pushes the * element at the given index back on. * * @author David J. Pearce * */ public static final class ListLoad extends Code { public final Type.List type; private ListLoad(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof ListLoad) { ListLoad i = (ListLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("listload",type); } } /** * Loads the contents of the given register onto the stack. * * @author David J. Pearce * */ public static final class Load extends Code { public final Type type; public final int slot; private Load(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Load(type, nslot); } else { return this; } } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Load) { Load i = (Load) o; return slot == i.slot && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { return toString("load " + slot,type); } } /** * Moves the contents of the given register onto the stack. This is similar * to a <code>load</code> bytecode, except that the register's contents are * "voided" afterwards. This guarantees that the register is no longer live, * which is useful for determining the live ranges of register in a * function or method. * * @author David J. Pearce * */ public static final class Move extends Code { public final Type type; public final int slot; private Move(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Move(type, nslot); } else { return this; } } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Move) { Move i = (Move) o; return slot == i.slot && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { return toString("move " + slot,type); } } public static class Loop extends Code { public final String target; public final HashSet<Integer> modifies; private Loop(String target, Collection<Integer> modifies) { this.target = target; this.modifies = new HashSet<Integer>(modifies); } public Loop relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return Loop(nlabel,modifies); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Loop) { Loop f = (Loop) o; return target.equals(f.target) && modifies.equals(f.modifies); } return false; } public String toString() { return "loop " + modifies; } } /** * Pops a set, list or dictionary from the stack and iterates over every * element it contains. An register is identified to hold the current value * being iterated over. * * @author David J. Pearce * */ public static final class ForAll extends Loop { public final int slot; public final Type type; private ForAll(Type type, int slot, String target, Collection<Integer> modifies) { super(target,modifies); this.type = type; this.slot = slot; } public ForAll relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return ForAll(type,slot,nlabel,modifies); } } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.ForAll(type, nslot, target, modifies); } else { return this; } } public int hashCode() { return super.hashCode() + slot; } public boolean equals(Object o) { if (o instanceof ForAll) { ForAll f = (ForAll) o; return target.equals(f.target) && (type == f.type || (type != null && type .equals(f.type))) && slot == f.slot && modifies.equals(f.modifies); } return false; } public String toString() { return toString("forall " + slot + " " + modifies,type); } } /** * Represents a type which may appear on the left of an assignment * expression. Lists, Dictionaries, Strings, Records and Processes are the * only valid types for an lval. * * @author David J. Pearce * */ public static abstract class LVal { protected Type type; public LVal(Type t) { this.type = t; } public Type rawType() { return type; } } /** * An LVal with dictionary type. * @author David J. Pearce * */ public static final class DictLVal extends LVal { public DictLVal(Type t) { super(t); if(Type.effectiveDictionaryType(t) == null) { throw new IllegalArgumentException("Invalid Dictionary Type"); } } public Type.Dictionary type() { return Type.effectiveDictionaryType(type); } } /** * An LVal with list type. * @author David J. Pearce * */ public static final class ListLVal extends LVal { public ListLVal(Type t) { super(t); if(Type.effectiveListType(t) == null) { throw new IllegalArgumentException("Invalid List Type"); } } public Type.List type() { return Type.effectiveListType(type); } } /** * An LVal with string type. * @author David J. Pearce * */ public static final class StringLVal extends LVal { public StringLVal() { super(Type.T_STRING); } } /** * An LVal with record type. * @author David J. Pearce * */ public static final class RecordLVal extends LVal { public final String field; public RecordLVal(Type t, String field) { super(t); this.field = field; Type.Record rt = Type.effectiveRecordType(t); if(rt == null || !rt.fields().containsKey(field)) { throw new IllegalArgumentException("Invalid Record Type"); } } public Type.Record type() { return Type.effectiveRecordType(type); } } private static final class UpdateIterator implements Iterator<LVal> { private final ArrayList<String> fields; private Type iter; private int fieldIndex; private int index; public UpdateIterator(Type type, int level, ArrayList<String> fields) { this.fields = fields; this.iter = type; this.index = level; // TODO: sort out this hack if(Type.isSubtype(Type.Process(Type.T_ANY), iter)) { Type.Process p = (Type.Process) iter; iter = p.element(); } } public LVal next() { Type raw = iter; index--; if(Type.isSubtype(Type.T_STRING,iter)) { iter = Type.T_CHAR; return new StringLVal(); } else if(Type.isSubtype(Type.List(Type.T_ANY,false),iter)) { Type.List list = Type.effectiveListType(iter); iter = list.element(); return new ListLVal(raw); } else if(Type.isSubtype(Type.Dictionary(Type.T_ANY, Type.T_ANY),iter)) { // this indicates a dictionary access, rather than a list access Type.Dictionary dict = Type.effectiveDictionaryType(iter); iter = dict.value(); return new DictLVal(raw); } else if(Type.effectiveRecordType(iter) != null) { Type.Record rec = Type.effectiveRecordType(iter); String field = fields.get(fieldIndex++); iter = rec.fields().get(field); return new RecordLVal(raw,field); } else { throw new IllegalArgumentException("Invalid type for Code.Update"); } } public boolean hasNext() { return index > 0; } public void remove() { throw new UnsupportedOperationException("UpdateIterator is unmodifiable"); } } /** * <p> * Pops a compound structure, zero or more indices and a value from the * stack and updates the compound structure with the given value. Valid * compound structures are lists, dictionaries, strings, records and * processes. * </p> * <p> * Ideally, this operation is done in-place, meaning the operation is * constant time. However, to support Whiley's value semantics this bytecode * may require (in some cases) a clone of the underlying data-structure. * Thus, the worst-case runtime of this operation is linear in the size of * the compound structure. * </p> * * @author David J. Pearce * */ public static final class Update extends Code implements Iterable<LVal> { public final Type beforeType; public final Type afterType; public final int level; public final int slot; public final ArrayList<String> fields; private Update(Type beforeType, Type afterType, int slot, int level, Collection<String> fields) { if (fields == null) { throw new IllegalArgumentException( "FieldStore fields argument cannot be null"); } this.beforeType = beforeType; this.afterType = afterType; this.slot = slot; this.level = level; this.fields = new ArrayList<String>(fields); } public void slots(Set<Integer> slots) { slots.add(slot); } public Iterator<LVal> iterator() { return new UpdateIterator(afterType,level,fields); } /** * Extract the type for the right-hand side of this assignment. * @return */ public Type rhs() { Type iter = afterType; // TODO: sort out this hack if (Type.isSubtype(Type.Process(Type.T_ANY), iter)) { Type.Process p = (Type.Process) iter; iter = p.element(); } int fieldIndex = 0; for (int i = 0; i != level; ++i) { if (Type.isSubtype(Type.T_STRING, iter)) { iter = Type.T_CHAR; } else if (Type.isSubtype(Type.List(Type.T_ANY,false), iter)) { Type.List list = Type.effectiveListType(iter); iter = list.element(); } else if (Type.isSubtype( Type.Dictionary(Type.T_ANY, Type.T_ANY), iter)) { // this indicates a dictionary access, rather than a list // access Type.Dictionary dict = Type.effectiveDictionaryType(iter); iter = dict.value(); } else if (Type.effectiveRecordType(iter) != null) { Type.Record rec = Type.effectiveRecordType(iter); String field = fields.get(fieldIndex++); iter = rec.fields().get(field); } else { throw new IllegalArgumentException( "Invalid type for Code.Update"); } } return iter; } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Update(beforeType, afterType, nslot, level, fields); } else { return this; } } public int hashCode() { if(afterType == null) { return level + fields.hashCode(); } else { return afterType.hashCode() + slot + level + fields.hashCode(); } } public boolean equals(Object o) { if (o instanceof Update) { Update i = (Update) o; return (i.beforeType == beforeType || (beforeType != null && beforeType .equals(i.beforeType))) && (i.afterType == afterType || (afterType != null && afterType .equals(i.afterType))) && level == i.level && slot == i.slot && fields.equals(i.fields); } return false; } public String toString() { String fs = fields.isEmpty() ? "" : " "; boolean firstTime=true; for(String f : fields) { if(!firstTime) { fs += "."; } firstTime=false; fs += f; } return toString("update " + slot + " #" + level + fs,beforeType,afterType); } } /** * Constructs a new dictionary value from zero or more key-value pairs on * the stack. For each pair, the key must occur directly before the value on * the stack. For example: * * <pre> * const 1 : int * const "Hello" : string * const 2 : int * const "World" : string * newdict #2 : {int->string} * </pre> * * Pushes the dictionary value <code>{1->"Hello",2->"World"}</code> onto the * stack. * * @author David J. Pearce * */ public static final class NewDict extends Code { public final Type.Dictionary type; public final int nargs; private NewDict(Type.Dictionary type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode() + nargs; } } public boolean equals(Object o) { if(o instanceof NewDict) { NewDict i = (NewDict) o; return (type == i.type || (type != null && type.equals(i.type))) && nargs == i.nargs; } return false; } public String toString() { return toString("newdict #" + nargs,type); } } /** * Constructs a new record value from zero or more values on the stack. Each * value is associated with a field name, and will be popped from the stack * in the reverse order. For example: * * <pre> * const 1 : int * const 2 : int * newrec : {int x,int y} * </pre> * * Pushes the record value <code>{x:1,y:2}</code> onto the stack. * * @author David J. Pearce * */ public static final class NewRecord extends Code { public final Type.Record type; private NewRecord(Type.Record type) { this.type = type; } public int hashCode() { if(type == null) { return 952; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewRecord) { NewRecord i = (NewRecord) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("newrec",type); } } /** * Constructs a new tuple value from two or more values on the stack. Values * are popped from the stack in the reverse order they occur in the tuple. * For example: * * <pre> * const 1 : int * const 2 : int * newtuple #2 : (int,int) * </pre> * * Pushes the tuple value <code>(1,2)</code> onto the stack. * * @author David J. Pearce * */ public static final class NewTuple extends Code { public final Type.Tuple type; public final int nargs; private NewTuple(Type.Tuple type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode() + nargs; } } public boolean equals(Object o) { if(o instanceof NewTuple) { NewTuple i = (NewTuple) o; return nargs == i.nargs && (type == i.type || (type != null && type.equals(i.type))); } return false; } public String toString() { return toString("newtuple #" + nargs,type); } } /** * Constructs a new set value from zero or more values on the stack. The new * set is load onto the stack. For example: * * <pre> * const 1 : int * const 2 : int * const 3 : int * newset #3 : {int} * </pre> * * Pushes the set value <code>{1,2,3}</code> onto the stack. * * @author David J. Pearce * */ public static final class NewSet extends Code { public final Type.Set type; public final int nargs; private NewSet(Type.Set type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewSet) { NewSet i = (NewSet) o; return type == i.type || (type != null && type.equals(i.type)) && nargs == i.nargs; } return false; } public String toString() { return toString("newset #" + nargs,type); } } /** * Constructs a new list value from zero or more values on the stack. The * values are popped from the stack in the reverse order they will occur in * the new list. The new list is load onto the stack. For example: * * <pre> * const 1 : int * const 2 : int * const 3 : int * newlist #3 : [int] * </pre> * * Pushes the list value <code>[1,2,3]</code> onto the stack. * * @author David J. Pearce * */ public static final class NewList extends Code { public final Type.List type; public final int nargs; private NewList(Type.List type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewList) { NewList i = (NewList) o; return type == i.type || (type != null && type.equals(i.type)) && nargs == i.nargs; } return false; } public String toString() { return toString("newlist #" + nargs,type); } } public static final class Nop extends Code { private Nop() {} public String toString() { return "nop"; } } public static final class Return extends Code { public final Type type; private Return(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 996; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Return) { Return i = (Return) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("return",type); } } public enum OpDir { UNIFORM { public String toString() { return ""; } }, LEFT { public String toString() { return "_l"; } }, RIGHT { public String toString() { return "_r"; } } } public static final class SetUnion extends Code { public final OpDir dir; public final Type.Set type; private SetUnion(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetUnion) { SetUnion setop = (SetUnion) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("union" + dir.toString(),type); } } public static final class SetIntersect extends Code { public final OpDir dir; public final Type.Set type; private SetIntersect(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetIntersect) { SetIntersect setop = (SetIntersect) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("intersect" + dir.toString(),type); } } public static final class SetDifference extends Code { public final OpDir dir; public final Type.Set type; private SetDifference(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetDifference) { SetDifference setop = (SetDifference) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("difference" + dir.toString(),type); } } public static final class SetLength extends Code { public final Type.Set type; private SetLength(Type.Set type) { this.type = type; } public int hashCode() { if(type == null) { return 558723; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetLength) { SetLength setop = (SetLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("setlength",type); } } public static final class StringAppend extends Code { public final OpDir dir; private StringAppend(OpDir dir) { if(dir == null) { throw new IllegalArgumentException("StringAppend direction cannot be null"); } this.dir = dir; } public int hashCode() { return dir.hashCode(); } public boolean equals(Object o) { if (o instanceof StringAppend) { StringAppend setop = (StringAppend) o; return dir.equals(setop.dir); } return false; } public String toString() { return toString("stringappend" + dir.toString(),Type.T_STRING); } } public static final class SubString extends Code { private SubString() { } public int hashCode() { return 983745; } public boolean equals(Object o) { return o instanceof SubString; } public String toString() { return toString("substring",Type.T_STRING); } } public static final class StringLength extends Code { private StringLength() { } public int hashCode() { return 982345; } public boolean equals(Object o) { return o instanceof StringLength; } public String toString() { return toString("stringlen",Type.T_STRING); } } public static final class StringLoad extends Code { private StringLoad() { } public int hashCode() { return 12387; } public boolean equals(Object o) { return o instanceof StringLoad; } public String toString() { return toString("stringload",Type.T_STRING); } } public static final class Skip extends Code { Skip() {} public int hashCode() { return 101; } public boolean equals(Object o) { return o instanceof Skip; } public String toString() { return "skip"; } } public static final class Store extends Code { public final Type type; public final int slot; private Store(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Store(type, nslot); } else { return this; } } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Store) { Store i = (Store) o; return (type == i.type || (type != null && type.equals(i.type))) && slot == i.slot; } return false; } public String toString() { return toString("store " + slot,type); } } public static final class Switch extends Code { public final Type type; public final ArrayList<Pair<Value,String>> branches; public final String defaultTarget; Switch(Type type, String defaultTarget, Collection<Pair<Value,String>> branches) { this.type = type; this.branches = new ArrayList<Pair<Value,String>>(branches); this.defaultTarget = defaultTarget; } public Switch relabel(Map<String,String> labels) { ArrayList<Pair<Value,String>> nbranches = new ArrayList(); for(Pair<Value,String> p : branches) { String nlabel = labels.get(p.second()); if(nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(),nlabel)); } } String nlabel = labels.get(defaultTarget); if(nlabel == null) { return Switch(type,defaultTarget,nbranches); } else { return Switch(type,nlabel,nbranches); } } public int hashCode() { if(type == null) { return defaultTarget.hashCode() + branches.hashCode(); } else { return type.hashCode() + defaultTarget.hashCode() + branches.hashCode(); } } public boolean equals(Object o) { if (o instanceof Switch) { Switch ig = (Switch) o; return defaultTarget.equals(ig.defaultTarget) && branches.equals(ig.branches) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Value, String> p : branches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } table += ", *->" + defaultTarget; return "switch " + table; } } public static final class Send extends Code { public final boolean synchronous; public final boolean retval; public final NameID name; public final Type.Method type; private Send(Type.Method type, NameID name, boolean synchronous, boolean retval) { this.type = type; this.name = name; this.synchronous = synchronous; this.retval = retval; } public int hashCode() { return type.hashCode() + name.hashCode(); } public boolean equals(Object o) { if(o instanceof Send) { Send i = (Send) o; return retval == i.retval && synchronous == i.synchronous && (type.equals(i.type) && name.equals(i.name)); } return false; } public String toString() { if(synchronous) { if(retval) { return toString("send " + name,type); } else { return toString("vsend " + name,type); } } else { return toString("asend " + name,type); } } } public static final class Throw extends Code { public final Type type; private Throw(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 98923; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Throw) { Throw i = (Throw) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("throw",type); } } public static final class TryCatch extends Code { public final String target; public final ArrayList<Pair<Type,String>> catches; TryCatch(String target, Collection<Pair<Type,String>> catches) { this.catches = new ArrayList<Pair<Type,String>>(catches); this.target = target; } public TryCatch relabel(Map<String,String> labels) { ArrayList<Pair<Type,String>> nbranches = new ArrayList(); for(Pair<Type,String> p : catches) { String nlabel = labels.get(p.second()); if(nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(),nlabel)); } } String ntarget = labels.get(target); if(ntarget != null) { return TryCatch(ntarget,nbranches); } else { return TryCatch(target,nbranches); } } public int hashCode() { return target.hashCode() + catches.hashCode(); } public boolean equals(Object o) { if (o instanceof TryCatch) { TryCatch ig = (TryCatch) o; return target.equals(ig.target) && catches.equals(ig.catches); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Type, String> p : catches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } return "trycatch " + table; } } /** * Marks the end of a try-catch block. * @author David J. Pearce * */ public static final class TryEnd extends Label { TryEnd(String label) { super(label); } public TryEnd relabel(Map<String,String> labels) { String nlabel = labels.get(label); if(nlabel == null) { return this; } else { return TryEnd(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if(o instanceof TryEnd) { TryEnd e = (TryEnd) o; return e.label.equals(label); } return false; } public String toString() { return "tryend " + label; } } /** * Pops a number (int or real) from the stack, negates it and pushes the * result back on. * * @author David J. Pearce * */ public static final class Negate extends Code { public final Type type; private Negate(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Negate) { Negate bo = (Negate) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("neg",type); } } /** * Corresponds to a bitwise inversion operation, which pops a byte off the * stack and pushes the result back on. For example: * * <pre> * byte f(byte x): * return ~x * </pre> * * Here, the expression <code>~x</code> generates an inverstion bytecode. * * @author David J. Pearce * */ public static final class Invert extends Code { public final Type type; private Invert(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Invert) { Invert bo = (Invert) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("invert",type); } } public static final class Spawn extends Code { public final Type.Process type; private Spawn(Type.Process type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Spawn) { Spawn bo = (Spawn) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("spawn",type); } } public static final class TupleLoad extends Code { public final Type.Tuple type; public final int index; private TupleLoad(Type.Tuple type, int index) { this.type = type; this.index = index; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof TupleLoad) { TupleLoad i = (TupleLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("tupleload " + index,type); } } public static final class ProcLoad extends Code { public final Type.Process type; private ProcLoad(Type.Process type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof ProcLoad) { ProcLoad bo = (ProcLoad) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("procload",type); } } /** * The void bytecode is used to indicate that a given register is no longer live. * @author David J. Pearce * */ public static class Void extends Code { public final Type type; public final int slot; private Void(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Void(type, nslot); } else { return this; } } public int hashCode() { return type.hashCode() + slot; } public boolean equals(Object o) { if(o instanceof Void) { Void i = (Void) o; return type.equals(i.type) && slot == i.slot; } return false; } public String toString() { return toString("void " + slot,type); } } public static String toString(String str, Type t) { if(t == null) { return str + " : ?"; } else { return str + " : " + t; } } public static String toString(String str, Type before, Type after) { if(before == null || after == null) { return str + " : ?"; } else { return str + " : " + before + " => " + after; } } private static final ArrayList<Code> values = new ArrayList<Code>(); private static final HashMap<Code,Integer> cache = new HashMap<Code,Integer>(); private static <T extends Code> T get(T type) { Integer idx = cache.get(type); if(idx != null) { return (T) values.get(idx); } else { cache.put(type, values.size()); values.add(type); return type; } } }
src/wyil/lang/Code.java
// Copyright (c) 2011, David J. Pearce ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyil.lang; import java.util.*; import wyil.util.*; /** * Represents a WYIL bytecode. The Whiley Intermediate Language (WYIL) employs * stack-based bytecodes, similar to the Java Virtual Machine. The frame of each * function/method consists of zero or more <i>local variables</i> (a.k.a * registers) and a <i>stack of unbounded depth</i>. Bytecodes may push/pop * values from the stack, and store/load them from local variables. Like Java * bytecode, WYIL uses unstructured control-flow and allows variables to take on * different types at different points. For example: * * <pre> * int sum([int] data): * r = 0 * for item in data: * r = r + item * return r * </pre> * * This function is compiled into the following WYIL bytecode: * * <pre> * int sum([int] data): * body: * var r, $2, item * const 0 : int * store r : int * move data : [int] * forall item [r] : [int] * move r : int * load item : int * add : int * store r : int * move r : int * return : int * </pre> * * Here, we can see that every bytecode is associated with one (or more) types. * These types are inferred by the compiler during type propagation. * * @author David J. Pearce * */ public abstract class Code { public final static int THIS_SLOT = 0; // =============================================================== // Bytecode Constructors // =============================================================== /** * Construct an <code>assert</code> bytecode which identifies a sequence of * bytecodes which represent a runtime assertion. * * @param label * --- end of block. * @return */ public static Assert Assert(String label) { return get(new Assert(label)); } public static BinOp BinOp(Type type, BOp op) { return get(new BinOp(type,op)); } /** * Construct a <code>const</code> bytecode which loads a given constant * onto the stack. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Const Const(Value constant) { return get(new Const(constant)); } public static Convert Convert(Type from, Type to) { return get(new Convert(from,to)); } public static final Debug debug = new Debug(); public static Destructure Destructure(Type from) { return get(new Destructure(from)); } public static DictLength DictLength(Type.Dictionary type) { return get(new DictLength(type)); } /** * Construct a <code>dictload</code> bytecode which reads the value * associated with a given key in a dictionary. * * @param type * --- dictionary type. * @return */ public static DictLoad DictLoad(Type.Dictionary type) { return get(new DictLoad(type)); } public static LoopEnd End(String label) { return get(new LoopEnd(label)); } /** * Construct a <code>fail</code> bytecode which indicates a runtime failure. * * @param label * --- end of block. * @return */ public static Fail Fail(String label) { return get(new Fail(label)); } /** * Construct a <code>fieldload</code> bytecode which reads a given field * from a record of a given type. * * @param type * --- record type. * @param field * --- field to load. * @return */ public static FieldLoad FieldLoad(Type.Record type, String field) { return get(new FieldLoad(type,field)); } /** * Construct a <code>goto</code> bytecode which branches unconditionally to * a given label. * * @param label * --- destination label. * @return */ public static Goto Goto(String label) { return get(new Goto(label)); } /** * Construct an <code>invoke</code> bytecode which invokes a method. * * @param label * --- destination label. * @return */ public static Invoke Invoke(Type.Function fun, NameID name, boolean retval) { return get(new Invoke(fun,name,retval)); } public static Not Not() { return get(new Not()); } /** * Construct a <code>load</code> bytecode which pushes a given register onto * the stack. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Load Load(Type type, int reg) { return get(new Load(type,reg)); } public static ListLength ListLength(Type.List type) { return get(new ListLength(type)); } /** * Construct a <code>move</code> bytecode which moves a given register onto * the stack. The register contents of the register are voided after this * operation. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Move Move(Type type, int reg) { return get(new Move(type,reg)); } public static SubList SubList(Type.List type) { return get(new SubList(type)); } public static ListAppend ListAppend(Type.List type, OpDir dir) { return get(new ListAppend(type,dir)); } /** * Construct a <code>listload</code> bytecode which reads a value from a * given index in a given list. * * @param type * --- list type. * @return */ public static ListLoad ListLoad(Type.List type) { return get(new ListLoad(type)); } /** * Construct a <code>loop</code> bytecode which iterates the sequence of * bytecodes upto the exit label. * * @param label * --- exit label. * @return */ public static Loop Loop(String label, Collection<Integer> modifies) { return get(new Loop(label,modifies)); } /** * Construct a <code>forall</code> bytecode which iterates over a given * source collection stored on top of the stack. The supplied variable * <code>var</code> is used as the iterator. The exit label denotes the end * of the loop block. * * * @param label * --- exit label. * @return */ public static ForAll ForAll(Type type, int var, String label, Collection<Integer> modifies) { return get(new ForAll(type, var, label, modifies)); } /** * Construct a <code>newdict</code> bytecode which constructs a new dictionary * and puts it on the stack. * * @param type * @return */ public static NewDict NewDict(Type.Dictionary type, int nargs) { return get(new NewDict(type,nargs)); } /** * Construct a <code>newset</code> bytecode which constructs a new set * and puts it on the stack. * * @param type * @return */ public static NewSet NewSet(Type.Set type, int nargs) { return get(new NewSet(type,nargs)); } /** * Construct a <code>newlist</code> bytecode which constructs a new list * and puts it on the stack. * * @param type * @return */ public static NewList NewList(Type.List type, int nargs) { return get(new NewList(type,nargs)); } /** * Construct a <code>newtuple</code> bytecode which constructs a new tuple * and puts it on the stack. * * @param type * @return */ public static NewTuple NewTuple(Type.Tuple type, int nargs) { return get(new NewTuple(type, nargs)); } /** * Construct a <code>newrecord</code> bytecode which constructs a new record * and puts it on the stack. * * @param type * @return */ public static NewRecord NewRecord(Type.Record type) { return get(new NewRecord(type)); } public static Return Return(Type t) { return get(new Return(t)); } public static IfGoto IfGoto(Type type, COp cop, String label) { return get(new IfGoto(type,cop,label)); } public static IfType IfType(Type type, int slot, Type test, String label) { return get(new IfType(type,slot,test,label)); } /** * Construct an <code>indirectsend</code> bytecode which sends an indirect * message to an actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static IndirectSend IndirectSend(Type.Method meth, boolean synchronous, boolean retval) { return get(new IndirectSend(meth,synchronous,retval)); } /** * Construct an <code>indirectinvoke</code> bytecode which sends an indirect * message to an actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static IndirectInvoke IndirectInvoke(Type.Function fun, boolean retval) { return get(new IndirectInvoke(fun,retval)); } public static Invert Invert(Type type) { return get(new Invert(type)); } public static Label Label(String label) { return get(new Label(label)); } public static final Skip Skip = new Skip(); public static SetLength SetLength(Type.Set type) { return get(new SetLength(type)); } public static SetUnion SetUnion(Type.Set type, OpDir dir) { return get(new SetUnion(type,dir)); } public static SetIntersect SetIntersect(Type.Set type, OpDir dir) { return get(new SetIntersect(type,dir)); } public static SetDifference SetDifference(Type.Set type, OpDir dir) { return get(new SetDifference(type,dir)); } public static StringAppend StringAppend(OpDir dir) { return get(new StringAppend(dir)); } public static SubString SubString() { return get(new SubString()); } public static StringLength StringLength() { return get(new StringLength()); } public static StringLoad StringLoad() { return get(new StringLoad()); } /** * Construct an <code>send</code> bytecode which sends a message to an * actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static Send Send(Type.Method meth, NameID name, boolean synchronous, boolean retval) { return get(new Send(meth,name,synchronous,retval)); } /** * Construct a <code>store</code> bytecode which writes a given register. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Store Store(Type type, int reg) { return get(new Store(type,reg)); } /** * Construct a <code>switch</code> bytecode which pops a value off the * stack, and switches to a given label based on it. * * @param type * --- value type to switch on. * @param defaultLabel * --- target for the default case. * @param cases * --- map from values to destination labels. * @return */ public static Switch Switch(Type type, String defaultLabel, Collection<Pair<Value, String>> cases) { return get(new Switch(type,defaultLabel,cases)); } /** * Construct a <code>throw</code> bytecode which pops a value off the * stack and throws it. * * @param afterType * --- value type to throw * @return */ public static Throw Throw(Type t) { return get(new Throw(t)); } /** * Construct a <code>trycatch</code> bytecode which defines a region of * bytecodes which are covered by one or more catch handles. * * @param target * --- identifies end-of-block label. * @param catches * --- map from types to destination labels. * @return */ public static TryCatch TryCatch(String target, Collection<Pair<Type, String>> catches) { return get(new TryCatch(target, catches)); } public static TryEnd TryEnd(String label) { return get(new TryEnd(label)); } /** * Construct a <code>tupleload</code> bytecode which reads the value * at a given index in a tuple * * @param type * --- dictionary type. * @return */ public static TupleLoad TupleLoad(Type.Tuple type, int index) { return get(new TupleLoad(type,index)); } public static Negate Negate(Type type) { return get(new Negate(type)); } public static Spawn Spawn(Type.Process type) { return get(new Spawn(type)); } public static ProcLoad ProcLoad(Type.Process type) { return get(new ProcLoad(type)); } /** * Construct a <code>update</code> bytecode which writes a value into a * compound structure, as determined by a given access path. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Update Update(Type beforeType, Type afterType, int slot, int level, Collection<String> fields) { return get(new Update(beforeType, afterType, slot, level, fields)); } public static Void Void(Type type, int slot) { return get(new Void(type,slot)); } // =============================================================== // Abstract Methods // =============================================================== // The following method adds any slots used by a given bytecode public void slots(Set<Integer> slots) { // default implementation does nothing } /** * The remap method remaps all slots according to a given binding. Slots not * mentioned in the binding retain their original value. * * @param binding * @return */ public Code remap(Map<Integer,Integer> binding) { return this; } /** * Relabel all labels according to the given map. * * @param labels * @return */ public Code relabel(Map<String,String> labels) { return this; } // =============================================================== // Bytecode Implementations // =============================================================== /** * Indicates the start of a code block representing an assertion. This * includes assertions arising from type invariants, as well as * method/function pre- and post-conditions. The target identifies the label * terminating this block. */ public static final class Assert extends Code { public final String target; private Assert(String target) { this.target = target; } public Assert relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return Assert(nlabel); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Assert) { return target.equals(((Assert)o).target); } return false; } public String toString() { return "assert " + target; } } /** * Represents a binary operator (e.g. '+','-',etc) that is provided to a * <code>BinOp</code> bytecode. * * @author David J. Pearce * */ public enum BOp { ADD{ public String toString() { return "add"; } }, SUB{ public String toString() { return "sub"; } }, MUL{ public String toString() { return "mul"; } }, DIV{ public String toString() { return "div"; } }, REM{ public String toString() { return "rem"; } }, RANGE{ public String toString() { return "range"; } }, BITWISEOR{ public String toString() { return "or"; } }, BITWISEXOR{ public String toString() { return "xor"; } }, BITWISEAND{ public String toString() { return "and"; } }, LEFTSHIFT{ public String toString() { return "shl"; } }, RIGHTSHIFT{ public String toString() { return "shr"; } }, }; /** * <p> * A binary operation takes two items off the stack and pushes a single * result. The binary operators are: * </p> * <ul> * <li><i>add, subtract, multiply, divide, remainder</i>. Both operands must * be either integers or reals (but not one or the other). A value of the * same type is produced.</li> * <li><i>range</i></li> * <li><i>bitwiseor, bitwisexor, bitwiseand</i></li> * <li><i>leftshift,rightshift</i></li> * </ul> * * @author David J. Pearce * */ public static final class BinOp extends Code { public final BOp bop; public final Type type; private BinOp(Type type, BOp bop) { if(bop == null) { throw new IllegalArgumentException("BinOp bop argument cannot be null"); } this.bop = bop; this.type = type; } public int hashCode() { if(type == null) { return bop.hashCode(); } else { return type.hashCode() + bop.hashCode(); } } public boolean equals(Object o) { if(o instanceof BinOp) { BinOp bo = (BinOp) o; return (type == bo.type || (type != null && type .equals(bo.type))) && bop.equals(bo.bop); } return false; } public String toString() { return toString(bop.toString(),type); } } /** * <p> * Pops a value from the stack, converts it to a given type and pushes it * back on. This bytecode is the only way to change the type of a value. * It's purpose is to simplify implementations which have different * representations of data types. * </p> * * <p> * In many cases, this bytecode may correspond to a nop on the hardware. * Consider converting from <code>[any]</code> to <code>any</code>. On the * JVM, <code>any</code> translates to <code>Object</code>, whilst * <code>[any]</code> translates to <code>List</code> (which is an instance * of <code>Object</code>). Thus, no conversion is necessary since * <code>List</code> can safely flow into <code>Object</code>. * </p> * * <p> * A convert bytecode must be inserted whenever the type of a variable * changes. This includes at control-flow meet points, when the value is * passed as a parameter, assigned to a field, etc. * </p> */ public static final class Convert extends Code { public final Type from; public final Type to; private Convert(Type from, Type to) { if(to == null) { throw new IllegalArgumentException("Convert to argument cannot be null"); } this.from = from; this.to = to; } public int hashCode() { if(from == null) { return to.hashCode(); } else { return from.hashCode() + to.hashCode(); } } public boolean equals(Object o) { if(o instanceof Convert) { Convert c = (Convert) o; return (from == c.from || (from != null && from.equals(c.from))) && to.equals(c.to); } return false; } public String toString() { return "convert " + from + " to " + to; } } /** * Pushes a constant value onto the stack. This includes integer constants, * rational constants, list constants, set constants, dictionary constants, * function constants, etc. * * @author David J. Pearce * */ public static final class Const extends Code { public final Value constant; private Const(Value constant) { this.constant = constant; } public int hashCode() { return constant.hashCode(); } public boolean equals(Object o) { if(o instanceof Const) { Const c = (Const) o; return constant.equals(c.constant); } return false; } public String toString() { return toString("const " + constant,constant.type()); } } /** * Pops a string from the stack and writes it to the debug console. This * bytecode is not intended to form part of the programs operation. Rather, * it is to facilitate debugging within functions (since they cannot have * side-effects). Furthermore, if debugging is disabled, this bytecode is a * nop. * * @author djp * */ public static final class Debug extends Code { Debug() {} public int hashCode() { return 101; } public boolean equals(Object o) { return o instanceof Debug; } public String toString() { return "debug"; } } /** * Pops a compound value from the stack "destructures" it into multiple * values which are pushed back on the stack. For example, a rational can be * destructured into two integers (the <i>numerator</i> and * <i>denominator</i>). Or, an n-tuple can be destructured into n values. * * Probably should be deprecated in favour of tupeload bytecode. */ public static final class Destructure extends Code { public final Type type; private Destructure(Type from) { this.type = from; } public int hashCode() { if(type == null) { return 12345; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Destructure) { Destructure c = (Destructure) o; return (type == c.type || (type != null && type.equals(c.type))); } return false; } public String toString() { return "destructure " + type; } } /** * Pops a dictionary value from stack, and pushes it's length back on. * * @author djp * */ public static final class DictLength extends Code { public final Type.Dictionary type; private DictLength(Type.Dictionary type) { this.type = type; } public int hashCode() { if(type == null) { return 558723; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof DictLength) { DictLength setop = (DictLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("dictlength",type); } } /** * Pops a key and dictionary from the stack, and looks up the value for that * key in the dictionary. If no value exists, a dictionary fault is raised. * Otherwise, the value is pushed onto the stack. * * @author djp * */ public static final class DictLoad extends Code { public final Type.Dictionary type; private DictLoad(Type.Dictionary type) { this.type = type; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof DictLoad) { DictLoad i = (DictLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("dictload",type); } } /** * Marks the end of a loop block. * @author djp * */ public static final class LoopEnd extends Label { LoopEnd(String label) { super(label); } public LoopEnd relabel(Map<String,String> labels) { String nlabel = labels.get(label); if(nlabel == null) { return this; } else { return End(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if(o instanceof LoopEnd) { LoopEnd e = (LoopEnd) o; return e.label.equals(label); } return false; } public String toString() { return "end " + label; } } /** * Raises an assertion failure fault with the given message. Fail bytecodes * may only appear within assertion blocks. * * @author djp * */ public static final class Fail extends Code { public final String msg; private Fail(String msg) { this.msg = msg; } public int hashCode() { return msg.hashCode(); } public boolean equals(Object o) { if(o instanceof Fail) { return msg.equals(((Fail)o).msg); } return false; } public String toString() { return "fail \"" + msg + "\""; } } /** * Pops a record from the stack and pushes the value from the given * field back on. * * @author David J. Pearce * */ public static final class FieldLoad extends Code { public final Type.Record type; public final String field; private FieldLoad(Type.Record type, String field) { if (field == null) { throw new IllegalArgumentException( "FieldLoad field argument cannot be null"); } this.type = type; this.field = field; } public int hashCode() { if(type != null) { return type.hashCode() + field.hashCode(); } else { return field.hashCode(); } } public Type fieldType() { return type.fields().get(field); } public boolean equals(Object o) { if(o instanceof FieldLoad) { FieldLoad i = (FieldLoad) o; return (i.type == type || (type != null && type.equals(i.type))) && field.equals(i.field); } return false; } public String toString() { return toString("fieldload " + field,type); } } /** * <p> * Branches unconditionally to the given label. * </p> * * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, a <code>goto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author djp * */ public static final class Goto extends Code { public final String target; private Goto(String target) { this.target = target; } public Goto relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return Goto(nlabel); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Goto) { return target.equals(((Goto)o).target); } return false; } public String toString() { return "goto " + target; } } /** * <p> * Branches conditionally to the given label by popping two operands from * the stack and comparing them. The possible comparators are: * </p> * <ul> * <li><i>equals (eq) and not-equals (ne)</i>. Both operands must have the * given type.</li> * <li><i>less-than (lt), less-than-or-equals (le), greater-than (gt) and * great-than-or-equals (ge).</i> Both operands must have the given type, * which additionally must by either <code>char</code>, <code>int</code> or * <code>real</code>.</li> * <li><i>element of (in).</i> The second operand must be a set whose * element type is that of the first.</li> * <li><i>subset (ss) and subset-equals (sse)</i>. Both operands must have * the given type, which additionally must be a set.</li> * </ul> * * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>ifgoto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author djp * */ public static final class IfGoto extends Code { public final Type type; public final COp op; public final String target; private IfGoto(Type type, COp op, String target) { if(op == null) { throw new IllegalArgumentException("IfGoto op argument cannot be null"); } if(target == null) { throw new IllegalArgumentException("IfGoto target argument cannot be null"); } this.type = type; this.op = op; this.target = target; } public IfGoto relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return IfGoto(type,op,nlabel); } } public int hashCode() { if(type == null) { return op.hashCode() + target.hashCode(); } else { return type.hashCode() + op.hashCode() + target.hashCode(); } } public boolean equals(Object o) { if(o instanceof IfGoto) { IfGoto ig = (IfGoto) o; return op == ig.op && target.equals(ig.target) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { return toString("if" + op + " goto " + target,type); } } /** * Represents a comparison operator (e.g. '==','!=',etc) that is provided to a * <code>IfGoto</code> bytecode. * * @author David J. Pearce * */ public enum COp { EQ() { public String toString() { return "eq"; } }, NEQ{ public String toString() { return "ne"; } }, LT{ public String toString() { return "lt"; } }, LTEQ{ public String toString() { return "le"; } }, GT{ public String toString() { return "gt"; } }, GTEQ{ public String toString() { return "ge"; } }, ELEMOF{ public String toString() { return "in"; } }, SUBSET{ public String toString() { return "sb"; } }, SUBSETEQ{ public String toString() { return "sbe"; } } }; /** * <p> * Branches conditionally to the given label based on the result of a * runtime type test against a given value. More specifically, it checks * whether the value is a subtype of the type test. The value in question is * either loaded directly from a variable, or popped off the stack. * </p> * <p> * In the case that the value is obtained from a specific variable, then * that variable is automatically <i>retyped</i> as a result of the type * test. On the true branch, its type is intersected with type test. On the * false branch, its type is intersected with the <i>negation</i> of the * type test. * </p> * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>iftype</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author djp * */ public static final class IfType extends Code { public final Type type; public final int slot; public final Type test; public final String target; private IfType(Type type, int slot, Type test, String target) { if(test == null) { throw new IllegalArgumentException("IfGoto op argument cannot be null"); } if(target == null) { throw new IllegalArgumentException("IfGoto target argument cannot be null"); } this.type = type; this.slot = slot; this.test = test; this.target = target; } public IfType relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return IfType(type,slot,test,nlabel); } } public void slots(Set<Integer> slots) { if(slot >= 0) { slots.add(slot); } } public Code remap(Map<Integer, Integer> binding) { if (slot >= 0) { Integer nslot = binding.get(slot); if (nslot != null) { return Code.IfType(type, nslot, test, target); } } return this; } public int hashCode() { if(type == null) { return test.hashCode() + target.hashCode(); } else { return type.hashCode() + test.hashCode() + target.hashCode(); } } public boolean equals(Object o) { if(o instanceof IfType) { IfType ig = (IfType) o; return test.equals(ig.test) && slot == ig.slot && target.equals(ig.target) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { if(slot >= 0) { return toString("if " + slot + " is " + test + " goto " + target,type); } else { return toString("if " + test + " goto " + target,type); } } } /** * Represents an indirect function call. For example, consider the * following: * * <pre> * int function(int(int) f, int x): * return f(x) * </pre> * * Here, the function call <code>f(x)</code> is indirect as the called * function is determined by the variable <code>f</code>. * * @author David J. Pearce * */ public static final class IndirectInvoke extends Code { public final Type.Function type; public final boolean retval; private IndirectInvoke(Type.Function type, boolean retval) { this.type = type; this.retval = retval; } public int hashCode() { if(type != null) { return type.hashCode(); } else { return 123; } } public boolean equals(Object o) { if(o instanceof IndirectInvoke) { IndirectInvoke i = (IndirectInvoke) o; return retval == i.retval && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { if(retval) { return toString("indirectinvoke",type); } else { return toString("vindirectinvoke",type); } } } /** * Represents an indirect message send (either synchronous or asynchronous). * For example, consider the following: * * <pre> * int ::method(Rec::int(int) m, Rec r, int x): * return r.m(x) * </pre> * * Here, the message send <code>r.m(x)</code> is indirect as the message * sent is determined by the variable <code>m</code>. * * @author David J. Pearce * */ public static final class IndirectSend extends Code { public final boolean synchronous; public final boolean retval; public final Type.Method type; private IndirectSend(Type.Method type, boolean synchronous, boolean retval) { this.type = type; this.synchronous = synchronous; this.retval = retval; } public int hashCode() { if(type != null) { return type.hashCode(); } else { return 123; } } public boolean equals(Object o) { if(o instanceof IndirectSend) { IndirectSend i = (IndirectSend) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { if(synchronous) { if(retval) { return toString("isend",type); } else { return toString("ivsend",type); } } else { return toString("iasend",type); } } } public static final class Not extends Code { private Not() { } public int hashCode() { return 12875; } public boolean equals(Object o) { return o instanceof Not; } public String toString() { return toString("not",Type.T_BYTE); } } /** * Corresponds to a direct function call whose parameters are found on the * stack in the order corresponding to the function type. If a return value * is required, this is pushed onto the stack after the function call. * * @author David J. Pearce * */ public static final class Invoke extends Code { public final Type.Function type; public final NameID name; public final boolean retval; private Invoke(Type.Function type, NameID name, boolean retval) { this.type = type; this.name = name; this.retval = retval; } public int hashCode() { if(type == null) { return name.hashCode(); } else { return type.hashCode() + name.hashCode(); } } public boolean equals(Object o) { if (o instanceof Invoke) { Invoke i = (Invoke) o; return name.equals(i.name) && retval == i.retval && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { if(retval) { return toString("invoke " + name,type); } else { return toString("vinvoke " + name,type); } } } /** * Represents the labelled destination of a branch or loop statement. * * @author David J. Pearce * */ public static class Label extends Code { public final String label; private Label(String label) { this.label = label; } public Label relabel(Map<String,String> labels) { String nlabel = labels.get(label); if(nlabel == null) { return this; } else { return Label(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof Label) { return label.equals(((Label) o).label); } return false; } public String toString() { return "." + label; } } /** * Pops two lists from the stack, appends them together and pushes the * result back onto the stack. * * @author David J. Pearce * */ public static final class ListAppend extends Code { public final OpDir dir; public final Type.List type; private ListAppend(Type.List type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("ListAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof ListAppend) { ListAppend setop = (ListAppend) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("listappend" + dir.toString(),type); } } /** * Pops a list from the stack and pushes its length back on. * * @author David J. Pearce * */ public static final class ListLength extends Code { public final Type.List type; private ListLength(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 124987; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof ListLength) { ListLength setop = (ListLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("listlength",type); } } public static final class SubList extends Code { public final Type.List type; private SubList(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 124987; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof SubList) { SubList setop = (SubList) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("sublist",type); } } /** * Pops am integer index from the stack, followed by a list and pushes the * element at the given index back on. * * @author David J. Pearce * */ public static final class ListLoad extends Code { public final Type.List type; private ListLoad(Type.List type) { this.type = type; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof ListLoad) { ListLoad i = (ListLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("listload",type); } } /** * Loads the contents of the given variable onto the stack. * * @author David J. Pearce * */ public static final class Load extends Code { public final Type type; public final int slot; private Load(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Load(type, nslot); } else { return this; } } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Load) { Load i = (Load) o; return slot == i.slot && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { return toString("load " + slot,type); } } /** * Moves the contents of the given variable onto the stack. This is similar * to a <code>load</code> bytecode, except that the variable's contents is * "voided" afterwards. This guarantees that the variable is no longer live, * which is useful for determining the live ranges of variables in a * function or method. * * @author David J. Pearce * */ public static final class Move extends Code { public final Type type; public final int slot; private Move(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Move(type, nslot); } else { return this; } } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Move) { Move i = (Move) o; return slot == i.slot && (type == i.type || (type != null && type .equals(i.type))); } return false; } public String toString() { return toString("move " + slot,type); } } public static class Loop extends Code { public final String target; public final HashSet<Integer> modifies; private Loop(String target, Collection<Integer> modifies) { this.target = target; this.modifies = new HashSet<Integer>(modifies); } public Loop relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return Loop(nlabel,modifies); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if(o instanceof Loop) { Loop f = (Loop) o; return target.equals(f.target) && modifies.equals(f.modifies); } return false; } public String toString() { return "loop " + modifies; } } /** * Pops a set, list or dictionary from the stack and iterates over every * element it contains. An index variable is given which holds the current * value being iterated over. * * @author djp * */ public static final class ForAll extends Loop { public final int slot; public final Type type; private ForAll(Type type, int slot, String target, Collection<Integer> modifies) { super(target,modifies); this.type = type; this.slot = slot; } public ForAll relabel(Map<String,String> labels) { String nlabel = labels.get(target); if(nlabel == null) { return this; } else { return ForAll(type,slot,nlabel,modifies); } } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.ForAll(type, nslot, target, modifies); } else { return this; } } public int hashCode() { return super.hashCode() + slot; } public boolean equals(Object o) { if (o instanceof ForAll) { ForAll f = (ForAll) o; return target.equals(f.target) && (type == f.type || (type != null && type .equals(f.type))) && slot == f.slot && modifies.equals(f.modifies); } return false; } public String toString() { return toString("forall " + slot + " " + modifies,type); } } /** * Represents a type which may appear on the left of an assignment * expression. Lists, Dictionaries, Strings, Records and Processes are the * only valid types for an lval. * * @author djp * */ public static abstract class LVal { protected Type type; public LVal(Type t) { this.type = t; } public Type rawType() { return type; } } /** * An LVal with dictionary type. * @author djp * */ public static final class DictLVal extends LVal { public DictLVal(Type t) { super(t); if(Type.effectiveDictionaryType(t) == null) { throw new IllegalArgumentException("Invalid Dictionary Type"); } } public Type.Dictionary type() { return Type.effectiveDictionaryType(type); } } /** * An LVal with list type. * @author djp * */ public static final class ListLVal extends LVal { public ListLVal(Type t) { super(t); if(Type.effectiveListType(t) == null) { throw new IllegalArgumentException("Invalid List Type"); } } public Type.List type() { return Type.effectiveListType(type); } } /** * An LVal with string type. * @author djp * */ public static final class StringLVal extends LVal { public StringLVal() { super(Type.T_STRING); } } /** * An LVal with record type. * @author djp * */ public static final class RecordLVal extends LVal { public final String field; public RecordLVal(Type t, String field) { super(t); this.field = field; Type.Record rt = Type.effectiveRecordType(t); if(rt == null || !rt.fields().containsKey(field)) { throw new IllegalArgumentException("Invalid Record Type"); } } public Type.Record type() { return Type.effectiveRecordType(type); } } private static final class UpdateIterator implements Iterator<LVal> { private final ArrayList<String> fields; private Type iter; private int fieldIndex; private int index; public UpdateIterator(Type type, int level, ArrayList<String> fields) { this.fields = fields; this.iter = type; this.index = level; // TODO: sort out this hack if(Type.isSubtype(Type.Process(Type.T_ANY), iter)) { Type.Process p = (Type.Process) iter; iter = p.element(); } } public LVal next() { Type raw = iter; index--; if(Type.isSubtype(Type.T_STRING,iter)) { iter = Type.T_CHAR; return new StringLVal(); } else if(Type.isSubtype(Type.List(Type.T_ANY,false),iter)) { Type.List list = Type.effectiveListType(iter); iter = list.element(); return new ListLVal(raw); } else if(Type.isSubtype(Type.Dictionary(Type.T_ANY, Type.T_ANY),iter)) { // this indicates a dictionary access, rather than a list access Type.Dictionary dict = Type.effectiveDictionaryType(iter); iter = dict.value(); return new DictLVal(raw); } else if(Type.effectiveRecordType(iter) != null) { Type.Record rec = Type.effectiveRecordType(iter); String field = fields.get(fieldIndex++); iter = rec.fields().get(field); return new RecordLVal(raw,field); } else { throw new IllegalArgumentException("Invalid type for Code.Update"); } } public boolean hasNext() { return index > 0; } public void remove() { throw new UnsupportedOperationException("UpdateIterator is unmodifiable"); } } /** * <p> * Pops a compound structure, zero or more indices and a value from the * stack and updates the compound structure with the given value. Valid * compound structures are lists, dictionaries, strings, records and * processes. * </p> * <p> * Ideally, this operation is done in-place, meaning the operation is * constant time. However, to support Whiley's value semantics this bytecode * may require (in some cases) a clone of the underlying data-structure. * Thus, the worst-case runtime of this operation is linear in the size of * the compound structure. * </p> * * @author djp * */ public static final class Update extends Code implements Iterable<LVal> { public final Type beforeType; public final Type afterType; public final int level; public final int slot; public final ArrayList<String> fields; private Update(Type beforeType, Type afterType, int slot, int level, Collection<String> fields) { if (fields == null) { throw new IllegalArgumentException( "FieldStore fields argument cannot be null"); } this.beforeType = beforeType; this.afterType = afterType; this.slot = slot; this.level = level; this.fields = new ArrayList<String>(fields); } public void slots(Set<Integer> slots) { slots.add(slot); } public Iterator<LVal> iterator() { return new UpdateIterator(afterType,level,fields); } /** * Extract the type for the right-hand side of this assignment. * @return */ public Type rhs() { Type iter = afterType; // TODO: sort out this hack if (Type.isSubtype(Type.Process(Type.T_ANY), iter)) { Type.Process p = (Type.Process) iter; iter = p.element(); } int fieldIndex = 0; for (int i = 0; i != level; ++i) { if (Type.isSubtype(Type.T_STRING, iter)) { iter = Type.T_CHAR; } else if (Type.isSubtype(Type.List(Type.T_ANY,false), iter)) { Type.List list = Type.effectiveListType(iter); iter = list.element(); } else if (Type.isSubtype( Type.Dictionary(Type.T_ANY, Type.T_ANY), iter)) { // this indicates a dictionary access, rather than a list // access Type.Dictionary dict = Type.effectiveDictionaryType(iter); iter = dict.value(); } else if (Type.effectiveRecordType(iter) != null) { Type.Record rec = Type.effectiveRecordType(iter); String field = fields.get(fieldIndex++); iter = rec.fields().get(field); } else { throw new IllegalArgumentException( "Invalid type for Code.Update"); } } return iter; } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Update(beforeType, afterType, nslot, level, fields); } else { return this; } } public int hashCode() { if(afterType == null) { return level + fields.hashCode(); } else { return afterType.hashCode() + slot + level + fields.hashCode(); } } public boolean equals(Object o) { if (o instanceof Update) { Update i = (Update) o; return (i.beforeType == beforeType || (beforeType != null && beforeType .equals(i.beforeType))) && (i.afterType == afterType || (afterType != null && afterType .equals(i.afterType))) && level == i.level && slot == i.slot && fields.equals(i.fields); } return false; } public String toString() { String fs = fields.isEmpty() ? "" : " "; boolean firstTime=true; for(String f : fields) { if(!firstTime) { fs += "."; } firstTime=false; fs += f; } return toString("update " + slot + " #" + level + fs,beforeType,afterType); } } /** * Constructs a new dictionary value from zero or more key-value pairs on * the stack. For each pair, the key must occur directly before the value on * the stack. For example: * * <pre> * const 1 : int * const "Hello" : string * const 2 : int * const "World" : string * newdict #2 : {int->string} * </pre> * * Pushes the dictionary value <code>{1->"Hello",2->"World"}</code> onto the * stack. * * @author David J. Pearce * */ public static final class NewDict extends Code { public final Type.Dictionary type; public final int nargs; private NewDict(Type.Dictionary type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode() + nargs; } } public boolean equals(Object o) { if(o instanceof NewDict) { NewDict i = (NewDict) o; return (type == i.type || (type != null && type.equals(i.type))) && nargs == i.nargs; } return false; } public String toString() { return toString("newdict #" + nargs,type); } } /** * Constructs a new record value from zero or more values on the stack. Each * value is associated with a field name, and will be popped from the stack * in the reverse order. For example: * * <pre> * const 1 : int * const 2 : int * newrec : {int x,int y} * </pre> * * Pushes the record value <code>{x:1,y:2}</code> onto the stack. * * @author David J. Pearce * */ public static final class NewRecord extends Code { public final Type.Record type; private NewRecord(Type.Record type) { this.type = type; } public int hashCode() { if(type == null) { return 952; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewRecord) { NewRecord i = (NewRecord) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("newrec",type); } } /** * Constructs a new tuple value from two or more values on the stack. Values * are popped from the stack in the reverse order they occur in the tuple. * For example: * * <pre> * const 1 : int * const 2 : int * newtuple #2 : (int,int) * </pre> * * Pushes the tuple value <code>(1,2)</code> onto the stack. * * @author David J. Pearce * */ public static final class NewTuple extends Code { public final Type.Tuple type; public final int nargs; private NewTuple(Type.Tuple type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode() + nargs; } } public boolean equals(Object o) { if(o instanceof NewTuple) { NewTuple i = (NewTuple) o; return nargs == i.nargs && (type == i.type || (type != null && type.equals(i.type))); } return false; } public String toString() { return toString("newtuple #" + nargs,type); } } /** * Constructs a new set value from zero or more values on the stack. The new * set is load onto the stack. For example: * * <pre> * const 1 : int * const 2 : int * const 3 : int * newset #3 : {int} * </pre> * * Pushes the set value <code>{1,2,3}</code> onto the stack. * * @author David J. Pearce * */ public static final class NewSet extends Code { public final Type.Set type; public final int nargs; private NewSet(Type.Set type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewSet) { NewSet i = (NewSet) o; return type == i.type || (type != null && type.equals(i.type)) && nargs == i.nargs; } return false; } public String toString() { return toString("newset #" + nargs,type); } } /** * Constructs a new list value from zero or more values on the stack. The * values are popped from the stack in the reverse order they will occur in * the new list. The new list is load onto the stack. For example: * * <pre> * const 1 : int * const 2 : int * const 3 : int * newlist #3 : [int] * </pre> * * Pushes the list value <code>[1,2,3]</code> onto the stack. * * @author David J. Pearce * */ public static final class NewList extends Code { public final Type.List type; public final int nargs; private NewList(Type.List type, int nargs) { this.type = type; this.nargs = nargs; } public int hashCode() { if(type == null) { return nargs; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof NewList) { NewList i = (NewList) o; return type == i.type || (type != null && type.equals(i.type)) && nargs == i.nargs; } return false; } public String toString() { return toString("newlist #" + nargs,type); } } public static final class Nop extends Code { private Nop() {} public String toString() { return "nop"; } } public static final class Return extends Code { public final Type type; private Return(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 996; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Return) { Return i = (Return) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("return",type); } } public enum OpDir { UNIFORM { public String toString() { return ""; } }, LEFT { public String toString() { return "_l"; } }, RIGHT { public String toString() { return "_r"; } } } public static final class SetUnion extends Code { public final OpDir dir; public final Type.Set type; private SetUnion(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetUnion) { SetUnion setop = (SetUnion) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("union" + dir.toString(),type); } } public static final class SetIntersect extends Code { public final OpDir dir; public final Type.Set type; private SetIntersect(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetIntersect) { SetIntersect setop = (SetIntersect) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("intersect" + dir.toString(),type); } } public static final class SetDifference extends Code { public final OpDir dir; public final Type.Set type; private SetDifference(Type.Set type, OpDir dir) { if(dir == null) { throw new IllegalArgumentException("SetAppend direction cannot be null"); } this.type = type; this.dir = dir; } public int hashCode() { if(type == null) { return dir.hashCode(); } else { return type.hashCode() + dir.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetDifference) { SetDifference setop = (SetDifference) o; return (type == setop.type || (type != null && type .equals(setop.type))) && dir.equals(setop.dir); } return false; } public String toString() { return toString("difference" + dir.toString(),type); } } public static final class SetLength extends Code { public final Type.Set type; private SetLength(Type.Set type) { this.type = type; } public int hashCode() { if(type == null) { return 558723; } else { return type.hashCode(); } } public boolean equals(Object o) { if (o instanceof SetLength) { SetLength setop = (SetLength) o; return (type == setop.type || (type != null && type .equals(setop.type))); } return false; } public String toString() { return toString("setlength",type); } } public static final class StringAppend extends Code { public final OpDir dir; private StringAppend(OpDir dir) { if(dir == null) { throw new IllegalArgumentException("StringAppend direction cannot be null"); } this.dir = dir; } public int hashCode() { return dir.hashCode(); } public boolean equals(Object o) { if (o instanceof StringAppend) { StringAppend setop = (StringAppend) o; return dir.equals(setop.dir); } return false; } public String toString() { return toString("stringappend" + dir.toString(),Type.T_STRING); } } public static final class SubString extends Code { private SubString() { } public int hashCode() { return 983745; } public boolean equals(Object o) { return o instanceof SubString; } public String toString() { return toString("substring",Type.T_STRING); } } public static final class StringLength extends Code { private StringLength() { } public int hashCode() { return 982345; } public boolean equals(Object o) { return o instanceof StringLength; } public String toString() { return toString("stringlen",Type.T_STRING); } } public static final class StringLoad extends Code { private StringLoad() { } public int hashCode() { return 12387; } public boolean equals(Object o) { return o instanceof StringLoad; } public String toString() { return toString("stringload",Type.T_STRING); } } public static final class Skip extends Code { Skip() {} public int hashCode() { return 101; } public boolean equals(Object o) { return o instanceof Skip; } public String toString() { return "skip"; } } public static final class Store extends Code { public final Type type; public final int slot; private Store(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Store(type, nslot); } else { return this; } } public int hashCode() { if(type == null) { return slot; } else { return type.hashCode() + slot; } } public boolean equals(Object o) { if(o instanceof Store) { Store i = (Store) o; return (type == i.type || (type != null && type.equals(i.type))) && slot == i.slot; } return false; } public String toString() { return toString("store " + slot,type); } } public static final class Switch extends Code { public final Type type; public final ArrayList<Pair<Value,String>> branches; public final String defaultTarget; Switch(Type type, String defaultTarget, Collection<Pair<Value,String>> branches) { this.type = type; this.branches = new ArrayList<Pair<Value,String>>(branches); this.defaultTarget = defaultTarget; } public Switch relabel(Map<String,String> labels) { ArrayList<Pair<Value,String>> nbranches = new ArrayList(); for(Pair<Value,String> p : branches) { String nlabel = labels.get(p.second()); if(nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(),nlabel)); } } String nlabel = labels.get(defaultTarget); if(nlabel == null) { return Switch(type,defaultTarget,nbranches); } else { return Switch(type,nlabel,nbranches); } } public int hashCode() { if(type == null) { return defaultTarget.hashCode() + branches.hashCode(); } else { return type.hashCode() + defaultTarget.hashCode() + branches.hashCode(); } } public boolean equals(Object o) { if (o instanceof Switch) { Switch ig = (Switch) o; return defaultTarget.equals(ig.defaultTarget) && branches.equals(ig.branches) && (type == ig.type || (type != null && type .equals(ig.type))); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Value, String> p : branches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } table += ", *->" + defaultTarget; return "switch " + table; } } public static final class Send extends Code { public final boolean synchronous; public final boolean retval; public final NameID name; public final Type.Method type; private Send(Type.Method type, NameID name, boolean synchronous, boolean retval) { this.type = type; this.name = name; this.synchronous = synchronous; this.retval = retval; } public int hashCode() { return type.hashCode() + name.hashCode(); } public boolean equals(Object o) { if(o instanceof Send) { Send i = (Send) o; return retval == i.retval && synchronous == i.synchronous && (type.equals(i.type) && name.equals(i.name)); } return false; } public String toString() { if(synchronous) { if(retval) { return toString("send " + name,type); } else { return toString("vsend " + name,type); } } else { return toString("asend " + name,type); } } } public static final class Throw extends Code { public final Type type; private Throw(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 98923; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Throw) { Throw i = (Throw) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("throw",type); } } public static final class TryCatch extends Code { public final String target; public final ArrayList<Pair<Type,String>> catches; TryCatch(String target, Collection<Pair<Type,String>> catches) { this.catches = new ArrayList<Pair<Type,String>>(catches); this.target = target; } public TryCatch relabel(Map<String,String> labels) { ArrayList<Pair<Type,String>> nbranches = new ArrayList(); for(Pair<Type,String> p : catches) { String nlabel = labels.get(p.second()); if(nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(),nlabel)); } } String ntarget = labels.get(target); if(ntarget != null) { return TryCatch(ntarget,nbranches); } else { return TryCatch(target,nbranches); } } public int hashCode() { return target.hashCode() + catches.hashCode(); } public boolean equals(Object o) { if (o instanceof TryCatch) { TryCatch ig = (TryCatch) o; return target.equals(ig.target) && catches.equals(ig.catches); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Type, String> p : catches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } return "trycatch " + table; } } /** * Marks the end of a try-catch block. * @author djp * */ public static final class TryEnd extends Label { TryEnd(String label) { super(label); } public TryEnd relabel(Map<String,String> labels) { String nlabel = labels.get(label); if(nlabel == null) { return this; } else { return TryEnd(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if(o instanceof TryEnd) { TryEnd e = (TryEnd) o; return e.label.equals(label); } return false; } public String toString() { return "tryend " + label; } } /** * Pops a number (int or real) from the stack, negates it and pushes the * result back on. * * @author David J. Pearce * */ public static final class Negate extends Code { public final Type type; private Negate(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Negate) { Negate bo = (Negate) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("neg",type); } } /** * Corresponds to a bitwise inversion operation, which pops a byte off the * stack and pushes the result back on. For example: * * <pre> * byte f(byte x): * return ~x * </pre> * * Here, the expression <code>~x</code> generates an inverstion bytecode. * * @author David J. Pearce * */ public static final class Invert extends Code { public final Type type; private Invert(Type type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Invert) { Invert bo = (Invert) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("invert",type); } } public static final class Spawn extends Code { public final Type.Process type; private Spawn(Type.Process type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof Spawn) { Spawn bo = (Spawn) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("spawn",type); } } public static final class TupleLoad extends Code { public final Type.Tuple type; public final int index; private TupleLoad(Type.Tuple type, int index) { this.type = type; this.index = index; } public int hashCode() { if(type == null) { return 235; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof TupleLoad) { TupleLoad i = (TupleLoad) o; return type == i.type || (type != null && type.equals(i.type)); } return false; } public String toString() { return toString("tupleload " + index,type); } } public static final class ProcLoad extends Code { public final Type.Process type; private ProcLoad(Type.Process type) { this.type = type; } public int hashCode() { if(type == null) { return 239487; } else { return type.hashCode(); } } public boolean equals(Object o) { if(o instanceof ProcLoad) { ProcLoad bo = (ProcLoad) o; return (type == bo.type || (type != null && type .equals(bo.type))); } return false; } public String toString() { return toString("procload",type); } } /** * The void bytecode is used to indicate that a given register is no longer live. * @author David J. Pearce * */ public static class Void extends Code { public final Type type; public final int slot; private Void(Type type, int slot) { this.type = type; this.slot = slot; } public void slots(Set<Integer> slots) { slots.add(slot); } public Code remap(Map<Integer,Integer> binding) { Integer nslot = binding.get(slot); if(nslot != null) { return Code.Void(type, nslot); } else { return this; } } public int hashCode() { return type.hashCode() + slot; } public boolean equals(Object o) { if(o instanceof Void) { Void i = (Void) o; return type.equals(i.type) && slot == i.slot; } return false; } public String toString() { return toString("void " + slot,type); } } public static String toString(String str, Type t) { if(t == null) { return str + " : ?"; } else { return str + " : " + t; } } public static String toString(String str, Type before, Type after) { if(before == null || after == null) { return str + " : ?"; } else { return str + " : " + before + " => " + after; } } private static final ArrayList<Code> values = new ArrayList<Code>(); private static final HashMap<Code,Integer> cache = new HashMap<Code,Integer>(); private static <T extends Code> T get(T type) { Integer idx = cache.get(type); if(idx != null) { return (T) values.get(idx); } else { cache.put(type, values.size()); values.add(type); return type; } } }
A little more documentation.
src/wyil/lang/Code.java
A little more documentation.
<ide><path>rc/wyil/lang/Code.java <del>// Copyright (c) 2011, David J. Pearce ([email protected]) <add>// Copyright (c) 2011, David J. Pearce (David J. [email protected]) <ide> // All rights reserved. <ide> // <ide> // Redistribution and use in source and binary forms, with or without <ide> * </p> <ide> * <ide> * <p> <del> * A convert bytecode must be inserted whenever the type of a variable <add> * A convert bytecode must be inserted whenever the type of a register <ide> * changes. This includes at control-flow meet points, when the value is <ide> * passed as a parameter, assigned to a field, etc. <ide> * </p> <ide> * side-effects). Furthermore, if debugging is disabled, this bytecode is a <ide> * nop. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class Debug extends Code { <ide> /** <ide> * Pops a dictionary value from stack, and pushes it's length back on. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class DictLength extends Code { <ide> * key in the dictionary. If no value exists, a dictionary fault is raised. <ide> * Otherwise, the value is pushed onto the stack. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class DictLoad extends Code { <ide> <ide> /** <ide> * Marks the end of a loop block. <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class LoopEnd extends Label { <ide> * Raises an assertion failure fault with the given message. Fail bytecodes <ide> * may only appear within assertion blocks. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class Fail extends Code { <ide> * Thus, a <code>goto</code> bytecode cannot be used to implement the <ide> * back-edge of a loop. Rather, a loop block must be used for this purpose. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class Goto extends Code { <ide> * Thus, an <code>ifgoto</code> bytecode cannot be used to implement the <ide> * back-edge of a loop. Rather, a loop block must be used for this purpose. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class IfGoto extends Code { <ide> * Branches conditionally to the given label based on the result of a <ide> * runtime type test against a given value. More specifically, it checks <ide> * whether the value is a subtype of the type test. The value in question is <del> * either loaded directly from a variable, or popped off the stack. <add> * either loaded directly from a register, or popped off the stack. <ide> * </p> <ide> * <p> <del> * In the case that the value is obtained from a specific variable, then <del> * that variable is automatically <i>retyped</i> as a result of the type <del> * test. On the true branch, its type is intersected with type test. On the <del> * false branch, its type is intersected with the <i>negation</i> of the <del> * type test. <add> * In the case that the value is obtained from a register, then that <add> * variable is automatically <i>retyped</i> as a result of the type test. On <add> * the true branch, its type is intersected with type test. On the false <add> * branch, its type is intersected with the <i>negation</i> of the type <add> * test. <ide> * </p> <ide> * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. <ide> * Thus, an <code>iftype</code> bytecode cannot be used to implement the <ide> * back-edge of a loop. Rather, a loop block must be used for this purpose. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class IfType extends Code { <ide> } <ide> <ide> /** <del> * Loads the contents of the given variable onto the stack. <add> * Loads the contents of the given register onto the stack. <ide> * <ide> * @author David J. Pearce <ide> * <ide> } <ide> <ide> /** <del> * Moves the contents of the given variable onto the stack. This is similar <del> * to a <code>load</code> bytecode, except that the variable's contents is <del> * "voided" afterwards. This guarantees that the variable is no longer live, <del> * which is useful for determining the live ranges of variables in a <add> * Moves the contents of the given register onto the stack. This is similar <add> * to a <code>load</code> bytecode, except that the register's contents are <add> * "voided" afterwards. This guarantees that the register is no longer live, <add> * which is useful for determining the live ranges of register in a <ide> * function or method. <ide> * <ide> * @author David J. Pearce <ide> <ide> /** <ide> * Pops a set, list or dictionary from the stack and iterates over every <del> * element it contains. An index variable is given which holds the current <del> * value being iterated over. <del> * <del> * @author djp <add> * element it contains. An register is identified to hold the current value <add> * being iterated over. <add> * <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class ForAll extends Loop { <ide> * expression. Lists, Dictionaries, Strings, Records and Processes are the <ide> * only valid types for an lval. <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static abstract class LVal { <ide> <ide> /** <ide> * An LVal with dictionary type. <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class DictLVal extends LVal { <ide> <ide> /** <ide> * An LVal with list type. <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class ListLVal extends LVal { <ide> <ide> /** <ide> * An LVal with string type. <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class StringLVal extends LVal { <ide> <ide> /** <ide> * An LVal with record type. <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class RecordLVal extends LVal { <ide> * the compound structure. <ide> * </p> <ide> * <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class Update extends Code implements Iterable<LVal> { <ide> <ide> /** <ide> * Marks the end of a try-catch block. <del> * @author djp <add> * @author David J. Pearce <ide> * <ide> */ <ide> public static final class TryEnd extends Label {
Java
apache-2.0
6426bf10871060f1112548e21bf297a0ad9e0294
0
webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno
/******************************************************************************* * Copyright 2012 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tudarmstadt.ukp.clarin.webanno.webapp.dialog; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.extensions.markup.html.form.select.Select; import org.apache.wicket.extensions.markup.html.form.select.SelectOption; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.springframework.security.core.context.SecurityContextHolder; import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService; import de.tudarmstadt.ukp.clarin.webanno.api.UserDao; import de.tudarmstadt.ukp.clarin.webanno.api.dao.SecurityUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotatorModel; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.User; /** * A panel used as Open dialog. It Lists all projects a user is member of for annotation/curation * and associated documents * * */ public class OpenModalWindowPanel extends Panel { private static final long serialVersionUID = 1299869948010875439L; @SpringBean(name = "documentRepository") private RepositoryService repository; @SpringBean(name = "userRepository") private UserDao userRepository; // Project list, Document List and buttons List, contained in separet forms private final ProjectSelectionForm projectSelectionForm; private final DocumentSelectionForm documentSelectionForm; private final ButtonsForm buttonsForm; private Select<SourceDocument> documentSelection; // The first project - selected by default private Project selectedProject; // The first document in the project // auto selected in the first time. private SourceDocument selectedDocument; private final String username; private final User user; // Dialog is for annotation or curation private final Mode mode; private final BratAnnotatorModel bModel; private List<Project> allowedProject = new ArrayList<Project>(); private List<Project> projectesWithFinishedAnnos; private Map<Project, String> projectColors = new HashMap<Project, String>(); public OpenModalWindowPanel(String aId, BratAnnotatorModel aBModel, ModalWindow aModalWindow, Mode aSubject) { super(aId); this.mode = aSubject; username = SecurityContextHolder.getContext().getAuthentication().getName(); user = userRepository.get(username); if (mode.equals(Mode.CURATION)) { projectesWithFinishedAnnos = repository.listProjectsWithFinishedAnnos(); } if (getAllowedProjects().size() > 0) { selectedProject = getAllowedProjects().get(0); } this.bModel = aBModel; projectSelectionForm = new ProjectSelectionForm("projectSelectionForm"); documentSelectionForm = new DocumentSelectionForm("documentSelectionForm", aModalWindow); buttonsForm = new ButtonsForm("buttonsForm", aModalWindow); add(buttonsForm); add(projectSelectionForm); add(documentSelectionForm); } private class ProjectSelectionForm extends Form<SelectionModel> { private static final long serialVersionUID = -1L; private Select<Project> projectSelection; public ProjectSelectionForm(String id) { super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel())); projectSelection = new Select<Project>("projectSelection"); ListView<Project> lv = new ListView<Project>("projects", new LoadableDetachableModel<List<Project>>() { private static final long serialVersionUID = 1L; @Override protected List<Project> load() { return getAllowedProjects(); } }) { private static final long serialVersionUID = 8901519963052692214L; @Override protected void populateItem(final ListItem<Project> item) { String color = projectColors.get(item.getModelObject()); if (color == null) { color = "#008000";// not in curation } item.add(new SelectOption<Project>("project", new Model<Project>(item .getModelObject())) { private static final long serialVersionUID = 3095089418860168215L; @Override public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { replaceComponentTagBody(markupStream, openTag, item.getModelObject() .getName()); } }.add(new AttributeModifier("style", "color:" + color + ";"))); } }; add(projectSelection.add(lv)); projectSelection.setOutputMarkupId(true); projectSelection.add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { selectedProject = getModelObject().projectSelection; // Remove selected document from other project selectedDocument = null; documentSelection.setModelObject(selectedDocument); aTarget.add(documentSelection); } }).add(new AjaxEventBehavior("ondblclick") { private static final long serialVersionUID = 1L; @Override protected void onEvent(final AjaxRequestTarget aTarget) { selectedProject = getModelObject().projectSelection; // Remove selected document from other project selectedDocument = null; aTarget.add(documentSelection.setOutputMarkupId(true)); } }); } } public List<Project> getAllowedProjects() { List<Project> allowedProject = new ArrayList<Project>(); switch (mode) { case ANNOTATION: for (Project project : repository.listProjects()) { if (SecurityUtil.isMember(project, repository, user) && project.getMode().equals(Mode.ANNOTATION)) { allowedProject.add(project); } } break; case CURATION: for (Project project : repository.listProjects()) { if (SecurityUtil.isCurator(project, repository, user)) { allowedProject.add(project); if (projectesWithFinishedAnnos.contains(project)) { projectColors.put(project, "#008000"); } else { projectColors.put(project, "#99cc99"); } } } break; case CORRECTION: for (Project project : repository.listProjects()) { if (SecurityUtil.isMember(project, repository, user) && project.getMode().equals(Mode.CORRECTION)) { allowedProject.add(project); } } break; case AUTOMATION: for (Project project : repository.listProjects()) { if (SecurityUtil.isMember(project, repository, user) && project.getMode().equals(Mode.AUTOMATION)) { allowedProject.add(project); } } break; default: break; } return allowedProject; } private class SelectionModel implements Serializable { private static final long serialVersionUID = -1L; private Project projectSelection; private SourceDocument documentSelection; } private class DocumentSelectionForm extends Form<SelectionModel> { private static final long serialVersionUID = -1L; public DocumentSelectionForm(String id, final ModalWindow modalWindow) { super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel())); final Map<SourceDocument, String> documnetColors = new HashMap<SourceDocument, String>(); documentSelection = new Select<SourceDocument>("documentSelection"); ListView<SourceDocument> lv = new ListView<SourceDocument>("documents", new LoadableDetachableModel<List<SourceDocument>>() { private static final long serialVersionUID = 1L; @Override protected List<SourceDocument> load() { List<SourceDocument> allDocuments = listDOcuments(documnetColors); return allDocuments; } }) { private static final long serialVersionUID = 8901519963052692214L; @Override protected void populateItem(final ListItem<SourceDocument> item) { item.add(new SelectOption<SourceDocument>("document", new Model<SourceDocument>(item.getModelObject())) { private static final long serialVersionUID = 3095089418860168215L; @Override public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { replaceComponentTagBody(markupStream, openTag, item.getModelObject() .getName()); } }.add(new AttributeModifier("style", "color:" + documnetColors.get(item.getModelObject()) + ";"))); } }; add(documentSelection.add(lv)); documentSelection.setOutputMarkupId(true); documentSelection.add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { selectedDocument = getModelObject().documentSelection; } }).add(new AjaxEventBehavior("ondblclick") { private static final long serialVersionUID = 1L; @Override protected void onEvent(final AjaxRequestTarget aTarget) { // do not use this default layer in that other project if(bModel.getProject()!=null){ if(!bModel.getProject().equals(selectedProject)){ bModel.setDefaultAnnotationLayer(null); } } if (selectedProject != null && selectedDocument != null) { bModel.setProject(selectedProject); bModel.setDocument(selectedDocument); modalWindow.close(aTarget); } } }); } } private List<SourceDocument> listDOcuments(final Map<SourceDocument, String> states) { if (selectedProject == null) { return new ArrayList<SourceDocument>(); } List<SourceDocument> allDocuments = repository.listSourceDocuments(selectedProject); // Remove from the list source documents that are in IGNORE state OR // that do not have at least one annotation document marked as // finished for curation dialog List<SourceDocument> excludeDocuments = new ArrayList<SourceDocument>(); for (SourceDocument sourceDocument : allDocuments) { switch (mode) { case ANNOTATION: case AUTOMATION: case CORRECTION: if (sourceDocument.isTrainingDocument()) { excludeDocuments.add(sourceDocument); continue; } if (repository.existsAnnotationDocument(sourceDocument, user)) { AnnotationDocument anno = repository .getAnnotationDocument(sourceDocument, user); if (anno.getState().equals(AnnotationDocumentState.IGNORE)) { excludeDocuments.add(sourceDocument); } else if (anno.getState().equals(AnnotationDocumentState.FINISHED)) { states.put(sourceDocument, "red"); } else if (anno.getState().equals(AnnotationDocumentState.IN_PROGRESS)) { states.put(sourceDocument, "blue"); } } break; case CURATION: if (!repository.existFinishedDocument(sourceDocument, selectedProject)) { excludeDocuments.add(sourceDocument); } else if (sourceDocument.getState().equals(SourceDocumentState.CURATION_FINISHED)) { states.put(sourceDocument, "red"); } else if (sourceDocument.getState().equals(SourceDocumentState.CURATION_IN_PROGRESS)) { states.put(sourceDocument, "blue"); } break; default: break; } } allDocuments.removeAll(excludeDocuments); return allDocuments; } private class ButtonsForm extends Form<Void> { private static final long serialVersionUID = -1879323194964417564L; public ButtonsForm(String id, final ModalWindow modalWindow) { super(id); add(new AjaxSubmitLink("openButton") { private static final long serialVersionUID = -755759008587787147L; @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { if (selectedProject == null) { aTarget.appendJavaScript("alert('No project is selected!')"); // If there is // no project // at all } else if (selectedDocument == null) { if (repository.existsFinishedAnnotation(selectedProject)) { aTarget.appendJavaScript("alert('Please select a document for project: " + selectedProject.getName() + "')"); } else { aTarget.appendJavaScript("alert('There is no document that is ready for curation yet for project: " + selectedProject.getName() + "')"); } } else { // do not use this default layer in that other project if(bModel.getProject()!=null){ if(!bModel.getProject().equals(selectedProject)){ bModel.setDefaultAnnotationLayer(null); } } bModel.setProject(selectedProject); bModel.setDocument(selectedDocument); modalWindow.close(aTarget); } } @Override protected void onError(AjaxRequestTarget aTarget, Form<?> aForm) { } }); add(new AjaxLink<Void>("cancelButton") { private static final long serialVersionUID = 7202600912406469768L; @Override public void onClick(AjaxRequestTarget aTarget) { projectSelectionForm.detach(); documentSelectionForm.detach(); if (mode.equals(Mode.CURATION)) { bModel.setDocument(null); // on cancel, go welcomePage } onCancel(aTarget); modalWindow.close(aTarget); } }); } } protected void onCancel(AjaxRequestTarget aTarget) { } }
webanno-webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/dialog/OpenModalWindowPanel.java
/******************************************************************************* * Copyright 2012 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tudarmstadt.ukp.clarin.webanno.webapp.dialog; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.wicket.AttributeModifier; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.extensions.markup.html.form.select.Select; import org.apache.wicket.extensions.markup.html.form.select.SelectOption; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.MarkupStream; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.springframework.security.core.context.SecurityContextHolder; import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService; import de.tudarmstadt.ukp.clarin.webanno.api.UserDao; import de.tudarmstadt.ukp.clarin.webanno.api.dao.SecurityUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotatorModel; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.User; /** * A panel used as Open dialog. It Lists all projects a user is member of for annotation/curation * and associated documents * * */ public class OpenModalWindowPanel extends Panel { private static final long serialVersionUID = 1299869948010875439L; @SpringBean(name = "documentRepository") private RepositoryService repository; @SpringBean(name = "userRepository") private UserDao userRepository; // Project list, Document List and buttons List, contained in separet forms private final ProjectSelectionForm projectSelectionForm; private final DocumentSelectionForm documentSelectionForm; private final ButtonsForm buttonsForm; private Select<SourceDocument> documentSelection; // The first project - selected by default private Project selectedProject; // The first document in the project // auto selected in the first time. private SourceDocument selectedDocument; private final String username; private final User user; // Dialog is for annotation or curation private final Mode mode; private final BratAnnotatorModel bratAnnotatorModel; private List<Project> allowedProject = new ArrayList<Project>(); private List<Project> projectesWithFinishedAnnos; private Map<Project, String> projectColors = new HashMap<Project, String>(); public OpenModalWindowPanel(String aId, BratAnnotatorModel aBratAnnotatorModel, ModalWindow aModalWindow, Mode aSubject) { super(aId); this.mode = aSubject; username = SecurityContextHolder.getContext().getAuthentication().getName(); user = userRepository.get(username); if (mode.equals(Mode.CURATION)) { projectesWithFinishedAnnos = repository.listProjectsWithFinishedAnnos(); } if (getAllowedProjects().size() > 0) { selectedProject = getAllowedProjects().get(0); } this.bratAnnotatorModel = aBratAnnotatorModel; projectSelectionForm = new ProjectSelectionForm("projectSelectionForm"); documentSelectionForm = new DocumentSelectionForm("documentSelectionForm", aModalWindow); buttonsForm = new ButtonsForm("buttonsForm", aModalWindow); add(buttonsForm); add(projectSelectionForm); add(documentSelectionForm); } private class ProjectSelectionForm extends Form<SelectionModel> { private static final long serialVersionUID = -1L; private Select<Project> projectSelection; public ProjectSelectionForm(String id) { super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel())); projectSelection = new Select<Project>("projectSelection"); ListView<Project> lv = new ListView<Project>("projects", new LoadableDetachableModel<List<Project>>() { private static final long serialVersionUID = 1L; @Override protected List<Project> load() { return getAllowedProjects(); } }) { private static final long serialVersionUID = 8901519963052692214L; @Override protected void populateItem(final ListItem<Project> item) { String color = projectColors.get(item.getModelObject()); if (color == null) { color = "#008000";// not in curation } item.add(new SelectOption<Project>("project", new Model<Project>(item .getModelObject())) { private static final long serialVersionUID = 3095089418860168215L; @Override public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { replaceComponentTagBody(markupStream, openTag, item.getModelObject() .getName()); } }.add(new AttributeModifier("style", "color:" + color + ";"))); } }; add(projectSelection.add(lv)); projectSelection.setOutputMarkupId(true); projectSelection.add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { selectedProject = getModelObject().projectSelection; // Remove selected document from other project selectedDocument = null; documentSelection.setModelObject(selectedDocument); aTarget.add(documentSelection); } }).add(new AjaxEventBehavior("ondblclick") { private static final long serialVersionUID = 1L; @Override protected void onEvent(final AjaxRequestTarget aTarget) { selectedProject = getModelObject().projectSelection; // Remove selected document from other project selectedDocument = null; aTarget.add(documentSelection.setOutputMarkupId(true)); } }); } } public List<Project> getAllowedProjects() { List<Project> allowedProject = new ArrayList<Project>(); switch (mode) { case ANNOTATION: for (Project project : repository.listProjects()) { if (SecurityUtil.isMember(project, repository, user) && project.getMode().equals(Mode.ANNOTATION)) { allowedProject.add(project); } } break; case CURATION: for (Project project : repository.listProjects()) { if (SecurityUtil.isCurator(project, repository, user)) { allowedProject.add(project); if (projectesWithFinishedAnnos.contains(project)) { projectColors.put(project, "#008000"); } else { projectColors.put(project, "#99cc99"); } } } break; case CORRECTION: for (Project project : repository.listProjects()) { if (SecurityUtil.isMember(project, repository, user) && project.getMode().equals(Mode.CORRECTION)) { allowedProject.add(project); } } break; case AUTOMATION: for (Project project : repository.listProjects()) { if (SecurityUtil.isMember(project, repository, user) && project.getMode().equals(Mode.AUTOMATION)) { allowedProject.add(project); } } break; default: break; } return allowedProject; } private class SelectionModel implements Serializable { private static final long serialVersionUID = -1L; private Project projectSelection; private SourceDocument documentSelection; } private class DocumentSelectionForm extends Form<SelectionModel> { private static final long serialVersionUID = -1L; public DocumentSelectionForm(String id, final ModalWindow modalWindow) { super(id, new CompoundPropertyModel<SelectionModel>(new SelectionModel())); final Map<SourceDocument, String> documnetColors = new HashMap<SourceDocument, String>(); documentSelection = new Select<SourceDocument>("documentSelection"); ListView<SourceDocument> lv = new ListView<SourceDocument>("documents", new LoadableDetachableModel<List<SourceDocument>>() { private static final long serialVersionUID = 1L; @Override protected List<SourceDocument> load() { List<SourceDocument> allDocuments = listDOcuments(documnetColors); return allDocuments; } }) { private static final long serialVersionUID = 8901519963052692214L; @Override protected void populateItem(final ListItem<SourceDocument> item) { item.add(new SelectOption<SourceDocument>("document", new Model<SourceDocument>(item.getModelObject())) { private static final long serialVersionUID = 3095089418860168215L; @Override public void onComponentTagBody(MarkupStream markupStream, ComponentTag openTag) { replaceComponentTagBody(markupStream, openTag, item.getModelObject() .getName()); } }.add(new AttributeModifier("style", "color:" + documnetColors.get(item.getModelObject()) + ";"))); } }; add(documentSelection.add(lv)); documentSelection.setOutputMarkupId(true); documentSelection.add(new OnChangeAjaxBehavior() { private static final long serialVersionUID = 1L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { selectedDocument = getModelObject().documentSelection; } }).add(new AjaxEventBehavior("ondblclick") { private static final long serialVersionUID = 1L; @Override protected void onEvent(final AjaxRequestTarget aTarget) { if (selectedProject != null && selectedDocument != null) { bratAnnotatorModel.setProject(selectedProject); bratAnnotatorModel.setDocument(selectedDocument); modalWindow.close(aTarget); } } }); } } private List<SourceDocument> listDOcuments(final Map<SourceDocument, String> states) { if (selectedProject == null) { return new ArrayList<SourceDocument>(); } List<SourceDocument> allDocuments = repository.listSourceDocuments(selectedProject); // Remove from the list source documents that are in IGNORE state OR // that do not have at least one annotation document marked as // finished for curation dialog List<SourceDocument> excludeDocuments = new ArrayList<SourceDocument>(); for (SourceDocument sourceDocument : allDocuments) { switch (mode) { case ANNOTATION: case AUTOMATION: case CORRECTION: if (sourceDocument.isTrainingDocument()) { excludeDocuments.add(sourceDocument); continue; } if (repository.existsAnnotationDocument(sourceDocument, user)) { AnnotationDocument anno = repository .getAnnotationDocument(sourceDocument, user); if (anno.getState().equals(AnnotationDocumentState.IGNORE)) { excludeDocuments.add(sourceDocument); } else if (anno.getState().equals(AnnotationDocumentState.FINISHED)) { states.put(sourceDocument, "red"); } else if (anno.getState().equals(AnnotationDocumentState.IN_PROGRESS)) { states.put(sourceDocument, "blue"); } } break; case CURATION: if (!repository.existFinishedDocument(sourceDocument, selectedProject)) { excludeDocuments.add(sourceDocument); } else if (sourceDocument.getState().equals(SourceDocumentState.CURATION_FINISHED)) { states.put(sourceDocument, "red"); } else if (sourceDocument.getState().equals(SourceDocumentState.CURATION_IN_PROGRESS)) { states.put(sourceDocument, "blue"); } break; default: break; } } allDocuments.removeAll(excludeDocuments); return allDocuments; } private class ButtonsForm extends Form<Void> { private static final long serialVersionUID = -1879323194964417564L; public ButtonsForm(String id, final ModalWindow modalWindow) { super(id); add(new AjaxSubmitLink("openButton") { private static final long serialVersionUID = -755759008587787147L; @Override protected void onSubmit(AjaxRequestTarget aTarget, Form<?> aForm) { if (selectedProject == null) { aTarget.appendJavaScript("alert('No project is selected!')"); // If there is // no project // at all } else if (selectedDocument == null) { if (repository.existsFinishedAnnotation(selectedProject)) { aTarget.appendJavaScript("alert('Please select a document for project: " + selectedProject.getName() + "')"); } else { aTarget.appendJavaScript("alert('There is no document that is ready for curation yet for project: " + selectedProject.getName() + "')"); } } else { bratAnnotatorModel.setProject(selectedProject); bratAnnotatorModel.setDocument(selectedDocument); modalWindow.close(aTarget); } } @Override protected void onError(AjaxRequestTarget aTarget, Form<?> aForm) { } }); add(new AjaxLink<Void>("cancelButton") { private static final long serialVersionUID = 7202600912406469768L; @Override public void onClick(AjaxRequestTarget aTarget) { projectSelectionForm.detach(); documentSelectionForm.detach(); if (mode.equals(Mode.CURATION)) { bratAnnotatorModel.setDocument(null); // on cancel, go welcomePage } onCancel(aTarget); modalWindow.close(aTarget); } }); } } protected void onCancel(AjaxRequestTarget aTarget) { } }
#141 - github - When a project is changed, clear the default annotation layer
webanno-webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/dialog/OpenModalWindowPanel.java
#141 - github - When a project is changed, clear the default annotation layer
<ide><path>ebanno-webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/dialog/OpenModalWindowPanel.java <ide> // Dialog is for annotation or curation <ide> <ide> private final Mode mode; <del> private final BratAnnotatorModel bratAnnotatorModel; <add> private final BratAnnotatorModel bModel; <ide> <ide> private List<Project> allowedProject = new ArrayList<Project>(); <ide> private List<Project> projectesWithFinishedAnnos; <ide> private Map<Project, String> projectColors = new HashMap<Project, String>(); <ide> <del> public OpenModalWindowPanel(String aId, BratAnnotatorModel aBratAnnotatorModel, <add> public OpenModalWindowPanel(String aId, BratAnnotatorModel aBModel, <ide> ModalWindow aModalWindow, Mode aSubject) <ide> { <ide> super(aId); <ide> selectedProject = getAllowedProjects().get(0); <ide> } <ide> <del> this.bratAnnotatorModel = aBratAnnotatorModel; <add> this.bModel = aBModel; <ide> projectSelectionForm = new ProjectSelectionForm("projectSelectionForm"); <ide> documentSelectionForm = new DocumentSelectionForm("documentSelectionForm", aModalWindow); <ide> buttonsForm = new ButtonsForm("buttonsForm", aModalWindow); <ide> @Override <ide> protected void onEvent(final AjaxRequestTarget aTarget) <ide> { <add> // do not use this default layer in that other project <add> if(bModel.getProject()!=null){ <add> if(!bModel.getProject().equals(selectedProject)){ <add> bModel.setDefaultAnnotationLayer(null); <add> } <add> } <ide> if (selectedProject != null && selectedDocument != null) { <del> bratAnnotatorModel.setProject(selectedProject); <del> bratAnnotatorModel.setDocument(selectedDocument); <add> bModel.setProject(selectedProject); <add> bModel.setDocument(selectedDocument); <ide> modalWindow.close(aTarget); <ide> } <ide> } <ide> } <ide> } <ide> else { <del> bratAnnotatorModel.setProject(selectedProject); <del> bratAnnotatorModel.setDocument(selectedDocument); <add> // do not use this default layer in that other project <add> if(bModel.getProject()!=null){ <add> if(!bModel.getProject().equals(selectedProject)){ <add> bModel.setDefaultAnnotationLayer(null); <add> } <add> } <add> <add> bModel.setProject(selectedProject); <add> bModel.setDocument(selectedDocument); <ide> modalWindow.close(aTarget); <ide> } <ide> } <ide> projectSelectionForm.detach(); <ide> documentSelectionForm.detach(); <ide> if (mode.equals(Mode.CURATION)) { <del> bratAnnotatorModel.setDocument(null); // on cancel, go welcomePage <add> bModel.setDocument(null); // on cancel, go welcomePage <ide> } <ide> onCancel(aTarget); <ide> modalWindow.close(aTarget);
Java
mit
6b4d95cb795a57287d6fcc9a09637824a5429325
0
aJanuary/argparse4j,aJanuary/argparse4j,aJanuary/argparse4j,aJanuary/argparse4j
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.argparse4j.internal; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Returns the column width of the command line terminal from which this program * was started. Typically the column width is around 80 characters or so. * * Currently works on Linux and OSX. * * Returns -1 if the column width cannot be determined for some reason. */ public class TerminalWidth { private static final int UNKNOWN_WIDTH = -1; public static void main(String[] args) { System.out.println("terminalWidth: " + new TerminalWidth().getTerminalWidth()); } public int getTerminalWidth() { String width = System.getenv("COLUMNS"); if (width != null) { try { return Integer.parseInt(width); } catch (NumberFormatException e) { return UNKNOWN_WIDTH; } } try { return getTerminalWidth2(); } catch (IOException e) { return UNKNOWN_WIDTH; } } // see // http://grokbase.com/t/gg/clojure/127qwgscvc/how-do-you-determine-terminal-console-width-in-%60lein-repl%60 private int getTerminalWidth2() throws IOException { String osName = System.getProperty("os.name"); boolean isOSX = osName.startsWith("Mac OS X"); boolean isLinux = osName.startsWith("Linux") || osName.startsWith("LINUX"); if (!isLinux && !isOSX) { return UNKNOWN_WIDTH; // actually, this might also work on Solaris // but this hasn't been tested } ProcessBuilder builder = new ProcessBuilder(which("sh").toString(), "-c", "stty -a < /dev/tty"); builder.redirectErrorStream(true); Process process = builder.start(); InputStream in = process.getInputStream(); ByteArrayOutputStream resultBytes = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) >= 0) { resultBytes.write(buf, 0, len); } } finally { in.close(); } String result = new String(resultBytes.toByteArray()); // System.out.println("result=" + result); try { if (process.waitFor() != 0) { return UNKNOWN_WIDTH; } } catch (InterruptedException e) { return UNKNOWN_WIDTH; } String pattern; if (isOSX) { // Extract columns from a line such as this: // speed 9600 baud; 39 rows; 80 columns; pattern = "(\\d+) columns"; } else { // Extract columns from a line such as this: // speed 9600 baud; rows 50; columns 83; line = 0; pattern = "columns (\\d+)"; } Matcher m = Pattern.compile(pattern).matcher(result); if (!m.find()) { return UNKNOWN_WIDTH; } result = m.group(1); try { return Integer.parseInt(result); } catch (NumberFormatException e) { return UNKNOWN_WIDTH; } } private File which(String cmd) throws IOException { String path = System.getenv("PATH"); if (path != null) { for (String dir : path.split(Pattern.quote(File.pathSeparator))) { File command = new File(dir.trim(), cmd); if (command.canExecute()) { return command.getAbsoluteFile(); } } } throw new IOException("No command '" + cmd + "' on path " + path); } }
src/main/java/net/sourceforge/argparse4j/internal/TerminalWidth.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.argparse4j.internal; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Returns the column width of the command line terminal from which this program * was started. Typically the column width is around 80 characters or so. * * Currently works on Linux and OSX. * * Returns -1 if the column width cannot be determined for some reason. */ public class TerminalWidth { private static final int UNKNOWN_WIDTH = -1; public static void main(String[] args) { System.out.println("terminalWidth: " + new TerminalWidth().getTerminalWidth()); } public int getTerminalWidth() { String width = System.getenv("COLUMNS"); if (width != null) { try { return Integer.parseInt(width); } catch (NumberFormatException e) { return UNKNOWN_WIDTH; } } try { return getTerminalWidth2(); } catch (IOException e) { return UNKNOWN_WIDTH; } } // see // http://grokbase.com/t/gg/clojure/127qwgscvc/how-do-you-determine-terminal-console-width-in-%60lein-repl%60 private int getTerminalWidth2() throws IOException { String osName = System.getProperty("os.name"); boolean isOSX = osName.startsWith("Mac OS X"); boolean isLinux = osName.startsWith("Linux") || osName.startsWith("LINUX"); if (!isLinux && !isOSX) { return UNKNOWN_WIDTH; // actually, this might also work on Solaris // but this hasn't been tested } ProcessBuilder builder = new ProcessBuilder(which("sh").toString(), "-c", "stty -a < /dev/tty"); builder.redirectErrorStream(true); Process process = builder.start(); InputStream in = process.getInputStream(); ByteArrayOutputStream resultBytes = new ByteArrayOutputStream(); try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) >= 0) { resultBytes.write(buf, 0, len); } } finally { in.close(); } String result = new String(resultBytes.toByteArray()); // System.out.println("result=" + result); try { if (process.waitFor() != 0) { return UNKNOWN_WIDTH; } } catch (InterruptedException e) { return UNKNOWN_WIDTH; } String pattern; if (isOSX) { // Extract columns from a line such as this: // speed 9600 baud; 39 rows; 80 columns; pattern = "(\\d+) columns"; } else { // Extract columns from a line such as this: // speed 9600 baud; rows 50; columns 83; line = 0; pattern = "columns (\\d+)"; } Matcher m = Pattern.compile(pattern).matcher(result); if (!m.find()) { return UNKNOWN_WIDTH; } result = m.group(1); try { return Integer.parseInt(result); } catch (NumberFormatException e) { return UNKNOWN_WIDTH; } } private File which(String cmd) throws IOException { String path = System.getenv("PATH"); for (String dir : path.split(Pattern.quote(File.pathSeparator))) { File command = new File(dir.trim(), cmd); if (command.canExecute()) { return command.getAbsoluteFile(); } } throw new IOException("No command '" + cmd + "' on path " + path); } }
fix for NPE if there is no PATH env var
src/main/java/net/sourceforge/argparse4j/internal/TerminalWidth.java
fix for NPE if there is no PATH env var
<ide><path>rc/main/java/net/sourceforge/argparse4j/internal/TerminalWidth.java <ide> <ide> private File which(String cmd) throws IOException { <ide> String path = System.getenv("PATH"); <del> for (String dir : path.split(Pattern.quote(File.pathSeparator))) { <del> File command = new File(dir.trim(), cmd); <del> if (command.canExecute()) { <del> return command.getAbsoluteFile(); <del> } <add> if (path != null) { <add> for (String dir : path.split(Pattern.quote(File.pathSeparator))) { <add> File command = new File(dir.trim(), cmd); <add> if (command.canExecute()) { <add> return command.getAbsoluteFile(); <add> } <add> } <ide> } <ide> throw new IOException("No command '" + cmd + "' on path " + path); <ide> }
JavaScript
apache-2.0
ed0b9f2c4cbc50296f41e7446343ce708b658771
0
TanayParikh/foam2,TanayParikh/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,jacksonic/vjlofvhjfgm,foam-framework/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,TanayParikh/foam2,TanayParikh/foam2,foam-framework/foam2,foam-framework/foam2
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ describe('FlowControl', function() { it('stops', function() { var fc = foam.dao.FlowControl.create(); fc.stop(); expect(fc.stopped).toEqual(true); }); it('errors', function() { var fc = foam.dao.FlowControl.create(); fc.error("error"); expect(fc.errorEvt).toEqual("error"); }); }); describe('Sink Interface', function() { it('covers empty methods', function() { var sinkMethods = foam.dao.Sink.getAxiomsByClass(foam.core.Method).map( function(m) { return m.code(); } ); }); }); describe('AbstractSink', function() { it('covers empty methods', function() { var sink = foam.dao.AbstractSink.create(); sink.put(); sink.remove(); sink.eof(); sink.error(); sink.reset(); }); }); describe('PredicatedSink', function() { beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); foam.CLASS({ name: 'TestPredicate', implements: [ 'foam.mlang.predicate.Predicate' ], properties: [ 'calledWith', 'allow', 'f' ] }); }); it('only puts on a match', function() { var fakePredicate = TestPredicate.create({ calledWith: null, allow: false, f: function(o) { this.calledWith = o; if ( this.allow ) return true; } }, foam.__context__); var sink = foam.dao.PredicatedSink.create({ predicate: fakePredicate, delegate: foam.dao.ArraySink.create() }); var a = test.CompA.create({ id: 0, a: 3 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 5 }, foam.__context__); sink.put(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.a.length).toEqual(0); fakePredicate.allow = true; sink.put(b); expect(fakePredicate.calledWith).toEqual(b); }); it('only removes on a match', function() { var fakePredicate = TestPredicate.create({ calledWith: null, allow: false, f: function(o) { this.calledWith = o; if ( this.allow ) return true; } }, foam.__context__); var sink = foam.dao.PredicatedSink.create({ predicate: fakePredicate, delegate: foam.dao.ArrayDAO.create() }); var a = test.CompA.create({ id: 0, a: 3 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 5 }, foam.__context__); fakePredicate.allow = true; sink.put(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.array.length).toEqual(1); fakePredicate.calledWith = null; fakePredicate.allow = false; sink.remove(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.array.length).toEqual(1); fakePredicate.calledWith = null; fakePredicate.allow = true; sink.remove(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.array.length).toEqual(0); }); }); describe('QuickSink', function() { it('calls given functions', function() { function mockCallP(o) { this.calledPut = o; } function mockCallR(o) { this.calledRemove = o; } function mockCallE(o) { this.calledEof = o; } function mockCallEr(o) { this.calledError = o; } function mockCallRe(o) { this.calledReset = o; } var sink = foam.dao.QuickSink.create({ putFn: mockCallP, removeFn: mockCallR, eofFn: mockCallE, errorFn: mockCallEr, resetFn: mockCallRe }); sink.put("putcall"); sink.remove("removecall"); sink.eof("eofcall"); sink.error("errorcall"); sink.reset("resetcall"); expect(sink.calledPut).toEqual("putcall"); expect(sink.calledRemove).toEqual("removecall"); expect(sink.calledEof).toEqual("eofcall"); expect(sink.calledError).toEqual("errorcall"); expect(sink.calledReset).toEqual("resetcall"); }); }); describe('LimitedSink', function() { beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); }); it('only puts when below limit', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.put(a); sink.put(b); sink.put(c); sink.put(d); expect(sink.delegate.array.length).toEqual(3); expect(sink.delegate.array[0].id).toEqual(0); expect(sink.delegate.array[1].id).toEqual(1); expect(sink.delegate.array[2].id).toEqual(2); }); it('only removes when below limit', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.delegate.put(a); sink.delegate.put(b); sink.delegate.put(c); sink.delegate.put(d); sink.remove(a); sink.remove(b); sink.remove(c); sink.remove(d); expect(sink.delegate.array.length).toEqual(1); expect(sink.delegate.array[0].id).toEqual(3); }); it('put stops flow control', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }); var fc = foam.dao.FlowControl.create(); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.put(a, fc); expect(fc.stopped).toEqual(false); sink.put(b, fc); expect(fc.stopped).toEqual(false); sink.put(c, fc); expect(fc.stopped).toEqual(false); sink.put(d, fc); expect(fc.stopped).toEqual(true); }); it('remove stops flow control', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }); var fc = foam.dao.FlowControl.create(); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.delegate.put(a); sink.delegate.put(b); sink.delegate.put(c); sink.delegate.put(d); sink.remove(a, fc); expect(fc.stopped).toEqual(false); sink.remove(b, fc); expect(fc.stopped).toEqual(false); sink.remove(c, fc); expect(fc.stopped).toEqual(false); sink.remove(d, fc); expect(fc.stopped).toEqual(true); }); }); describe('SkipSink', function() { beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); }); it('only puts when above limit', function() { var sink = foam.dao.SkipSink.create({ skip: 2, delegate: foam.dao.ArrayDAO.create() }); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.put(a); sink.put(b); sink.put(c); sink.put(d); expect(sink.delegate.array.length).toEqual(2); expect(sink.delegate.array[0].id).toEqual(2); expect(sink.delegate.array[1].id).toEqual(3); }); it('only removes when below limit', function() { var sink = foam.dao.SkipSink.create({ skip: 2, delegate: foam.dao.ArrayDAO.create() }); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.delegate.put(a); sink.delegate.put(b); sink.delegate.put(c); sink.delegate.put(d); sink.remove(a); sink.remove(b); sink.remove(c); sink.remove(d); expect(sink.delegate.array.length).toEqual(2); expect(sink.delegate.array[0].id).toEqual(0); expect(sink.delegate.array[1].id).toEqual(1); }); }); if ( typeof localStorage === "undefined" || localStorage === null ) { var LocalStorage = require('node-localstorage').LocalStorage; localStorage = new LocalStorage('./tmp'); } describe('LocalStorageDAO', function() { var a; var a2; var b; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a', 'b' ] }); foam.CLASS({ package: 'test', name: 'CompB', properties: [ 'id', 'b' ] }); a = test.CompA.create({id: 4, a:1, b:2}, foam.__context__); a2 = test.CompA.create({id: 6, a:'hello', b:6}, foam.__context__); b = test.CompB.create({id: 8, b:a2}, foam.__context__); }); afterEach(function() { a = a2 = b = null; }); it('can be created', function() { foam.dao.LocalStorageDAO.create({ name: '_test_LS_' }); }); it('reads back written data', function() { var dao = foam.dao.LocalStorageDAO.create({ name: '_test_LS_' }); dao.put(a); dao.put(a2); dao.put(b); // a new local storage dao with the same store name // TODO: guarantee file sync so we can test this synchronously //var dao2 = foam.dao.LocalStorageDAO.create({ name: '_test_LS_' }); var dao2 = dao; // still checks deserialization var result = foam.dao.ArraySink.create(); dao2.select(result); expect(result.a[0]).toEqual(a); expect(result.a[1]).toEqual(a2); expect(result.a[2]).toEqual(b); expect(result.a[2].stringify()).toEqual(b.stringify()); }); // Run the generic suite of DAO tests against it. genericDAOTestBattery(function(model) { localStorage.removeItem('_test_LS_generic_'); return Promise.resolve(foam.dao.LocalStorageDAO.create({ name: '_test_LS_generic_', of: model })); }); afterAll(function() { localStorage.clear(); }); // TODO: test nested objects when foam.json supports them }); describe('ArrayDAO', function() { genericDAOTestBattery(function(model) { return Promise.resolve(foam.dao.ArrayDAO.create({ of: model })); }); }); if ( foam.dao.IDBDAO ) { describe('IDBDAO', function() { genericDAOTestBattery(function(model) { var dao = foam.dao.IDBDAO.create({ of: model }); return dao.removeAll().then(function() { return Promise.resolve(dao); } ); }); }); } describe('MDAO', function() { genericDAOTestBattery(function(model) { return Promise.resolve(foam.dao.MDAO.create({ of: model })); }); }); // NOTE: not all generic tests are applicable, as LazyCacheDAO does not // offer a way to immediately sync results. It will eagerly deliver // partial results and update eventually. Perhaps a different set // of genericDAOTestBattery for this kind of partial-result case. // describe('LazyCacheDAO-cacheOnSelect-async', function() { // // test caching against an IDBDAO remote and MDAO cache. // genericDAOTestBattery(function(model) { // var idbDAO = test.helpers.RandomDelayDAO.create({ // of: model, // delays: [ 5, 20, 1, 10, 20, 5, 20 ] // }); // var mDAO = test.helpers.RandomDelayDAO.create({ // of: model, // delays: [ 5, 20, 1, 10, 20, 5, 20 ] // }); // return Promise.resolve(foam.dao.LazyCacheDAO.create({ // delegate: idbDAO, // cache: mDAO, // cacheOnSelect: true // })); // }); // }); describe('LazyCacheDAO-cacheOnSelect', function() { // test caching against an IDBDAO remote and MDAO cache. genericDAOTestBattery(function(model) { var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) .create({ name: '_test_lazyCache_', of: model }); return idbDAO.removeAll().then(function() { var mDAO = foam.dao.MDAO.create({ of: model }); return foam.dao.LazyCacheDAO.create({ delegate: idbDAO, cache: mDAO, cacheOnSelect: true }); }); }); }); describe('LazyCacheDAO', function() { // test caching against an IDBDAO remote and MDAO cache. genericDAOTestBattery(function(model) { var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) .create({ name: '_test_lazyCache_', of: model }); return idbDAO.removeAll().then(function() { var mDAO = foam.dao.MDAO.create({ of: model }); return foam.dao.LazyCacheDAO.create({ delegate: idbDAO, cache: mDAO, cacheOnSelect: false }); }); }); }); describe('CachingDAO', function() { genericDAOTestBattery(function(model) { var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) .create({ name: '_test_readCache_', of: model }); return idbDAO.removeAll().then(function() { var mDAO = foam.dao.MDAO.create({ of: model }); return foam.dao.CachingDAO.create({ src: idbDAO, cache: mDAO }); }); }); }); describe('CachingDAO-async', function() { genericDAOTestBattery(function(model) { var idbDAO = test.helpers.RandomDelayDAO.create({ of: model, delays: [ 30, 5, 20, 1, 10, 20, 5, 20 ] }, foam.__context__); return idbDAO.removeAll().then(function() { var mDAO = test.helpers.RandomDelayDAO.create({ of: model, delays: [ 5, 20, 1, 10, 20, 5, 20 ] }, foam.__context__); return foam.dao.CachingDAO.create({ src: idbDAO, cache: mDAO }); }); }); }); describe('DeDupDAO', function() { genericDAOTestBattery(function(model) { var mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.DeDupDAO.create({ delegate: mDAO })); }); }); describe('SequenceNumberDAO', function() { var mDAO; var sDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.SequenceNumberDAO.create({ delegate: mDAO, of: model })); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); sDAO = foam.dao.SequenceNumberDAO.create({ delegate: mDAO, of: test.CompA }); }); it('assigns sequence numbers to objects missing the value', function(done) { var a = test.CompA.create({ a: 4 }, foam.__context__); // id not set sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(1); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(1); expect(sink.a[0].a).toEqual(4); expect(sink.a[1].id).toEqual(2); expect(sink.a[1].a).toEqual(6); done(); }); }); }); }); }); it('skips sequence numbers to objects with an existing value', function(done) { var a = test.CompA.create({ id: 3, a: 4 }, foam.__context__); sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(3); a = test.CompA.create({ id: 2, a: 6 }, foam.__context__); return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(2); expect(sink.a[0].a).toEqual(6); expect(sink.a[1].id).toEqual(3); expect(sink.a[1].a).toEqual(4); done(); }); }); }); }); }); it('does not reuse sequence numbers from objects with an existing value', function(done) { var a = test.CompA.create({ id: 1, a: 4 }, foam.__context__); sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(1); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(1); expect(sink.a[0].a).toEqual(4); expect(sink.a[1].id).toEqual(2); expect(sink.a[1].a).toEqual(6); done(); }); }); }); }); }); it('starts from the existing max value', function(done) { mDAO.put(test.CompA.create({ id: 568, a: 4 }, foam.__context__)); mDAO.put(test.CompA.create({ id: 45, a: 5 }, foam.__context__)); var a = test.CompA.create({ a: 6 }, foam.__context__); // id not set sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(3); expect(sink.a[0].id).toEqual(45); expect(sink.a[1].id).toEqual(568); expect(sink.a[2].id).toEqual(569); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(4); expect(sink.a[3].id).toEqual(570); done(); }); }); }); }); }); }); describe('GUIDDAO', function() { var mDAO; var gDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.GUIDDAO.create({ delegate: mDAO, of: model })); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); gDAO = foam.dao.GUIDDAO.create({ delegate: mDAO, of: test.CompA }); }); it('assigns GUIDs to objects missing the value', function(done) { var a = test.CompA.create({ a: 4 }, foam.__context__); // id not set gDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id.length).toBeGreaterThan(8); // id set, not a GUID character for predictable sorting in this test a = test.CompA.create({ id: '!!!', a: 6 }, foam.__context__); return gDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id.length).toBeLessThan(8); expect(sink.a[1].id.length).toBeGreaterThan(8); done(); }); }); }); }); }); }); describe('LRUDAOManager', function() { var mDAO; var lruManager; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); lruManager = foam.dao.LRUDAOManager.create({ dao: mDAO, maxSize: 4 }); }); afterEach(function() { mDAO = null; lruManager = null; }); it('accepts items up to its max size', function(done) { // Note that MDAO and LRU do not go async for this test mDAO.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(4); done(); }); }); it('clears old items to maintain its max size', function(done) { mDAO.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 5, a: 'five' }, foam.__context__)); // LRU updates the dao slighly asynchronously, so give the notifies a // frame to propagate (relevant for browser only, node promises are sync-y // enough to get by) setTimeout(function() { mDAO.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(4); }).then(function() { mDAO.find(1).then(function() { fail("Expected no item 1 to be found"); done(); }, function(err) { //expected not to find it done(); }); }); }, 100); }); it('handles a dao switch', function(done) { // Note that MDAO and LRU do not go async for this test // swap dao mDAO2 = foam.dao.MDAO.create({ of: test.CompA }); lruManager.dao = mDAO2; // original dao should not be managed mDAO.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 5, a: 'five' }, foam.__context__)); // LRU updates the dao slighly asynchronously, so give the notifies a // frame to propagate (relevant for browser only, node promises are sync-y // enough to get by) setTimeout(function() { mDAO.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(5); }); }, 100); //////// new dao should be managed. mDAO2.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 5, a: 'five' }, foam.__context__)); // LRU updates the dao slighly asynchronously, so give the notifies a // frame to propagate (relevant for browser only, node promises are sync-y // enough to get by) setTimeout(function() { mDAO2.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(4); }).then(function() { mDAO2.find(1).then(function() { fail("Expected no item 1 to be found"); done(); }, function(err) { //expected not to find it done(); }); }); }, 100); }); }); describe('ArrayDAO', function() { var dao; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); dao = foam.dao.ArrayDAO.create({ of: test.CompA }); }); afterEach(function() { dao = null; }); it('skips properly on removeAll', function(done) { dao.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); dao.skip(2).removeAll().then(function() { expect(dao.array.length).toEqual(2); expect(dao.array[0].a).toEqual('one'); expect(dao.array[1].a).toEqual('two'); }).then(done); }); it('skips and limits properly on removeAll', function(done) { dao.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); dao.skip(1).limit(2).removeAll().then(function() { expect(dao.array.length).toEqual(2); expect(dao.array[0].a).toEqual('one'); expect(dao.array[1].a).toEqual('four'); }).then(done); }); it('skips and limits with predicate properly on removeAll', function(done) { dao.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); dao.skip(1).limit(2).where( foam.mlang.predicate.Gt.create({ arg1: test.CompA.ID, arg2: 1 }) ).removeAll().then(function() { expect(dao.array.length).toEqual(2); expect(dao.array[0].a).toEqual('one'); expect(dao.array[1].a).toEqual('two'); }).then(done); }); }); describe('ContextualizingDAO', function() { var mDAO; var cDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.ContextualizingDAO.create({ delegate: mDAO, of: model })); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'Environment', exports: [ 'exp' ], properties: [ 'exp' ] }); foam.CLASS({ package: 'test', name: 'ImporterA', imports: [ 'exp?' ], properties: [ 'id' ] }); var env = test.Environment.create({ exp: 66 }, foam.__context__); mDAO = foam.dao.MDAO.create({ of: test.ImporterA }); cDAO = foam.dao.ContextualizingDAO.create({ delegate: mDAO, of: test.ImporterA }, env); }); it('swaps context so find() result objects see ContextualizingDAO context', function(done) { var a = test.ImporterA.create({ id: 1 }, foam.__context__); expect(a.exp).toBeUndefined(); cDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].exp).toBeUndefined(); return cDAO.find(1).then(function (obj) { expect(obj.exp).toEqual(66); // now has context with env export done(); }); }); }); }); }); describe('SyncDAO', function() { // NOTE: Test assumes polling can be simulated by calling SyncDAO.sync() var remoteDAO; var cacheDAO; var syncDAO; var syncRecordDAO; beforeEach(function() { foam.CLASS({ package: 'test', name: 'SyncModel', properties: [ 'id', 'version', 'source' ] }); remoteDAO = test.helpers.OfflineableDAO.create({ of: test.SyncModel }, foam.__context__); cacheDAO = foam.dao.ArrayDAO.create({ of: test.SyncModel }); syncRecordDAO = foam.dao.ArrayDAO.create({ of: foam.dao.SyncRecord }); syncDAO = foam.dao.SyncDAO.create({ of: test.SyncModel, syncProperty: test.SyncModel.VERSION, remoteDAO: remoteDAO, delegate: cacheDAO, syncRecordDAO: syncRecordDAO, polling: false, // Polling simulated by invasive calls to sync() }); }); // isolate sync/timeout call code, as it may change with SyncDAO's implementation function doSyncThen(fn) { syncDAO.sync(); // let promises settle setTimeout(fn, 250); } function preloadRemote() { remoteDAO.array = [ test.SyncModel.create({ id: 0, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 1, version: 3, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 2, version: 3, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 3, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 4, version: 2, source: 'server' }, foam.__context__), ]; } function loadSync() { syncDAO.put(test.SyncModel.create({ id: 2, source: 'client' }, foam.__context__)); syncDAO.put(test.SyncModel.create({ id: 3, source: 'client' }, foam.__context__)); syncDAO.put(test.SyncModel.create({ id: 4, source: 'client' }, foam.__context__)); syncDAO.put(test.SyncModel.create({ id: 5, source: 'client' }, foam.__context__)); } it('syncs from remote on first connect', function(done) { preloadRemote(); remoteDAO.offline = false; doSyncThen(function() { syncDAO.select().then(function(sink) { expect(sink.a.length).toEqual(5); expect(sink.a[2].version).toEqual(3); }).then(done); }); }); it('syncs from remote on first connect', function(done) { preloadRemote(); remoteDAO.offline = false; doSyncThen(function() { syncDAO.select().then(function(sink) { expect(sink.a.length).toEqual(5); expect(sink.a[2].version).toEqual(3); }).then(done); }); }); it('starts offline, items put to client, then online, syncs to remote', function(done) { remoteDAO.offline = true; loadSync(); remoteDAO.offline = false; doSyncThen(function() { expect(remoteDAO.array.length).toEqual(4); done(); }); }); it('starts offline, items put to client, items inserted into remote, then online, syncs both ways', function(done) { remoteDAO.offline = true; preloadRemote(); loadSync(); remoteDAO.offline = false; doSyncThen(function() { expect(remoteDAO.array.length).toEqual(6); expect(cacheDAO.array.length).toEqual(6); done(); }); }); it('syncs removes from client, to server', function(done) { preloadRemote(); remoteDAO.offline = false; doSyncThen(function() { syncDAO.select().then(function(sink) { expect(sink.a.length).toEqual(5); remoteDAO.offline = true; syncDAO.remove(sink.a[1]); syncDAO.remove(sink.a[0]); // version is stale, will not remove remoteDAO.offline = false; doSyncThen(function() { expect(remoteDAO.array.length).toEqual(4); done(); }); }) }); }); // TODO: is there a server removal path intended? // it('syncs removes from client and server', function(done) { // preloadRemote(); // remoteDAO.offline = false; // doSyncThen(function() { // syncDAO.select().then(function(sink) { // expect(sink.a.length).toEqual(5); // console.log("cache1", cacheDAO.array); // remoteDAO.remove(sink.a[1]); // remoteDAO.offline = true; // syncDAO.remove(sink.a[0]); // remoteDAO.offline = false; // doSyncThen(function() { // expect(remoteDAO.array.length).toEqual(3); // expect(cacheDAO.array.length).toEqual(3); // console.log("remote2", remoteDAO.array); // console.log("cache2", cacheDAO.array); // console.log("sync2", syncRecordDAO.array); // done(); // }); // }) // }); // }); }); describe('JournalDAO', function() { var delegateDAO; var journalDAO; var dao; beforeEach(function() { foam.CLASS({ package: 'test', name: 'JournalModel', properties: [ 'id', 'value' ] }); journalDAO = foam.dao.ArrayDAO.create({ of: foam.dao.JournalEntry }); delegateDAO = foam.dao.ArrayDAO.create({ of: test.JournalModel }); dao = foam.dao.JournalDAO.create({ of: test.JournalModel, delegate: delegateDAO, journal: foam.dao.SequenceNumberDAO.create({ of: foam.dao.JournalEntry, delegate: journalDAO }) }); }); function loadItems1() { return Promise.all([ dao.put(test.JournalModel.create({ id: 0, value: 1 }, foam.__context__)), dao.put(test.JournalModel.create({ id: 1, value: 'one' }, foam.__context__)), dao.put(test.JournalModel.create({ id: 2, value: 'a' }, foam.__context__)) ]); } function removeItems2() { return dao.remove(test.JournalModel.create({ id: 1, value: 'two' }, foam.__context__)); } function loadItems3() { return Promise.all([ dao.put(test.JournalModel.create({ id: 0, value: 3 }, foam.__context__)), dao.put(test.JournalModel.create({ id: 2, value: 'c' }, foam.__context__)) ]); } it('records write operations', function(done) { loadItems1().then(function() { expect(journalDAO.array.length).toEqual(3); removeItems2().then(function() { expect(journalDAO.array.length).toEqual(4); loadItems3().then(function() { expect(journalDAO.array.length).toEqual(6); done(); }); }); }); }); it('records enough to rebuild the delegate DAO', function(done) { Promise.all([ loadItems1(), removeItems2(), loadItems3() ]).then(function() { // rebuild from the journal // select() to ensure the ordering is what the journal thinks is correct journalDAO.select().then(function(sink) { var newDAO = foam.dao.ArrayDAO.create({ of: test.JournalModel }); var journal = sink.a; for ( var i = 0; i < journal.length; i++ ) { var entry = journal[i]; if ( entry.isRemove ) newDAO.remove(entry.record); else newDAO.put(entry.record); } // compare newDAO and delegateDAO expect(delegateDAO.array.length).toEqual(newDAO.array.length); for ( var i = 0; i < delegateDAO.array.length; i++ ) { if ( delegateDAO.array[i].compareTo(newDAO.array[i]) !== 0 ) { fail('mismatched results'); } } done(); }); }); }); }); describe('TimingDAO', function() { genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.TimingDAO.create({ delegate: mDAO, of: model, name: 'timingtest', })); }); }); describe('LoggingDAO', function() { genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.LoggingDAO.create({ delegate: mDAO, of: model, logger: function() { }, name: 'loggingtest', logReads: true })); }); }); describe('NullDAO', function() { it('rejects put operations', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.put().then( function() { fail('put should not be accepted'); }, function(err) { done(); } ); }); it('rejects find operations', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.find(4).then( function() { fail('find should not be accepted'); }, function(err) { done(); } ); }); it('selects as empty', function(done) { var sink = { eof: function() { this.eofCalled++ }, eofCalled: 0, put: function(o) { this.putCalled++ }, putCalled: 0, }; var nDAO = foam.dao.NullDAO.create(); nDAO.select(sink).then(function(sink) { expect(sink.eofCalled).toEqual(1); expect(sink.putCalled).toEqual(0); done(); }); }); it('accepts remove as no-op', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.remove().then(done); }); it('accepts removeAll as no-op', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.removeAll().then(done); }); }); describe('TimestampDAO', function() { var mDAO; var sDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.SequenceNumberDAO.create({ delegate: mDAO, of: model })); }); beforeEach(function() { jasmine.clock().install(); foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); sDAO = foam.dao.TimestampDAO.create({ delegate: mDAO, of: test.CompA }); }); afterEach(function() { jasmine.clock().uninstall(); }); it('assigns timestamps to objects missing the value', function(done) { jasmine.clock().mockDate(new Date(0)); jasmine.clock().tick(2000); var a = test.CompA.create({ a: 4 }, foam.__context__); // id not set sDAO.put(a).then(function() { jasmine.clock().tick(2000); return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toBeGreaterThan(0); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set jasmine.clock().tick(2000); return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { jasmine.clock().tick(2000); expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toBeGreaterThan(0); expect(sink.a[0].a).toEqual(4); expect(sink.a[1].id).toBeGreaterThan(sink.a[0].id); expect(sink.a[1].a).toEqual(6); done(); }); }); }); }); }); it('skips assigning to objects with an existing value', function(done) { jasmine.clock().mockDate(new Date(0)); jasmine.clock().tick(2000); var a = test.CompA.create({ id: 3, a: 4 }, foam.__context__); sDAO.put(a).then(function() { jasmine.clock().tick(2000); return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(3); a = test.CompA.create({ id: 2, a: 6 }, foam.__context__); jasmine.clock().tick(2000); return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { jasmine.clock().tick(2000); expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(2); expect(sink.a[0].a).toEqual(6); expect(sink.a[1].id).toEqual(3); expect(sink.a[1].a).toEqual(4); done(); }); }); }); }); }); }); describe('EasyDAO-permutations', function() { [ { daoType: 'MDAO', }, { daoType: 'LOCAL', }, { daoType: 'MDAO', seqNo: true, seqProperty: 'id' }, { daoType: 'LOCAL', guid: true, seqProperty: 'id' }, { daoType: 'MDAO', logging: true, timing: true, journal: true, dedup: true, contextualize: true }, { daoType: 'MDAO', cache: true, }, // TODO: fix cache issues: // { // daoType: foam.dao.ArrayDAO, // cache: true, // }, // { // daoType: 'LOCAL', // cache: true, // }, // Property name foam.core.Property // debug.js:264 Boolean seqNo false // debug.js:264 Boolean guid false // debug.js:264 Property seqProperty undefined // debug.js:264 Boolean cache false // debug.js:264 Boolean dedup false // debug.js:264 Property journal false // debug.js:264 Boolean contextualize false // debug.js:264 Property daoType foam.dao.IDBDAO // debug.js:264 Boolean autoIndex false // debug.js:264 Boolean syncWithServer false // debug.js:264 Boolean syncPolling true // debug.js:264 String serverUri http://localhost:8000/api // debug.js:264 Boolean isServer false // debug.js:264 Property syncProperty undefined // debug.js:264 Class2 of PropertyClass ].forEach(function(cfg) { genericDAOTestBattery(function(model) { cfg.of = model; var dao = foam.dao.EasyDAO.create(cfg); return dao.removeAll().then(function() { return dao; }); }); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); }); it('throws on seqNo && guid', function() { expect(function() { foam.dao.EasyDAO.create({ of: test.CompA, daoType: 'MDAO', seqNo: true, guid: true, }); }).toThrow(); }); it('forwards addPropertyIndex', function() { var dao = foam.dao.EasyDAO.create({ of: test.CompA, daoType: foam.dao.MDAO }); // TODO: mock MDAO, check that these get called through dao.addPropertyIndex(test.CompA.A); dao.addIndex(test.CompA.A.toIndex(dao.mdao.idIndex)); }); it('constructs HTTP ClientDAO', function() { foam.CLASS({ package: 'test', name: 'HTTPBoxMocker', exports: [ 'httpResponse' ], properties: [ 'httpResponse' ] }); var env = test.HTTPBoxMocker.create(undefined, foam.__context__); // TODO: dependency injection reistering is a bit awkward: env.__subContext__.register(test.helpers.MockHTTPBox, 'foam.box.HTTPBox'); var dao = foam.dao.EasyDAO.create({ of: test.CompA, daoType: 'MDAO', syncWithServer: true, serverUri: 'localhost:8888', syncPolling: true, syncProperty: test.CompA.A }, env); }); }); describe('DAO.listen', function() { var dao; var sink; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); dao = foam.dao.ArrayDAO.create({ of: test.CompA }); sink = foam.dao.ArrayDAO.create({ of: test.CompA }); }); it('forwards puts', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao.listen(sink); dao.put(a); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(a); dao.put(b); expect(sink.array.length).toEqual(2); expect(sink.array[1]).toEqual(b); }); it('forwards removes', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); sink.put(a); sink.put(b); dao.put(a); dao.put(b); dao.listen(sink); dao.remove(a); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(b); }); it('covers reset', function() { dao.listen(sink); dao.pub('on', 'reset'); }); it('filters puts with predicate', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); var pred = foam.mlang.predicate.Eq.create({ arg1: test.CompA.A, arg2: 4 }); dao.where(pred).listen(sink); dao.put(a); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(a); dao.put(b); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(a); }); it('terminates on flow control stop', function() { var a = test.CompA.create({ id: 0, a: 8 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 6 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 4 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 2 }, foam.__context__); var obj; var fcSink = foam.dao.QuickSink.create({ putFn: function(o, fc) { obj = o; fc.stop(); } }); dao.listen(fcSink); dao.put(a); expect(obj).toEqual(a); dao.put(b); expect(obj).toEqual(a); }); it('terminates on flow control error', function() { var a = test.CompA.create({ id: 0, a: 8 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 6 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 4 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 2 }, foam.__context__); var obj; var fcSink = foam.dao.QuickSink.create({ putFn: function(o, fc) { obj = o; fc.error("err!"); } }); dao.listen(fcSink); dao.put(a); expect(obj).toEqual(a); dao.put(b); expect(obj).toEqual(a); }); it('and pipe() listens', function(done) { var a = test.CompA.create({ id: 0, a: 8 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 6 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 4 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 2 }, foam.__context__); dao.put(a); dao.put(b); dao.pipe(sink).then(function(sub) { expect(sink.array.length).toEqual(2); expect(sink.array[0]).toEqual(a); expect(sink.array[1]).toEqual(b); // and we should be listening, too dao.put(c); expect(sink.array.length).toEqual(3); expect(sink.array[2]).toEqual(c); // subscription allows disconnect sub.destroy(); dao.put(d); // no longer listening expect(sink.array.length).toEqual(3); done(); }); }); }); describe('FilteredDAO', function() { var dao; var sink; var m; var l, l2; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); m = foam.mlang.ExpressionsSingleton.create(); dao = foam.dao.ArrayDAO.create({ of: test.CompA }); sink = foam.dao.ArrayDAO.create({ of: test.CompA }); l = function(s, on, evt, obj) { l.evt = evt; l.obj = obj; l.count = ( l.count + 1 ) || 1; }; l2 = function(s, on, evt, obj) { l2.evt = evt; l2.obj = obj; l2.count = ( l2.count + 1 ) || 1; } }); it('filters put events', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao = dao.where(m.EQ(test.CompA.A, 4)); dao.on.sub(l); dao.on.sub(l2); dao.put(a); expect(l.evt).toEqual('put'); expect(l.obj).toEqual(a); expect(l.count).toEqual(1); // since 'b' is filtered out, the put changes to remove to ensure the // listener knows it shouldn't exist dao.put(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); expect(l.count).toEqual(2); }); it('does not filter remove events', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao.put(a); dao.put(b); dao = dao.where(m.EQ(test.CompA.A, 4)); dao.on.sub(l); dao.remove(a); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(a); dao.remove(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); }); it('handles a delegate swap', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao = dao.where(m.EQ(test.CompA.A, 4)); dao.on.sub(l); // normal put test dao.put(a); expect(l.evt).toEqual('put'); expect(l.obj).toEqual(a); dao.put(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); // swap a new base dao in delete l.evt; delete l.obj; var newBaseDAO = foam.dao.ArrayDAO.create({ of: test.CompA }); var oldDAO = dao.delegate; dao.delegate = newBaseDAO; expect(l.evt).toEqual('reset'); // filtered put from new base newBaseDAO.put(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); delete l.evt; delete l.obj; // old dao does not cause updates oldDAO.put(a); expect(l.evt).toBeUndefined(); expect(l.obj).toBeUndefined(); // cover destructor dao.destroy(); }); }); describe('String.daoize', function() { it('handles a model name', function() { expect(foam.String.daoize('MyModel')).toEqual('myModelDAO'); }); it('handles a model name with package', function() { expect(foam.String.daoize('test.package.PkgModel')).toEqual('test_package_PkgModelDAO'); }); }); describe('Relationship', function() { foam.CLASS({ package: 'test', name: 'RelA', properties: [ 'bRef' ] }); foam.CLASS({ package: 'test', name: 'RelB', properties: [ 'aRef' ] }); foam.CLASS({ package: 'test', name: 'relEnv', exports: [ 'test_RelADAO', 'test_RelBDAO' ], properties: [ { name: 'test.RelADAO', factory: function() { return foam.dao.ArrayDAO.create(); } }, { name: 'test.RelBDAO', factory: function() { return foam.dao.ArrayDAO.create(); } } ] }); foam.RELATIONSHIP({ name: 'children', inverseName: 'parent', sourceModel: 'test.RelA', //sourceProperties: [ 'bRef' ], targetModel: 'test.RelB', //targetProperties: [ 'aRef' ], }); it('has relationship DAOs', function() { var env = test.relEnv.create(undefined, foam.__context__); var relObjA = test.RelA.create(undefined, env); var relDAO = relObjA.children; }) }); describe('MultiPartID MDAO support', function() { var mDAO; beforeEach(function() { foam.CLASS({ package: 'test', name: 'Mpid', ids: [ 'a', 'b' ], properties: [ 'a', 'b', 'c' ] }); mDAO = foam.dao.MDAO.create({ of: test.Mpid }); }); afterEach(function() { mDAO = null; }); it('generates a proper ID index', function(done) { mDAO.put(test.Mpid.create({ a: 1, b: 1, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 1, b: 2, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 1, b: 1, c: 2 }, foam.__context__)); // update mDAO.put(test.Mpid.create({ a: 1, b: 2, c: 2 }, foam.__context__)); // update mDAO.put(test.Mpid.create({ a: 2, b: 1, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 2, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 2, c: 2 }, foam.__context__)); // update mDAO.select(foam.mlang.sink.Count.create()).then(function(counter) { expect(counter.value).toEqual(4); done(); }); }); it('finds by multipart ID array', function(done) { mDAO.put(test.Mpid.create({ a: 1, b: 1, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 1, b: 2, c: 2 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 1, c: 3 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 2, c: 4 }, foam.__context__)); // add mDAO.find([ 2, 1 ]).then(function(obj) { // with array key expect(obj.c).toEqual(3); mDAO.find(test.Mpid.create({ a: 2, b: 2 }, foam.__context__).id) // array from MultiPartID .then(function(obj2) { expect(obj2.c).toEqual(4); done(); }); }); }); }); describe('NoSelectAllDAO', function() { var dao; var srcdao; var sink; var m; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); m = foam.mlang.ExpressionsSingleton.create(); srcdao = foam.dao.ArrayDAO.create({ of: test.CompA }); sink = foam.dao.ArrayDAO.create({ of: test.CompA }); dao = foam.dao.NoSelectAllDAO.create({ of: test.CompA, delegate: srcdao }); dao.put(test.CompA.create({ id: 0, a: 4 }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 77 }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 8 }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 99 }, foam.__context__)); }); it('Does not forward select() with no restrictions', function(done) { dao.select(sink).then(function(snk) { expect(snk.array.length).toEqual(0); done(); }); }); it('Forwards select() with a predicate', function(done) { dao.where(m.LT(test.CompA.A, 20)).select(sink).then(function(snk) { expect(snk.array.length).toEqual(2); done(); }); }); it('Forwards select() with a limit', function(done) { dao.limit(2).select(sink).then(function(snk) { expect(snk.array.length).toEqual(2); done(); }); }); it('Forwards select() with a skip', function(done) { dao.skip(1).select(sink).then(function(snk) { expect(snk.array.length).toEqual(3); done(); }); }); it('Does not forward select() with an infinite limit', function(done) { dao.limit(Math.Infinity).select(sink).then(function(snk) { expect(snk.array.length).toEqual(0); done(); }); }); });
test/src/lib/dao.js
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ describe('FlowControl', function() { it('stops', function() { var fc = foam.dao.FlowControl.create(); fc.stop(); expect(fc.stopped).toEqual(true); }); it('errors', function() { var fc = foam.dao.FlowControl.create(); fc.error("error"); expect(fc.errorEvt).toEqual("error"); }); }); describe('Sink Interface', function() { it('covers empty methods', function() { var sinkMethods = foam.dao.Sink.getAxiomsByClass(foam.core.Method).map( function(m) { return m.code(); } ); }); }); describe('AbstractSink', function() { it('covers empty methods', function() { var sink = foam.dao.AbstractSink.create(); sink.put(); sink.remove(); sink.eof(); sink.error(); sink.reset(); }); }); describe('PredicatedSink', function() { beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); foam.CLASS({ name: 'TestPredicate', implements: [ 'foam.mlang.predicate.Predicate' ], properties: [ 'calledWith', 'allow', 'f' ] }); }); it('only puts on a match', function() { var fakePredicate = TestPredicate.create({ calledWith: null, allow: false, f: function(o) { this.calledWith = o; if ( this.allow ) return true; } }, foam.__context__); var sink = foam.dao.PredicatedSink.create({ predicate: fakePredicate, delegate: foam.dao.ArraySink.create() }, foam.__context__); var a = test.CompA.create({ id: 0, a: 3 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 5 }, foam.__context__); sink.put(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.a.length).toEqual(0); fakePredicate.allow = true; sink.put(b); expect(fakePredicate.calledWith).toEqual(b); }); it('only removes on a match', function() { var fakePredicate = TestPredicate.create({ calledWith: null, allow: false, f: function(o) { this.calledWith = o; if ( this.allow ) return true; } }, foam.__context__); var sink = foam.dao.PredicatedSink.create({ predicate: fakePredicate, delegate: foam.dao.ArrayDAO.create() }, foam.__context__); var a = test.CompA.create({ id: 0, a: 3 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 5 }, foam.__context__); fakePredicate.allow = true; sink.put(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.array.length).toEqual(1); fakePredicate.calledWith = null; fakePredicate.allow = false; sink.remove(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.array.length).toEqual(1); fakePredicate.calledWith = null; fakePredicate.allow = true; sink.remove(a); expect(fakePredicate.calledWith).toEqual(a); expect(sink.delegate.array.length).toEqual(0); }); }); describe('QuickSink', function() { it('calls given functions', function() { function mockCallP(o) { this.calledPut = o; } function mockCallR(o) { this.calledRemove = o; } function mockCallE(o) { this.calledEof = o; } function mockCallEr(o) { this.calledError = o; } function mockCallRe(o) { this.calledReset = o; } var sink = foam.dao.QuickSink.create({ putFn: mockCallP, removeFn: mockCallR, eofFn: mockCallE, errorFn: mockCallEr, resetFn: mockCallRe }); sink.put("putcall"); sink.remove("removecall"); sink.eof("eofcall"); sink.error("errorcall"); sink.reset("resetcall"); expect(sink.calledPut).toEqual("putcall"); expect(sink.calledRemove).toEqual("removecall"); expect(sink.calledEof).toEqual("eofcall"); expect(sink.calledError).toEqual("errorcall"); expect(sink.calledReset).toEqual("resetcall"); }); }); describe('LimitedSink', function() { beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); }); it('only puts when below limit', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.put(a); sink.put(b); sink.put(c); sink.put(d); expect(sink.delegate.array.length).toEqual(3); expect(sink.delegate.array[0].id).toEqual(0); expect(sink.delegate.array[1].id).toEqual(1); expect(sink.delegate.array[2].id).toEqual(2); }); it('only removes when below limit', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.delegate.put(a); sink.delegate.put(b); sink.delegate.put(c); sink.delegate.put(d); sink.remove(a); sink.remove(b); sink.remove(c); sink.remove(d); expect(sink.delegate.array.length).toEqual(1); expect(sink.delegate.array[0].id).toEqual(3); }); it('put stops flow control', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }, foam.__context__); var fc = foam.dao.FlowControl.create(); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.put(a, fc); expect(fc.stopped).toEqual(false); sink.put(b, fc); expect(fc.stopped).toEqual(false); sink.put(c, fc); expect(fc.stopped).toEqual(false); sink.put(d, fc); expect(fc.stopped).toEqual(true); }); it('remove stops flow control', function() { var sink = foam.dao.LimitedSink.create({ limit: 3, delegate: foam.dao.ArrayDAO.create() }, foam.__context__); var fc = foam.dao.FlowControl.create(); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.delegate.put(a); sink.delegate.put(b); sink.delegate.put(c); sink.delegate.put(d); sink.remove(a, fc); expect(fc.stopped).toEqual(false); sink.remove(b, fc); expect(fc.stopped).toEqual(false); sink.remove(c, fc); expect(fc.stopped).toEqual(false); sink.remove(d, fc); expect(fc.stopped).toEqual(true); }); }); describe('SkipSink', function() { beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); }); it('only puts when above limit', function() { var sink = foam.dao.SkipSink.create({ skip: 2, delegate: foam.dao.ArrayDAO.create() }, foam.__context__); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.put(a); sink.put(b); sink.put(c); sink.put(d); expect(sink.delegate.array.length).toEqual(2); expect(sink.delegate.array[0].id).toEqual(2); expect(sink.delegate.array[1].id).toEqual(3); }); it('only removes when below limit', function() { var sink = foam.dao.SkipSink.create({ skip: 2, delegate: foam.dao.ArrayDAO.create() }, foam.__context__); var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 5 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 3 }, foam.__context__); sink.delegate.put(a); sink.delegate.put(b); sink.delegate.put(c); sink.delegate.put(d); sink.remove(a); sink.remove(b); sink.remove(c); sink.remove(d); expect(sink.delegate.array.length).toEqual(2); expect(sink.delegate.array[0].id).toEqual(0); expect(sink.delegate.array[1].id).toEqual(1); }); }); if ( typeof localStorage === "undefined" || localStorage === null ) { var LocalStorage = require('node-localstorage').LocalStorage; localStorage = new LocalStorage('./tmp'); } describe('LocalStorageDAO', function() { var a; var a2; var b; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a', 'b' ] }); foam.CLASS({ package: 'test', name: 'CompB', properties: [ 'id', 'b' ] }); a = test.CompA.create({id: 4, a:1, b:2}, foam.__context__); a2 = test.CompA.create({id: 6, a:'hello', b:6}, foam.__context__); b = test.CompB.create({id: 8, b:a2}, foam.__context__); }); afterEach(function() { a = a2 = b = null; }); it('can be created', function() { foam.dao.LocalStorageDAO.create({ name: '_test_LS_' }); }); it('reads back written data', function() { var dao = foam.dao.LocalStorageDAO.create({ name: '_test_LS_' }); dao.put(a); dao.put(a2); dao.put(b); // a new local storage dao with the same store name // TODO: guarantee file sync so we can test this synchronously //var dao2 = foam.dao.LocalStorageDAO.create({ name: '_test_LS_' }); var dao2 = dao; // still checks deserialization var result = foam.dao.ArraySink.create(); dao2.select(result); expect(result.a[0]).toEqual(a); expect(result.a[1]).toEqual(a2); expect(result.a[2]).toEqual(b); expect(result.a[2].stringify()).toEqual(b.stringify()); }); // Run the generic suite of DAO tests against it. genericDAOTestBattery(function(model) { localStorage.removeItem('_test_LS_generic_'); return Promise.resolve(foam.dao.LocalStorageDAO.create({ name: '_test_LS_generic_', of: model })); }); afterAll(function() { localStorage.clear(); }); // TODO: test nested objects when foam.json supports them }); describe('ArrayDAO', function() { genericDAOTestBattery(function(model) { return Promise.resolve(foam.dao.ArrayDAO.create({ of: model })); }); }); if ( foam.dao.IDBDAO ) { describe('IDBDAO', function() { genericDAOTestBattery(function(model) { var dao = foam.dao.IDBDAO.create({ of: model }); return dao.removeAll().then(function() { return Promise.resolve(dao); } ); }); }); } describe('MDAO', function() { genericDAOTestBattery(function(model) { return Promise.resolve(foam.dao.MDAO.create({ of: model })); }); }); // NOTE: not all generic tests are applicable, as LazyCacheDAO does not // offer a way to immediately sync results. It will eagerly deliver // partial results and update eventually. Perhaps a different set // of genericDAOTestBattery for this kind of partial-result case. // describe('LazyCacheDAO-cacheOnSelect-async', function() { // // test caching against an IDBDAO remote and MDAO cache. // genericDAOTestBattery(function(model) { // var idbDAO = test.helpers.RandomDelayDAO.create({ // of: model, // delays: [ 5, 20, 1, 10, 20, 5, 20 ] // }); // var mDAO = test.helpers.RandomDelayDAO.create({ // of: model, // delays: [ 5, 20, 1, 10, 20, 5, 20 ] // }); // return Promise.resolve(foam.dao.LazyCacheDAO.create({ // delegate: idbDAO, // cache: mDAO, // cacheOnSelect: true // })); // }); // }); describe('LazyCacheDAO-cacheOnSelect', function() { // test caching against an IDBDAO remote and MDAO cache. genericDAOTestBattery(function(model) { var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) .create({ name: '_test_lazyCache_', of: model }, foam.__context__); return idbDAO.removeAll().then(function() { var mDAO = foam.dao.MDAO.create({ of: model }); return foam.dao.LazyCacheDAO.create({ delegate: idbDAO, cache: mDAO, cacheOnSelect: true }, foam.__context__); }); }); }); describe('LazyCacheDAO', function() { // test caching against an IDBDAO remote and MDAO cache. genericDAOTestBattery(function(model) { var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) .create({ name: '_test_lazyCache_', of: model }, foam.__context__); return idbDAO.removeAll().then(function() { var mDAO = foam.dao.MDAO.create({ of: model }); return foam.dao.LazyCacheDAO.create({ delegate: idbDAO, cache: mDAO, cacheOnSelect: false }, foam.__context__); }); }); }); describe('CachingDAO', function() { genericDAOTestBattery(function(model) { var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) .create({ name: '_test_readCache_', of: model }, foam.__context__); return idbDAO.removeAll().then(function() { var mDAO = foam.dao.MDAO.create({ of: model }); return foam.dao.CachingDAO.create({ src: idbDAO, cache: mDAO }); }); }); }); describe('CachingDAO-async', function() { genericDAOTestBattery(function(model) { var idbDAO = test.helpers.RandomDelayDAO.create({ of: model, delays: [ 30, 5, 20, 1, 10, 20, 5, 20 ] }, foam.__context__); return idbDAO.removeAll().then(function() { var mDAO = test.helpers.RandomDelayDAO.create({ of: model, delays: [ 5, 20, 1, 10, 20, 5, 20 ] }, foam.__context__); return foam.dao.CachingDAO.create({ src: idbDAO, cache: mDAO }); }); }); }); describe('DeDupDAO', function() { genericDAOTestBattery(function(model) { var mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.DeDupDAO.create({ delegate: mDAO })); }); }); describe('SequenceNumberDAO', function() { var mDAO; var sDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.SequenceNumberDAO.create({ delegate: mDAO, of: model }, foam.__context__)); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); sDAO = foam.dao.SequenceNumberDAO.create({ delegate: mDAO, of: test.CompA }, foam.__context__); }); it('assigns sequence numbers to objects missing the value', function(done) { var a = test.CompA.create({ a: 4 }, foam.__context__); // id not set sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(1); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(1); expect(sink.a[0].a).toEqual(4); expect(sink.a[1].id).toEqual(2); expect(sink.a[1].a).toEqual(6); done(); }); }); }); }); }); it('skips sequence numbers to objects with an existing value', function(done) { var a = test.CompA.create({ id: 3, a: 4 }, foam.__context__); sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(3); a = test.CompA.create({ id: 2, a: 6 }, foam.__context__); return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(2); expect(sink.a[0].a).toEqual(6); expect(sink.a[1].id).toEqual(3); expect(sink.a[1].a).toEqual(4); done(); }); }); }); }); }); it('does not reuse sequence numbers from objects with an existing value', function(done) { var a = test.CompA.create({ id: 1, a: 4 }, foam.__context__); sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(1); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(1); expect(sink.a[0].a).toEqual(4); expect(sink.a[1].id).toEqual(2); expect(sink.a[1].a).toEqual(6); done(); }); }); }); }); }); it('starts from the existing max value', function(done) { mDAO.put(test.CompA.create({ id: 568, a: 4 }, foam.__context__)); mDAO.put(test.CompA.create({ id: 45, a: 5 }, foam.__context__)); var a = test.CompA.create({ a: 6 }, foam.__context__); // id not set sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(3); expect(sink.a[0].id).toEqual(45); expect(sink.a[1].id).toEqual(568); expect(sink.a[2].id).toEqual(569); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(4); expect(sink.a[3].id).toEqual(570); done(); }); }); }); }); }); }); describe('GUIDDAO', function() { var mDAO; var gDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.GUIDDAO.create({ delegate: mDAO, of: model }, foam.__context__)); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); gDAO = foam.dao.GUIDDAO.create({ delegate: mDAO, of: test.CompA }); }); it('assigns GUIDs to objects missing the value', function(done) { var a = test.CompA.create({ a: 4 }, foam.__context__); // id not set gDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id.length).toBeGreaterThan(8); // id set, not a GUID character for predictable sorting in this test a = test.CompA.create({ id: '!!!', a: 6 }, foam.__context__); return gDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(2); expect(sink.a[0].id.length).toBeLessThan(8); expect(sink.a[1].id.length).toBeGreaterThan(8); done(); }); }); }); }); }); }); describe('LRUDAOManager', function() { var mDAO; var lruManager; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); lruManager = foam.dao.LRUDAOManager.create({ dao: mDAO, maxSize: 4 }, foam.__context__); }); afterEach(function() { mDAO = null; lruManager = null; }); it('accepts items up to its max size', function(done) { // Note that MDAO and LRU do not go async for this test mDAO.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(4); done(); }); }); it('clears old items to maintain its max size', function(done) { mDAO.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 5, a: 'five' }, foam.__context__)); // LRU updates the dao slighly asynchronously, so give the notifies a // frame to propagate (relevant for browser only, node promises are sync-y // enough to get by) setTimeout(function() { mDAO.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(4); }).then(function() { mDAO.find(1).then(function() { fail("Expected no item 1 to be found"); done(); }, function(err) { //expected not to find it done(); }); }); }, 100); }); it('handles a dao switch', function(done) { // Note that MDAO and LRU do not go async for this test // swap dao mDAO2 = foam.dao.MDAO.create({ of: test.CompA }); lruManager.dao = mDAO2; // original dao should not be managed mDAO.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO.put(test.CompA.create({ id: 5, a: 'five' }, foam.__context__)); // LRU updates the dao slighly asynchronously, so give the notifies a // frame to propagate (relevant for browser only, node promises are sync-y // enough to get by) setTimeout(function() { mDAO.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(5); }); }, 100); //////// new dao should be managed. mDAO2.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); mDAO2.put(test.CompA.create({ id: 5, a: 'five' }, foam.__context__)); // LRU updates the dao slighly asynchronously, so give the notifies a // frame to propagate (relevant for browser only, node promises are sync-y // enough to get by) setTimeout(function() { mDAO2.select(foam.mlang.sink.Count.create()) .then(function(counter) { expect(counter.value).toEqual(4); }).then(function() { mDAO2.find(1).then(function() { fail("Expected no item 1 to be found"); done(); }, function(err) { //expected not to find it done(); }); }); }, 100); }); }); describe('ArrayDAO', function() { var dao; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); dao = foam.dao.ArrayDAO.create({ of: test.CompA }); }); afterEach(function() { dao = null; }); it('skips properly on removeAll', function(done) { dao.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); dao.skip(2).removeAll().then(function() { expect(dao.array.length).toEqual(2); expect(dao.array[0].a).toEqual('one'); expect(dao.array[1].a).toEqual('two'); }).then(done); }); it('skips and limits properly on removeAll', function(done) { dao.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); dao.skip(1).limit(2).removeAll().then(function() { expect(dao.array.length).toEqual(2); expect(dao.array[0].a).toEqual('one'); expect(dao.array[1].a).toEqual('four'); }).then(done); }); it('skips and limits with predicate properly on removeAll', function(done) { dao.put(test.CompA.create({ id: 1, a: 'one' }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 'two' }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 'three' }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 'four' }, foam.__context__)); dao.skip(1).limit(2).where( foam.mlang.predicate.Gt.create({ arg1: test.CompA.ID, arg2: 1 }) ).removeAll().then(function() { expect(dao.array.length).toEqual(2); expect(dao.array[0].a).toEqual('one'); expect(dao.array[1].a).toEqual('two'); }).then(done); }); }); describe('ContextualizingDAO', function() { var mDAO; var cDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.ContextualizingDAO.create({ delegate: mDAO, of: model })); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'Environment', exports: [ 'exp' ], properties: [ 'exp' ] }); foam.CLASS({ package: 'test', name: 'ImporterA', imports: [ 'exp?' ], properties: [ 'id' ] }); var env = test.Environment.create({ exp: 66 }, foam.__context__); mDAO = foam.dao.MDAO.create({ of: test.ImporterA }); cDAO = foam.dao.ContextualizingDAO.create({ delegate: mDAO, of: test.ImporterA }, env); }); it('swaps context so find() result objects see ContextualizingDAO context', function(done) { var a = test.ImporterA.create({ id: 1 }, foam.__context__); expect(a.exp).toBeUndefined(); cDAO.put(a).then(function() { return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].exp).toBeUndefined(); return cDAO.find(1).then(function (obj) { expect(obj.exp).toEqual(66); // now has context with env export done(); }); }); }); }); }); describe('SyncDAO', function() { // NOTE: Test assumes polling can be simulated by calling SyncDAO.sync() var remoteDAO; var cacheDAO; var syncDAO; var syncRecordDAO; beforeEach(function() { foam.CLASS({ package: 'test', name: 'SyncModel', properties: [ 'id', 'version', 'source' ] }); remoteDAO = test.helpers.OfflineableDAO.create({ of: test.SyncModel }, foam.__context__); cacheDAO = foam.dao.ArrayDAO.create({ of: test.SyncModel }); syncRecordDAO = foam.dao.ArrayDAO.create({ of: foam.dao.SyncRecord }); syncDAO = foam.dao.SyncDAO.create({ of: test.SyncModel, syncProperty: test.SyncModel.VERSION, remoteDAO: remoteDAO, delegate: cacheDAO, syncRecordDAO: syncRecordDAO, polling: false, // Polling simulated by invasive calls to sync() }, foam.__context__); }); // isolate sync/timeout call code, as it may change with SyncDAO's implementation function doSyncThen(fn) { syncDAO.sync(); // let promises settle setTimeout(fn, 250); } function preloadRemote() { remoteDAO.array = [ test.SyncModel.create({ id: 0, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 1, version: 3, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 2, version: 3, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 3, source: 'server' }, foam.__context__), test.SyncModel.create({ id: 4, version: 2, source: 'server' }, foam.__context__), ]; } function loadSync() { syncDAO.put(test.SyncModel.create({ id: 2, source: 'client' }, foam.__context__)); syncDAO.put(test.SyncModel.create({ id: 3, source: 'client' }, foam.__context__)); syncDAO.put(test.SyncModel.create({ id: 4, source: 'client' }, foam.__context__)); syncDAO.put(test.SyncModel.create({ id: 5, source: 'client' }, foam.__context__)); } it('syncs from remote on first connect', function(done) { preloadRemote(); remoteDAO.offline = false; doSyncThen(function() { syncDAO.select().then(function(sink) { expect(sink.a.length).toEqual(5); expect(sink.a[2].version).toEqual(3); }).then(done); }); }); it('syncs from remote on first connect', function(done) { preloadRemote(); remoteDAO.offline = false; doSyncThen(function() { syncDAO.select().then(function(sink) { expect(sink.a.length).toEqual(5); expect(sink.a[2].version).toEqual(3); }).then(done); }); }); it('starts offline, items put to client, then online, syncs to remote', function(done) { remoteDAO.offline = true; loadSync(); remoteDAO.offline = false; doSyncThen(function() { expect(remoteDAO.array.length).toEqual(4); done(); }); }); it('starts offline, items put to client, items inserted into remote, then online, syncs both ways', function(done) { remoteDAO.offline = true; preloadRemote(); loadSync(); remoteDAO.offline = false; doSyncThen(function() { expect(remoteDAO.array.length).toEqual(6); expect(cacheDAO.array.length).toEqual(6); done(); }); }); it('syncs removes from client, to server', function(done) { preloadRemote(); remoteDAO.offline = false; doSyncThen(function() { syncDAO.select().then(function(sink) { expect(sink.a.length).toEqual(5); remoteDAO.offline = true; syncDAO.remove(sink.a[1]); syncDAO.remove(sink.a[0]); // version is stale, will not remove remoteDAO.offline = false; doSyncThen(function() { expect(remoteDAO.array.length).toEqual(4); done(); }); }) }); }); // TODO: is there a server removal path intended? // it('syncs removes from client and server', function(done) { // preloadRemote(); // remoteDAO.offline = false; // doSyncThen(function() { // syncDAO.select().then(function(sink) { // expect(sink.a.length).toEqual(5); // console.log("cache1", cacheDAO.array); // remoteDAO.remove(sink.a[1]); // remoteDAO.offline = true; // syncDAO.remove(sink.a[0]); // remoteDAO.offline = false; // doSyncThen(function() { // expect(remoteDAO.array.length).toEqual(3); // expect(cacheDAO.array.length).toEqual(3); // console.log("remote2", remoteDAO.array); // console.log("cache2", cacheDAO.array); // console.log("sync2", syncRecordDAO.array); // done(); // }); // }) // }); // }); }); describe('JournalDAO', function() { var delegateDAO; var journalDAO; var dao; beforeEach(function() { foam.CLASS({ package: 'test', name: 'JournalModel', properties: [ 'id', 'value' ] }); journalDAO = foam.dao.ArrayDAO.create({ of: foam.dao.JournalEntry }); delegateDAO = foam.dao.ArrayDAO.create({ of: test.JournalModel }); dao = foam.dao.JournalDAO.create({ of: test.JournalModel, delegate: delegateDAO, journal: foam.dao.SequenceNumberDAO.create({ of: foam.dao.JournalEntry, delegate: journalDAO }, foam.__context__) }, foam.__context__); }); function loadItems1() { return Promise.all([ dao.put(test.JournalModel.create({ id: 0, value: 1 }, foam.__context__)), dao.put(test.JournalModel.create({ id: 1, value: 'one' }, foam.__context__)), dao.put(test.JournalModel.create({ id: 2, value: 'a' }, foam.__context__)) ]); } function removeItems2() { return dao.remove(test.JournalModel.create({ id: 1, value: 'two' }, foam.__context__)); } function loadItems3() { return Promise.all([ dao.put(test.JournalModel.create({ id: 0, value: 3 }, foam.__context__)), dao.put(test.JournalModel.create({ id: 2, value: 'c' }, foam.__context__)) ]); } it('records write operations', function(done) { loadItems1().then(function() { expect(journalDAO.array.length).toEqual(3); removeItems2().then(function() { expect(journalDAO.array.length).toEqual(4); loadItems3().then(function() { expect(journalDAO.array.length).toEqual(6); done(); }); }); }); }); it('records enough to rebuild the delegate DAO', function(done) { Promise.all([ loadItems1(), removeItems2(), loadItems3() ]).then(function() { // rebuild from the journal // select() to ensure the ordering is what the journal thinks is correct journalDAO.select().then(function(sink) { var newDAO = foam.dao.ArrayDAO.create({ of: test.JournalModel }); var journal = sink.a; for ( var i = 0; i < journal.length; i++ ) { var entry = journal[i]; if ( entry.isRemove ) newDAO.remove(entry.record); else newDAO.put(entry.record); } // compare newDAO and delegateDAO expect(delegateDAO.array.length).toEqual(newDAO.array.length); for ( var i = 0; i < delegateDAO.array.length; i++ ) { if ( delegateDAO.array[i].compareTo(newDAO.array[i]) !== 0 ) { fail('mismatched results'); } } done(); }); }); }); }); describe('TimingDAO', function() { genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.TimingDAO.create({ delegate: mDAO, of: model, name: 'timingtest', }, foam.__context__)); }); }); describe('LoggingDAO', function() { genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.LoggingDAO.create({ delegate: mDAO, of: model, logger: function() { }, name: 'loggingtest', logReads: true }, foam.__context__)); }); }); describe('NullDAO', function() { it('rejects put operations', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.put().then( function() { fail('put should not be accepted'); }, function(err) { done(); } ); }); it('rejects find operations', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.find(4).then( function() { fail('find should not be accepted'); }, function(err) { done(); } ); }); it('selects as empty', function(done) { var sink = { eof: function() { this.eofCalled++ }, eofCalled: 0, put: function(o) { this.putCalled++ }, putCalled: 0, }; var nDAO = foam.dao.NullDAO.create(); nDAO.select(sink).then(function(sink) { expect(sink.eofCalled).toEqual(1); expect(sink.putCalled).toEqual(0); done(); }); }); it('accepts remove as no-op', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.remove().then(done); }); it('accepts removeAll as no-op', function(done) { var nDAO = foam.dao.NullDAO.create(); nDAO.removeAll().then(done); }); }); describe('TimestampDAO', function() { var mDAO; var sDAO; genericDAOTestBattery(function(model) { mDAO = foam.dao.MDAO.create({ of: model }); return Promise.resolve(foam.dao.SequenceNumberDAO.create({ delegate: mDAO, of: model })); }); beforeEach(function() { jasmine.clock().install(); foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); mDAO = foam.dao.MDAO.create({ of: test.CompA }); sDAO = foam.dao.TimestampDAO.create({ delegate: mDAO, of: test.CompA }); }); afterEach(function() { jasmine.clock().uninstall(); }); it('assigns timestamps to objects missing the value', function(done) { jasmine.clock().mockDate(new Date(0)); jasmine.clock().tick(2000); var a = test.CompA.create({ a: 4 }, foam.__context__); // id not set sDAO.put(a).then(function() { jasmine.clock().tick(2000); return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toBeGreaterThan(0); a = test.CompA.create({ a: 6 }, foam.__context__); // id not set jasmine.clock().tick(2000); return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { jasmine.clock().tick(2000); expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toBeGreaterThan(0); expect(sink.a[0].a).toEqual(4); expect(sink.a[1].id).toBeGreaterThan(sink.a[0].id); expect(sink.a[1].a).toEqual(6); done(); }); }); }); }); }); it('skips assigning to objects with an existing value', function(done) { jasmine.clock().mockDate(new Date(0)); jasmine.clock().tick(2000); var a = test.CompA.create({ id: 3, a: 4 }, foam.__context__); sDAO.put(a).then(function() { jasmine.clock().tick(2000); return mDAO.select().then(function (sink) { expect(sink.a.length).toEqual(1); expect(sink.a[0].id).toEqual(3); a = test.CompA.create({ id: 2, a: 6 }, foam.__context__); jasmine.clock().tick(2000); return sDAO.put(a).then(function() { return mDAO.select().then(function (sink) { jasmine.clock().tick(2000); expect(sink.a.length).toEqual(2); expect(sink.a[0].id).toEqual(2); expect(sink.a[0].a).toEqual(6); expect(sink.a[1].id).toEqual(3); expect(sink.a[1].a).toEqual(4); done(); }); }); }); }); }); }); describe('EasyDAO-permutations', function() { [ { daoType: 'MDAO', }, { daoType: 'LOCAL', }, { daoType: 'MDAO', seqNo: true, seqProperty: 'id' }, { daoType: 'LOCAL', guid: true, seqProperty: 'id' }, { daoType: 'MDAO', logging: true, timing: true, journal: true, dedup: true, contextualize: true }, { daoType: 'MDAO', cache: true, }, // TODO: fix cache issues: // { // daoType: foam.dao.ArrayDAO, // cache: true, // }, // { // daoType: 'LOCAL', // cache: true, // }, // Property name foam.core.Property // debug.js:264 Boolean seqNo false // debug.js:264 Boolean guid false // debug.js:264 Property seqProperty undefined // debug.js:264 Boolean cache false // debug.js:264 Boolean dedup false // debug.js:264 Property journal false // debug.js:264 Boolean contextualize false // debug.js:264 Property daoType foam.dao.IDBDAO // debug.js:264 Boolean autoIndex false // debug.js:264 Boolean syncWithServer false // debug.js:264 Boolean syncPolling true // debug.js:264 String serverUri http://localhost:8000/api // debug.js:264 Boolean isServer false // debug.js:264 Property syncProperty undefined // debug.js:264 Class2 of PropertyClass ].forEach(function(cfg) { genericDAOTestBattery(function(model) { cfg.of = model; var dao = foam.dao.EasyDAO.create(cfg); return dao.removeAll().then(function() { return dao; }); }); }); beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); }); it('throws on seqNo && guid', function() { expect(function() { foam.dao.EasyDAO.create({ of: test.CompA, daoType: 'MDAO', seqNo: true, guid: true, }, foam.__context__); }).toThrow(); }); it('forwards addPropertyIndex', function() { var dao = foam.dao.EasyDAO.create({ of: test.CompA, daoType: foam.dao.MDAO }, foam.__context__); // TODO: mock MDAO, check that these get called through dao.addPropertyIndex(test.CompA.A); dao.addIndex(test.CompA.A.toIndex(dao.mdao.idIndex)); }); it('constructs HTTP ClientDAO', function() { foam.CLASS({ package: 'test', name: 'HTTPBoxMocker', exports: [ 'httpResponse' ], properties: [ 'httpResponse' ] }); var env = test.HTTPBoxMocker.create(undefined, foam.__context__); // TODO: dependency injection reistering is a bit awkward: env.__subContext__.register(test.helpers.MockHTTPBox, 'foam.box.HTTPBox'); var dao = foam.dao.EasyDAO.create({ of: test.CompA, daoType: 'MDAO', syncWithServer: true, serverUri: 'localhost:8888', syncPolling: true, syncProperty: test.CompA.A }, env); }); }); describe('DAO.listen', function() { var dao; var sink; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); dao = foam.dao.ArrayDAO.create({ of: test.CompA }); sink = foam.dao.ArrayDAO.create({ of: test.CompA }); }); it('forwards puts', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao.listen(sink); dao.put(a); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(a); dao.put(b); expect(sink.array.length).toEqual(2); expect(sink.array[1]).toEqual(b); }); it('forwards removes', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); sink.put(a); sink.put(b); dao.put(a); dao.put(b); dao.listen(sink); dao.remove(a); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(b); }); it('covers reset', function() { dao.listen(sink); dao.pub('on', 'reset'); }); it('filters puts with predicate', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); var pred = foam.mlang.predicate.Eq.create({ arg1: test.CompA.A, arg2: 4 }); dao.where(pred).listen(sink); dao.put(a); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(a); dao.put(b); expect(sink.array.length).toEqual(1); expect(sink.array[0]).toEqual(a); }); it('terminates on flow control stop', function() { var a = test.CompA.create({ id: 0, a: 8 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 6 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 4 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 2 }, foam.__context__); var obj; var fcSink = foam.dao.QuickSink.create({ putFn: function(o, fc) { obj = o; fc.stop(); } }); dao.listen(fcSink); dao.put(a); expect(obj).toEqual(a); dao.put(b); expect(obj).toEqual(a); }); it('terminates on flow control error', function() { var a = test.CompA.create({ id: 0, a: 8 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 6 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 4 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 2 }, foam.__context__); var obj; var fcSink = foam.dao.QuickSink.create({ putFn: function(o, fc) { obj = o; fc.error("err!"); } }); dao.listen(fcSink); dao.put(a); expect(obj).toEqual(a); dao.put(b); expect(obj).toEqual(a); }); it('and pipe() listens', function(done) { var a = test.CompA.create({ id: 0, a: 8 }, foam.__context__); var b = test.CompA.create({ id: 1, a: 6 }, foam.__context__); var c = test.CompA.create({ id: 2, a: 4 }, foam.__context__); var d = test.CompA.create({ id: 3, a: 2 }, foam.__context__); dao.put(a); dao.put(b); dao.pipe(sink).then(function(sub) { expect(sink.array.length).toEqual(2); expect(sink.array[0]).toEqual(a); expect(sink.array[1]).toEqual(b); // and we should be listening, too dao.put(c); expect(sink.array.length).toEqual(3); expect(sink.array[2]).toEqual(c); // subscription allows disconnect sub.destroy(); dao.put(d); // no longer listening expect(sink.array.length).toEqual(3); done(); }); }); }); describe('FilteredDAO', function() { var dao; var sink; var m; var l, l2; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); m = foam.mlang.ExpressionsSingleton.create(); dao = foam.dao.ArrayDAO.create({ of: test.CompA }); sink = foam.dao.ArrayDAO.create({ of: test.CompA }); l = function(s, on, evt, obj) { l.evt = evt; l.obj = obj; l.count = ( l.count + 1 ) || 1; }; l2 = function(s, on, evt, obj) { l2.evt = evt; l2.obj = obj; l2.count = ( l2.count + 1 ) || 1; } }); it('filters put events', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao = dao.where(m.EQ(test.CompA.A, 4)); dao.on.sub(l); dao.on.sub(l2); dao.put(a); expect(l.evt).toEqual('put'); expect(l.obj).toEqual(a); expect(l.count).toEqual(1); // since 'b' is filtered out, the put changes to remove to ensure the // listener knows it shouldn't exist dao.put(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); expect(l.count).toEqual(2); }); it('does not filter remove events', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao.put(a); dao.put(b); dao = dao.where(m.EQ(test.CompA.A, 4)); dao.on.sub(l); dao.remove(a); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(a); dao.remove(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); }); it('handles a delegate swap', function() { var a = test.CompA.create({ id: 0, a: 4 }, foam.__context__); var b = test.CompA.create({ id: 4, a: 8 }, foam.__context__); dao = dao.where(m.EQ(test.CompA.A, 4)); dao.on.sub(l); // normal put test dao.put(a); expect(l.evt).toEqual('put'); expect(l.obj).toEqual(a); dao.put(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); // swap a new base dao in delete l.evt; delete l.obj; var newBaseDAO = foam.dao.ArrayDAO.create({ of: test.CompA }); var oldDAO = dao.delegate; dao.delegate = newBaseDAO; expect(l.evt).toEqual('reset'); // filtered put from new base newBaseDAO.put(b); expect(l.evt).toEqual('remove'); expect(l.obj).toEqual(b); delete l.evt; delete l.obj; // old dao does not cause updates oldDAO.put(a); expect(l.evt).toBeUndefined(); expect(l.obj).toBeUndefined(); // cover destructor dao.destroy(); }); }); describe('String.daoize', function() { it('handles a model name', function() { expect(foam.String.daoize('MyModel')).toEqual('myModelDAO'); }); it('handles a model name with package', function() { expect(foam.String.daoize('test.package.PkgModel')).toEqual('test_package_PkgModelDAO'); }); }); describe('Relationship', function() { foam.CLASS({ package: 'test', name: 'RelA', properties: [ 'bRef' ] }); foam.CLASS({ package: 'test', name: 'RelB', properties: [ 'aRef' ] }); foam.CLASS({ package: 'test', name: 'relEnv', exports: [ 'test_RelADAO', 'test_RelBDAO' ], properties: [ { name: 'test.RelADAO', factory: function() { return foam.dao.ArrayDAO.create(); } }, { name: 'test.RelBDAO', factory: function() { return foam.dao.ArrayDAO.create(); } } ] }); foam.RELATIONSHIP({ name: 'children', inverseName: 'parent', sourceModel: 'test.RelA', //sourceProperties: [ 'bRef' ], targetModel: 'test.RelB', //targetProperties: [ 'aRef' ], }); it('has relationship DAOs', function() { var env = test.relEnv.create(undefined, foam.__context__); var relObjA = test.RelA.create(undefined, env); var relDAO = relObjA.children; }) }); describe('MultiPartID MDAO support', function() { var mDAO; beforeEach(function() { foam.CLASS({ package: 'test', name: 'Mpid', ids: [ 'a', 'b' ], properties: [ 'a', 'b', 'c' ] }); mDAO = foam.dao.MDAO.create({ of: test.Mpid }); }); afterEach(function() { mDAO = null; }); it('generates a proper ID index', function(done) { mDAO.put(test.Mpid.create({ a: 1, b: 1, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 1, b: 2, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 1, b: 1, c: 2 }, foam.__context__)); // update mDAO.put(test.Mpid.create({ a: 1, b: 2, c: 2 }, foam.__context__)); // update mDAO.put(test.Mpid.create({ a: 2, b: 1, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 2, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 2, c: 2 }, foam.__context__)); // update mDAO.select(foam.mlang.sink.Count.create()).then(function(counter) { expect(counter.value).toEqual(4); done(); }); }); it('finds by multipart ID array', function(done) { mDAO.put(test.Mpid.create({ a: 1, b: 1, c: 1 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 1, b: 2, c: 2 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 1, c: 3 }, foam.__context__)); // add mDAO.put(test.Mpid.create({ a: 2, b: 2, c: 4 }, foam.__context__)); // add mDAO.find([ 2, 1 ]).then(function(obj) { // with array key expect(obj.c).toEqual(3); mDAO.find(test.Mpid.create({ a: 2, b: 2 }, foam.__context__).id) // array from MultiPartID .then(function(obj2) { expect(obj2.c).toEqual(4); done(); }); }); }); }); describe('NoSelectAllDAO', function() { var dao; var srcdao; var sink; var m; beforeEach(function() { foam.CLASS({ package: 'test', name: 'CompA', properties: [ 'id', 'a' ] }); m = foam.mlang.ExpressionsSingleton.create(); srcdao = foam.dao.ArrayDAO.create({ of: test.CompA }); sink = foam.dao.ArrayDAO.create({ of: test.CompA }); dao = foam.dao.NoSelectAllDAO.create({ of: test.CompA, delegate: srcdao }); dao.put(test.CompA.create({ id: 0, a: 4 }, foam.__context__)); dao.put(test.CompA.create({ id: 2, a: 77 }, foam.__context__)); dao.put(test.CompA.create({ id: 3, a: 8 }, foam.__context__)); dao.put(test.CompA.create({ id: 4, a: 99 }, foam.__context__)); }); it('Does not forward select() with no restrictions', function(done) { dao.select(sink).then(function(snk) { expect(snk.array.length).toEqual(0); done(); }); }); it('Forwards select() with a predicate', function(done) { dao.where(m.LT(test.CompA.A, 20)).select(sink).then(function(snk) { expect(snk.array.length).toEqual(2); done(); }); }); it('Forwards select() with a limit', function(done) { dao.limit(2).select(sink).then(function(snk) { expect(snk.array.length).toEqual(2); done(); }); }); it('Forwards select() with a skip', function(done) { dao.skip(1).select(sink).then(function(snk) { expect(snk.array.length).toEqual(3); done(); }); }); it('Does not forward select() with an infinite limit', function(done) { dao.limit(Math.Infinity).select(sink).then(function(snk) { expect(snk.array.length).toEqual(0); done(); }); }); });
Final DAO related __context__ removals in tests
test/src/lib/dao.js
Final DAO related __context__ removals in tests
<ide><path>est/src/lib/dao.js <ide> var sink = foam.dao.PredicatedSink.create({ <ide> predicate: fakePredicate, <ide> delegate: foam.dao.ArraySink.create() <del> }, foam.__context__); <add> }); <ide> <ide> var a = test.CompA.create({ id: 0, a: 3 }, foam.__context__); <ide> var b = test.CompA.create({ id: 1, a: 5 }, foam.__context__); <ide> var sink = foam.dao.PredicatedSink.create({ <ide> predicate: fakePredicate, <ide> delegate: foam.dao.ArrayDAO.create() <del> }, foam.__context__); <add> }); <ide> <ide> var a = test.CompA.create({ id: 0, a: 3 }, foam.__context__); <ide> var b = test.CompA.create({ id: 1, a: 5 }, foam.__context__); <ide> var sink = foam.dao.LimitedSink.create({ <ide> limit: 3, <ide> delegate: foam.dao.ArrayDAO.create() <del> }, foam.__context__); <add> }); <ide> var fc = foam.dao.FlowControl.create(); <ide> <ide> var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); <ide> var sink = foam.dao.LimitedSink.create({ <ide> limit: 3, <ide> delegate: foam.dao.ArrayDAO.create() <del> }, foam.__context__); <add> }); <ide> var fc = foam.dao.FlowControl.create(); <ide> <ide> var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); <ide> var sink = foam.dao.SkipSink.create({ <ide> skip: 2, <ide> delegate: foam.dao.ArrayDAO.create() <del> }, foam.__context__); <add> }); <ide> <ide> var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); <ide> var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); <ide> var sink = foam.dao.SkipSink.create({ <ide> skip: 2, <ide> delegate: foam.dao.ArrayDAO.create() <del> }, foam.__context__); <add> }); <ide> <ide> var a = test.CompA.create({ id: 0, a: 9 }, foam.__context__); <ide> var b = test.CompA.create({ id: 1, a: 7 }, foam.__context__); <ide> // test caching against an IDBDAO remote and MDAO cache. <ide> genericDAOTestBattery(function(model) { <ide> var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) <del> .create({ name: '_test_lazyCache_', of: model }, foam.__context__); <add> .create({ name: '_test_lazyCache_', of: model }); <ide> return idbDAO.removeAll().then(function() { <ide> var mDAO = foam.dao.MDAO.create({ of: model }); <ide> return foam.dao.LazyCacheDAO.create({ <ide> delegate: idbDAO, <ide> cache: mDAO, <ide> cacheOnSelect: true <del> }, foam.__context__); <add> }); <ide> }); <ide> }); <ide> }); <ide> // test caching against an IDBDAO remote and MDAO cache. <ide> genericDAOTestBattery(function(model) { <ide> var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) <del> .create({ name: '_test_lazyCache_', of: model }, foam.__context__); <add> .create({ name: '_test_lazyCache_', of: model }); <ide> return idbDAO.removeAll().then(function() { <ide> var mDAO = foam.dao.MDAO.create({ of: model }); <ide> return foam.dao.LazyCacheDAO.create({ <ide> delegate: idbDAO, <ide> cache: mDAO, <ide> cacheOnSelect: false <del> }, foam.__context__); <add> }); <ide> }); <ide> }); <ide> }); <ide> describe('CachingDAO', function() { <ide> genericDAOTestBattery(function(model) { <ide> var idbDAO = ( foam.dao.IDBDAO || foam.dao.LocalStorageDAO ) <del> .create({ name: '_test_readCache_', of: model }, foam.__context__); <add> .create({ name: '_test_readCache_', of: model }); <ide> return idbDAO.removeAll().then(function() { <ide> var mDAO = foam.dao.MDAO.create({ of: model }); <ide> return foam.dao.CachingDAO.create({ src: idbDAO, cache: mDAO }); <ide> return Promise.resolve(foam.dao.SequenceNumberDAO.create({ <ide> delegate: mDAO, <ide> of: model <del> }, foam.__context__)); <add> })); <ide> }); <ide> <ide> beforeEach(function() { <ide> sDAO = foam.dao.SequenceNumberDAO.create({ <ide> delegate: mDAO, <ide> of: test.CompA <del> }, foam.__context__); <add> }); <ide> }); <ide> <ide> it('assigns sequence numbers to objects missing the value', function(done) { <ide> return Promise.resolve(foam.dao.GUIDDAO.create({ <ide> delegate: mDAO, <ide> of: model <del> }, foam.__context__)); <add> })); <ide> }); <ide> <ide> beforeEach(function() { <ide> lruManager = foam.dao.LRUDAOManager.create({ <ide> dao: mDAO, <ide> maxSize: 4 <del> }, foam.__context__); <add> }); <ide> }); <ide> afterEach(function() { <ide> mDAO = null; <ide> delegate: cacheDAO, <ide> syncRecordDAO: syncRecordDAO, <ide> polling: false, // Polling simulated by invasive calls to sync() <del> }, foam.__context__); <add> }); <ide> }); <ide> <ide> // isolate sync/timeout call code, as it may change with SyncDAO's implementation <ide> journal: foam.dao.SequenceNumberDAO.create({ <ide> of: foam.dao.JournalEntry, <ide> delegate: journalDAO <del> }, foam.__context__) <del> }, foam.__context__); <add> }) <add> }); <ide> <ide> }); <ide> <ide> delegate: mDAO, <ide> of: model, <ide> name: 'timingtest', <del> }, foam.__context__)); <add> })); <ide> }); <ide> <ide> }); <ide> logger: function() { }, <ide> name: 'loggingtest', <ide> logReads: true <del> }, foam.__context__)); <add> })); <ide> }); <ide> <ide> }); <ide> daoType: 'MDAO', <ide> seqNo: true, <ide> guid: true, <del> }, foam.__context__); <add> }); <ide> }).toThrow(); <ide> }); <ide> <ide> var dao = foam.dao.EasyDAO.create({ <ide> of: test.CompA, <ide> daoType: foam.dao.MDAO <del> }, foam.__context__); <add> }); <ide> // TODO: mock MDAO, check that these get called through <ide> dao.addPropertyIndex(test.CompA.A); <ide> dao.addIndex(test.CompA.A.toIndex(dao.mdao.idIndex));
Java
apache-2.0
ea20d67545facb2080fcd771bab7399827713ae3
0
datazup/dzupper-expression
package base; import junit.framework.Assert; import org.datazup.utils.DateTimeUtils; import org.datazup.utils.JsonUtils; import org.joda.time.DateTime; import org.junit.Test; import java.util.HashMap; import java.util.Map; /** * Created by ninel on 11/30/16. */ public class OtherTest { @Test public void dateTimeTwitterFormatTest(){ Object twitterCreatedAt = "Wed Aug 27 13:08:45 +0900 2008"; DateTime dt = DateTimeUtils.resolve(twitterCreatedAt); Assert.assertNotNull(dt); } @Test public void isJsonKeyValid(){ Map<String,Object> map = new HashMap<>(); map.put("ime~prezime", 123); map.put("ime#prezime", 234); map.put("ime%prezime", 456); map.put("ime.prezime", 567); String json = JsonUtils.getJsonFromObject(map); Map<String,Object> map1 = JsonUtils.getMapFromJson(json); System.out.println(JsonUtils.getJsonFromObject(map1)); } }
src/test/java/base/OtherTest.java
package base; import junit.framework.Assert; import org.datazup.utils.DateTimeUtils; import org.joda.time.DateTime; import org.junit.Test; /** * Created by ninel on 11/30/16. */ public class OtherTest { @Test public void dateTimeTwitterFormatTest(){ Object twitterCreatedAt = "Wed Aug 27 13:08:45 +0900 2008"; DateTime dt = DateTimeUtils.resolve(twitterCreatedAt); Assert.assertNotNull(dt); } }
small test for other types
src/test/java/base/OtherTest.java
small test for other types
<ide><path>rc/test/java/base/OtherTest.java <ide> <ide> import junit.framework.Assert; <ide> import org.datazup.utils.DateTimeUtils; <add>import org.datazup.utils.JsonUtils; <ide> import org.joda.time.DateTime; <ide> import org.junit.Test; <add> <add>import java.util.HashMap; <add>import java.util.Map; <ide> <ide> /** <ide> * Created by ninel on 11/30/16. <ide> DateTime dt = DateTimeUtils.resolve(twitterCreatedAt); <ide> Assert.assertNotNull(dt); <ide> } <add> <add> @Test <add> public void isJsonKeyValid(){ <add> Map<String,Object> map = new HashMap<>(); <add> <add> map.put("ime~prezime", 123); <add> map.put("ime#prezime", 234); <add> map.put("ime%prezime", 456); <add> map.put("ime.prezime", 567); <add> String json = JsonUtils.getJsonFromObject(map); <add> <add> Map<String,Object> map1 = JsonUtils.getMapFromJson(json); <add> <add> System.out.println(JsonUtils.getJsonFromObject(map1)); <add> } <ide> }
Java
lgpl-2.1
51902180143966446edcb60deda1f48a861a92fa
0
cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl
package org.cytoscape.search.internal.util; /* * #%L * Cytoscape Search Impl (search-impl) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2006 - 2013 The Cytoscape Consortium * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.regex.Pattern; public final class EnhancedSearchUtils { public static final String SEARCH_STRING = "\\s"; public static final String REPLACE_STRING = "_"; public static final String LOWERCASE_AND = " and "; public static final String LOWERCASE_OR = " or "; public static final String LOWERCASE_NOT = " not "; public static final String LOWERCASE_TO = " to "; public static final String UPPERCASE_AND = " AND "; public static final String UPPERCASE_OR = " OR "; public static final String UPPERCASE_NOT = " NOT "; public static final String UPPERCASE_TO = " TO "; /** * Replaces whitespace characters with underline. Method: Search for * SEARCH_STRING, replace with REPLACE_STRING. */ public static String replaceWhitespace(final String searchTerm) { if (searchTerm == null){ return ""; } Pattern searchPattern = Pattern.compile(SEARCH_STRING); String[] result = searchPattern.split(searchTerm); StringBuffer sbuf = new StringBuffer(); sbuf.append(result[0]); for (int i = 1; i < result.length; i++) { sbuf.append(REPLACE_STRING); sbuf.append(result[i]); } return sbuf.toString(); } /** * This special lowercase handling turns a query string into lowercase, * and logical operators (AND, OR, NOT) into uppercase. */ public static String queryToLowerCase (final String queryString) { String lowercaseQuery = queryString.toLowerCase(); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_AND, UPPERCASE_AND); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_OR, UPPERCASE_OR); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_NOT, UPPERCASE_NOT); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_TO, UPPERCASE_TO); return lowercaseQuery; } private EnhancedSearchUtils() { } }
search-impl/src/main/java/org/cytoscape/search/internal/util/EnhancedSearchUtils.java
package org.cytoscape.search.internal.util; /* * #%L * Cytoscape Search Impl (search-impl) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2006 - 2013 The Cytoscape Consortium * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.regex.Pattern; public final class EnhancedSearchUtils { public static final String SEARCH_STRING = "\\s"; public static final String REPLACE_STRING = "_"; public static final String LOWERCASE_AND = " and "; public static final String LOWERCASE_OR = " or "; public static final String LOWERCASE_NOT = " not "; public static final String LOWERCASE_TO = " to "; public static final String UPPERCASE_AND = " AND "; public static final String UPPERCASE_OR = " OR "; public static final String UPPERCASE_NOT = " NOT "; public static final String UPPERCASE_TO = " TO "; /** * Replaces whitespace characters with underline. Method: Search for * SEARCH_STRING, replace with REPLACE_STRING. */ public static String replaceWhitespace(String searchTerm) { String replaceTerm = ""; if (searchTerm == null){ return replaceTerm; } Pattern searchPattern = Pattern.compile(SEARCH_STRING); String[] result = searchPattern.split(searchTerm); replaceTerm = result[0]; for (int i = 1; i < result.length; i++) { replaceTerm = replaceTerm + REPLACE_STRING + result[i]; } return replaceTerm; } /** * This special lowercase handling turns a query string into lowercase, * and logical operators (AND, OR, NOT) into uppercase. */ public static String queryToLowerCase (String queryString) { String lowercaseQuery; lowercaseQuery = queryString; lowercaseQuery = lowercaseQuery.toLowerCase(); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_AND, UPPERCASE_AND); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_OR, UPPERCASE_OR); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_NOT, UPPERCASE_NOT); lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_TO, UPPERCASE_TO); return lowercaseQuery; } private EnhancedSearchUtils() { } }
switched code to use StringBuilder which is more efficient
search-impl/src/main/java/org/cytoscape/search/internal/util/EnhancedSearchUtils.java
switched code to use StringBuilder which is more efficient
<ide><path>earch-impl/src/main/java/org/cytoscape/search/internal/util/EnhancedSearchUtils.java <ide> * Replaces whitespace characters with underline. Method: Search for <ide> * SEARCH_STRING, replace with REPLACE_STRING. <ide> */ <del> public static String replaceWhitespace(String searchTerm) { <del> String replaceTerm = ""; <add> public static String replaceWhitespace(final String searchTerm) { <ide> <ide> if (searchTerm == null){ <del> return replaceTerm; <add> return ""; <ide> } <ide> <ide> Pattern searchPattern = Pattern.compile(SEARCH_STRING); <ide> <ide> String[] result = searchPattern.split(searchTerm); <del> replaceTerm = result[0]; <add> StringBuffer sbuf = new StringBuffer(); <add> sbuf.append(result[0]); <ide> for (int i = 1; i < result.length; i++) { <del> replaceTerm = replaceTerm + REPLACE_STRING + result[i]; <add> sbuf.append(REPLACE_STRING); <add> sbuf.append(result[i]); <ide> } <ide> <del> return replaceTerm; <add> return sbuf.toString(); <ide> } <ide> <ide> /** <ide> * This special lowercase handling turns a query string into lowercase, <ide> * and logical operators (AND, OR, NOT) into uppercase. <ide> */ <del> public static String queryToLowerCase (String queryString) { <add> public static String queryToLowerCase (final String queryString) { <ide> <del> String lowercaseQuery; <del> <del> lowercaseQuery = queryString; <del> lowercaseQuery = lowercaseQuery.toLowerCase(); <add> String lowercaseQuery = queryString.toLowerCase(); <ide> <ide> lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_AND, UPPERCASE_AND); <ide> lowercaseQuery = lowercaseQuery.replaceAll(LOWERCASE_OR, UPPERCASE_OR);
Java
apache-2.0
d0b4bdb24e77a08181e07f13d7c5794d39c6203c
0
tweise/apex-core,mattqzhang/apex-core,deepak-narkhede/apex-core,vrozov/apex-core,mattqzhang/apex-core,deepak-narkhede/apex-core,devtagare/incubator-apex-core,brightchen/incubator-apex-core,devtagare/incubator-apex-core,brightchen/apex-core,sandeshh/apex-core,PramodSSImmaneni/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,vrozov/incubator-apex-core,tweise/incubator-apex-core,devtagare/incubator-apex-core,vrozov/incubator-apex-core,tweise/apex-core,tushargosavi/apex-core,tushargosavi/apex-core,PramodSSImmaneni/incubator-apex-core,ishark/incubator-apex-core,apache/incubator-apex-core,apache/incubator-apex-core,vrozov/incubator-apex-core,ishark/incubator-apex-core,tushargosavi/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,tushargosavi/incubator-apex-core,vrozov/apex-core,simplifi-it/otterx,deepak-narkhede/apex-core,ishark/incubator-apex-core,tushargosavi/incubator-apex-core,tweise/incubator-apex-core,tushargosavi/apex-core,brightchen/apex-core,brightchen/apex-core,tweise/apex-core,sandeshh/apex-core,PramodSSImmaneni/apex-core,brightchen/incubator-apex-core,sandeshh/incubator-apex-core,simplifi-it/otterx,apache/incubator-apex-core,mattqzhang/apex-core,sandeshh/incubator-apex-core,PramodSSImmaneni/apex-core,PramodSSImmaneni/apex-core,sandeshh/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,vrozov/apex-core,tweise/incubator-apex-core,sandeshh/apex-core,simplifi-it/otterx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.stram.plan.physical; import java.io.IOException; import java.io.Serializable; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.datatorrent.api.Context.OperatorContext; import com.datatorrent.api.Context.PortContext; import com.datatorrent.api.*; import com.datatorrent.api.DAG.Locality; import com.datatorrent.api.Operator.InputPort; import com.datatorrent.api.Partitioner.Partition; import com.datatorrent.api.Partitioner.PartitionKeys; import com.datatorrent.api.StatsListener.OperatorRequest; import com.datatorrent.api.annotation.Stateless; import com.datatorrent.common.util.AsyncFSStorageAgent; import com.datatorrent.netlet.util.DTThrowable; import com.datatorrent.stram.Journal.Recoverable; import com.datatorrent.stram.api.Checkpoint; import com.datatorrent.stram.api.StramEvent; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.StramToNodeRequest; import com.datatorrent.stram.plan.logical.LogicalPlan; import com.datatorrent.stram.plan.logical.LogicalPlan.InputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OutputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.StreamMeta; import com.datatorrent.stram.plan.logical.StreamCodecWrapperForPersistance; import com.datatorrent.stram.plan.physical.PTOperator.HostOperatorSet; import com.datatorrent.stram.plan.physical.PTOperator.PTInput; import com.datatorrent.stram.plan.physical.PTOperator.PTOutput; /** * Translates the logical DAG into physical model. Is the initial query planner * and performs dynamic changes. * <p> * Attributes in the logical DAG affect how the physical plan is derived. * Examples include partitioning schemes, resource allocation, recovery * semantics etc.<br> * * The current implementation does not dynamically change or optimize allocation * of containers. The maximum number of containers and container size can be * specified per application, but all containers are requested at the same size * and execution will block until all containers were allocated by the resource * manager. Future enhancements will allow to define resource constraints at the * operator level and elasticity in resource allocation.<br> * * @since 0.3.2 */ public class PhysicalPlan implements Serializable { private static final long serialVersionUID = 201312112033L; private static final Logger LOG = LoggerFactory.getLogger(PhysicalPlan.class); public static class LoadIndicator { public final int indicator; public final String note; LoadIndicator(int indicator, String note) { this.indicator = indicator; this.note = note; } } private final AtomicInteger idSequence = new AtomicInteger(); final AtomicInteger containerSeq = new AtomicInteger(); private LinkedHashMap<OperatorMeta, PMapping> logicalToPTOperator = new LinkedHashMap<OperatorMeta, PMapping>(); private final List<PTContainer> containers = new CopyOnWriteArrayList<PTContainer>(); private final LogicalPlan dag; private transient final PlanContext ctx; private int maxContainers = 1; private int availableMemoryMB = Integer.MAX_VALUE; private final LocalityPrefs localityPrefs = new LocalityPrefs(); private final LocalityPrefs inlinePrefs = new LocalityPrefs(); final Set<PTOperator> deployOpers = Sets.newHashSet(); final Map<PTOperator, Operator> newOpers = Maps.newHashMap(); final Set<PTOperator> undeployOpers = Sets.newHashSet(); final ConcurrentMap<Integer, PTOperator> allOperators = Maps.newConcurrentMap(); private final ConcurrentMap<OperatorMeta, OperatorMeta> pendingRepartition = Maps.newConcurrentMap(); private final AtomicInteger strCodecIdSequence = new AtomicInteger(); private final Map<StreamCodec<?>, Integer> streamCodecIdentifiers = Maps.newHashMap(); private PTContainer getContainer(int index) { if (index >= containers.size()) { if (index >= maxContainers) { index = maxContainers - 1; } for (int i=containers.size(); i<index+1; i++) { containers.add(i, new PTContainer(this)); } } return containers.get(index); } /** * Interface to execution context that can be mocked for plan testing. */ public interface PlanContext { /** * Record an event in the event log * * @param ev The event * */ public void recordEventAsync(StramEvent ev); /** * Request deployment change as sequence of undeploy, container start and deploy groups with dependency. * Called on initial plan and on dynamic changes during execution. * @param releaseContainers * @param undeploy * @param startContainers * @param deploy */ public void deploy(Set<PTContainer> releaseContainers, Collection<PTOperator> undeploy, Set<PTContainer> startContainers, Collection<PTOperator> deploy); /** * Trigger event to perform plan modification. * @param r */ public void dispatch(Runnable r); /** * Write the recoverable operation to the log. * @param operation */ public void writeJournal(Recoverable operation); public void addOperatorRequest(PTOperator oper, StramToNodeRequest request); } private static class StatsListenerProxy implements StatsListener, Serializable { private static final long serialVersionUID = 201312112033L; final private OperatorMeta om; private StatsListenerProxy(OperatorMeta om) { this.om = om; } @Override public Response processStats(BatchedOperatorStats stats) { return ((StatsListener)om.getOperator()).processStats(stats); } } /** * The logical operator with physical plan info tagged on. */ public static class PMapping implements java.io.Serializable { private static final long serialVersionUID = 201312112033L; final private OperatorMeta logicalOperator; private List<PTOperator> partitions = new LinkedList<PTOperator>(); private final Map<LogicalPlan.OutputPortMeta, StreamMapping> outputStreams = Maps.newHashMap(); private List<StatsListener> statsHandlers; /** * Operators that form a parallel partition */ private Set<OperatorMeta> parallelPartitions = Sets.newHashSet(); private PMapping(OperatorMeta om) { this.logicalOperator = om; } private void addPartition(PTOperator p) { partitions.add(p); p.statsListeners = this.statsHandlers; } /** * Return all partitions and unifiers, except MxN unifiers * @return */ private Collection<PTOperator> getAllOperators() { Collection<PTOperator> c = new ArrayList<PTOperator>(partitions.size() + 1); c.addAll(partitions); for (StreamMapping ug : outputStreams.values()) { ug.addTo(c); } return c; } @Override public String toString() { return logicalOperator.toString(); } } private class LocalityPref implements java.io.Serializable { private static final long serialVersionUID = 201312112033L; String host; Set<PMapping> operators = Sets.newHashSet(); } /** * Group logical operators by locality constraint. Used to derive locality * groupings for physical operators, which are used when assigning containers * and requesting resources from the scheduler. */ private class LocalityPrefs implements java.io.Serializable { private static final long serialVersionUID = 201312112033L; private final Map<PMapping, LocalityPref> prefs = Maps.newHashMap(); private final AtomicInteger groupSeq = new AtomicInteger(); void add(PMapping m, String group) { if (group != null) { LocalityPref pref = null; for (LocalityPref lp : prefs.values()) { if (group.equals(lp.host)) { lp.operators.add(m); pref = lp; break; } } if (pref == null) { pref = new LocalityPref(); pref.host = group; pref.operators.add(m); this.prefs.put(m, pref); } } } // if netbeans is not smart, don't produce warnings in other IDE //@SuppressWarnings("null") /* for lp2.operators.add(m1); line below - netbeans is not very smart; you don't be an idiot! */ void setLocal(PMapping m1, PMapping m2) { LocalityPref lp1 = prefs.get(m1); LocalityPref lp2 = prefs.get(m2); if (lp1 == null && lp2 == null) { lp1 = lp2 = new LocalityPref(); lp1.host = "host" + groupSeq.incrementAndGet(); lp1.operators.add(m1); lp1.operators.add(m2); } else if (lp1 != null && lp2 != null) { // check if we can combine if (StringUtils.equals(lp1.host, lp2.host)) { lp1.operators.addAll(lp2.operators); lp2.operators.addAll(lp1.operators); } else { LOG.warn("Node locality conflict {} {}", m1, m2); } } else { if (lp1 == null) { lp2.operators.add(m1); lp1 = lp2; } else { lp1.operators.add(m2); lp2 = lp1; } } prefs.put(m1, lp1); prefs.put(m2, lp2); } } /** * * @param dag * @param ctx */ public PhysicalPlan(LogicalPlan dag, PlanContext ctx) { this.dag = dag; this.ctx = ctx; this.maxContainers = Math.max(dag.getMaxContainerCount(), 1); LOG.debug("Max containers: {}", this.maxContainers); Stack<OperatorMeta> pendingNodes = new Stack<OperatorMeta>(); // Add logging operators for streams if not added already updatePersistOperatorStreamCodec(dag); for (OperatorMeta n : dag.getAllOperators()) { pendingNodes.push(n); } while (!pendingNodes.isEmpty()) { OperatorMeta n = pendingNodes.pop(); if (this.logicalToPTOperator.containsKey(n)) { // already processed as upstream dependency continue; } boolean upstreamDeployed = true; for (StreamMeta s : n.getInputStreams().values()) { if (s.getSource() != null && !this.logicalToPTOperator.containsKey(s.getSource().getOperatorMeta())) { pendingNodes.push(n); pendingNodes.push(s.getSource().getOperatorMeta()); upstreamDeployed = false; break; } } if (upstreamDeployed) { addLogicalOperator(n); } } updatePartitionsInfoForPersistOperator(dag); // assign operators to containers int groupCount = 0; Set<PTOperator> deployOperators = Sets.newHashSet(); for (Map.Entry<OperatorMeta, PMapping> e : logicalToPTOperator.entrySet()) { for (PTOperator oper : e.getValue().getAllOperators()) { if (oper.container == null) { PTContainer container = getContainer((groupCount++) % maxContainers); if (!container.operators.isEmpty()) { LOG.warn("Operator {} shares container without locality contraint due to insufficient resources.", oper); } Set<PTOperator> inlineSet = oper.getGrouping(Locality.CONTAINER_LOCAL).getOperatorSet(); if (!inlineSet.isEmpty()) { // process inline operators for (PTOperator inlineOper : inlineSet) { setContainer(inlineOper, container); } } else { setContainer(oper, container); } deployOperators.addAll(container.operators); } } } for (PTContainer container : containers) { updateContainerMemoryWithBufferServer(container); container.setRequiredVCores(getVCores(container.getOperators())); } for (Map.Entry<PTOperator, Operator> operEntry : this.newOpers.entrySet()) { initCheckpoint(operEntry.getKey(), operEntry.getValue(), Checkpoint.INITIAL_CHECKPOINT); } // request initial deployment ctx.deploy(Collections.<PTContainer>emptySet(), Collections.<PTOperator>emptySet(), Sets.newHashSet(containers), deployOperators); this.newOpers.clear(); this.deployOpers.clear(); this.undeployOpers.clear(); } private void updatePartitionsInfoForPersistOperator(LogicalPlan dag) { // Add Partition mask and partition keys of Sinks to persist to Wrapper // StreamCodec for persist operator try { for (OperatorMeta n : dag.getAllOperators()) { for (StreamMeta s : n.getOutputStreams().values()) { if (s.getPersistOperator() != null) { InputPortMeta persistInputPort = s.getPersistOperatorInputPort(); StreamCodecWrapperForPersistance<?> persistCodec = (StreamCodecWrapperForPersistance<?>) persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); if (persistCodec == null) continue; // Logging is enabled for the stream for (InputPortMeta portMeta : s.getSinksToPersist()) { updatePersistOperatorWithSinkPartitions(persistInputPort, s.getPersistOperator(), persistCodec, portMeta); } } // Check partitioning for persist operators per sink too for (Entry<InputPortMeta, InputPortMeta> entry : s.sinkSpecificPersistInputPortMap.entrySet()) { InputPortMeta persistInputPort = entry.getValue(); StreamCodec<?> codec = persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); if (codec != null) { if (codec instanceof StreamCodecWrapperForPersistance) { StreamCodecWrapperForPersistance<?> persistCodec = (StreamCodecWrapperForPersistance<?>) codec; updatePersistOperatorWithSinkPartitions(persistInputPort, s.sinkSpecificPersistOperatorMap.get(entry.getKey()), persistCodec, entry.getKey()); } } } } } } catch (Exception e) { DTThrowable.wrapIfChecked(e); } } private void updatePersistOperatorWithSinkPartitions(InputPortMeta persistInputPort, OperatorMeta persistOperatorMeta, StreamCodecWrapperForPersistance<?> persistCodec, InputPortMeta sinkPortMeta) { Collection<PTOperator> ptOperators = getOperators(sinkPortMeta.getOperatorWrapper()); Collection<PartitionKeys> partitionKeysList = new ArrayList<PartitionKeys>(); for (PTOperator p : ptOperators) { PartitionKeys keys = p.partitionKeys.get(sinkPortMeta); partitionKeysList.add(keys); } persistCodec.inputPortToPartitionMap.put(sinkPortMeta, partitionKeysList); } private void updatePersistOperatorStreamCodec(LogicalPlan dag) { HashMap<StreamMeta, StreamCodec<?>> streamMetaToCodecMap = new HashMap<StreamMeta, StreamCodec<?>>(); try { for (OperatorMeta n : dag.getAllOperators()) { for (StreamMeta s : n.getOutputStreams().values()) { if (s.getPersistOperator() != null) { Map<InputPortMeta, StreamCodec<?>> inputStreamCodecs = new HashMap<>(); // Logging is enabled for the stream for (InputPortMeta portMeta : s.getSinksToPersist()) { InputPort<?> port = portMeta.getPortObject(); StreamCodec<?> inputStreamCodec = (portMeta.getValue(PortContext.STREAM_CODEC) != null) ? portMeta.getValue(PortContext.STREAM_CODEC) : port.getStreamCodec(); if (inputStreamCodec != null) { boolean alreadyAdded = false; for (StreamCodec<?> codec : inputStreamCodecs.values()) { if (inputStreamCodec.equals(codec)) { alreadyAdded = true; break; } } if (!alreadyAdded) { inputStreamCodecs.put(portMeta, inputStreamCodec); } } } if (inputStreamCodecs.isEmpty()) { // Stream codec not specified // So everything out of Source should be captured without any // StreamCodec // Do nothing } else { // Create Wrapper codec for Stream persistence using all unique // stream codecs // Logger should write merged or union of all input stream codecs StreamCodec<?> specifiedCodecForLogger = (s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) != null) ? s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) : s.getPersistOperatorInputPort().getPortObject().getStreamCodec(); @SuppressWarnings({ "unchecked", "rawtypes" }) StreamCodecWrapperForPersistance<Object> codec = new StreamCodecWrapperForPersistance(inputStreamCodecs, specifiedCodecForLogger); streamMetaToCodecMap.put(s, codec); } } } } for (java.util.Map.Entry<StreamMeta, StreamCodec<?>> entry : streamMetaToCodecMap.entrySet()) { dag.setInputPortAttribute(entry.getKey().getPersistOperatorInputPort().getPortObject(), PortContext.STREAM_CODEC, entry.getValue()); } } catch (Exception e) { DTThrowable.wrapIfChecked(e); } } private void setContainer(PTOperator pOperator, PTContainer container) { LOG.debug("Setting container {} for {}", container, pOperator); assert (pOperator.container == null) : "Container already assigned for " + pOperator; pOperator.container = container; container.operators.add(pOperator); int upStreamUnifierMemory = 0; if (!pOperator.upstreamMerge.isEmpty()) { for (Map.Entry<InputPortMeta, PTOperator> mEntry : pOperator.upstreamMerge.entrySet()) { assert (mEntry.getValue().container == null) : "Container already assigned for " + mEntry.getValue(); mEntry.getValue().container = container; container.operators.add(mEntry.getValue()); upStreamUnifierMemory += mEntry.getValue().getOperatorMeta().getValue(OperatorContext.MEMORY_MB); } } int memoryMB = pOperator.getOperatorMeta().getValue(OperatorContext.MEMORY_MB) + upStreamUnifierMemory; container.setRequiredMemoryMB(container.getRequiredMemoryMB() + memoryMB); } private void updateContainerMemoryWithBufferServer(PTContainer container) { int bufferServerMemory = 0; for (PTOperator operator : container.getOperators()) { bufferServerMemory += operator.getBufferServerMemory(); } container.setRequiredMemoryMB(container.getRequiredMemoryMB() + bufferServerMemory); } /** * This returns the vCores for a set of operators in a container. This forms the group of thread_local operators and get the maximum value of the group * * @param operators The container local operators * @return the number of vcores required for a container */ private int getVCores(Collection<PTOperator> operators) { // this forms the groups of thread local operators in the given container HashMap<PTOperator, Set<PTOperator>> groupMap = new HashMap<PTOperator, Set<PTOperator>>(); for (PTOperator operator : operators) { Set<PTOperator> group = new HashSet<PTOperator>(); group.add(operator); groupMap.put(operator, group); } int vCores = 0; for (PTOperator operator : operators) { Set<PTOperator> threadLocal = operator.getThreadLocalOperators(); if (threadLocal != null) { Set<PTOperator> group = groupMap.get(operator); for (PTOperator operator1 : threadLocal) { group.addAll(groupMap.get(operator1)); } for (PTOperator operator1 : group) { groupMap.put(operator1, group); } } } Set<PTOperator> visitedOperators = new HashSet<PTOperator>(); for (Map.Entry<PTOperator, Set<PTOperator>> group : groupMap.entrySet()) { if (!visitedOperators.contains(group.getKey())) { visitedOperators.addAll(group.getValue()); int tempCores = 0; for (PTOperator operator : group.getValue()) { tempCores = Math.max(tempCores, operator.getOperatorMeta().getValue(OperatorContext.VCORES)); } vCores += tempCores; } } return vCores; } private class PartitioningContextImpl implements Partitioner.PartitioningContext { private List<InputPort<?>> inputPorts; private final int parallelPartitionCount; private final PMapping om; private PartitioningContextImpl(PMapping om, int parallelPartitionCount) { this.om = om; this.parallelPartitionCount = parallelPartitionCount; } @Override public int getParallelPartitionCount() { return parallelPartitionCount; } @Override public List<InputPort<?>> getInputPorts() { if (inputPorts == null) { inputPorts = getInputPortList(om.logicalOperator); } return inputPorts; } } private void initPartitioning(PMapping m, int partitionCnt) { Operator operator = m.logicalOperator.getOperator(); Collection<Partition<Operator>> partitions; @SuppressWarnings("unchecked") Partitioner<Operator> partitioner = m.logicalOperator.getAttributes().contains(OperatorContext.PARTITIONER) ? (Partitioner<Operator>)m.logicalOperator.getValue(OperatorContext.PARTITIONER) : operator instanceof Partitioner? (Partitioner<Operator>)operator: null; Collection<Partition<Operator>> collection = new ArrayList<Partition<Operator>>(1); DefaultPartition<Operator> firstPartition = new DefaultPartition<Operator>(operator); collection.add(firstPartition); if (partitioner != null) { partitions = partitioner.definePartitions(collection, new PartitioningContextImpl(m, partitionCnt)); if(partitions == null || partitions.isEmpty()) { throw new IllegalStateException("Partitioner returns null or empty."); } } else { //This handles the case when parallel partitioning is occurring. Partition count will be //Non zero in the case of parallel partitioning. for (int partitionCounter = 0; partitionCounter < partitionCnt - 1; partitionCounter++) { collection.add(firstPartition); } partitions = collection; } Collection<StatsListener> statsListeners = m.logicalOperator.getValue(OperatorContext.STATS_LISTENERS); if (statsListeners != null && !statsListeners.isEmpty()) { if (m.statsHandlers == null) { m.statsHandlers = new ArrayList<StatsListener>(statsListeners.size()); } m.statsHandlers.addAll(statsListeners); } if (m.logicalOperator.getOperator() instanceof StatsListener) { if (m.statsHandlers == null) { m.statsHandlers = new ArrayList<StatsListener>(1); } m.statsHandlers.add(new StatsListenerProxy(m.logicalOperator)); } // create operator instance per partition Map<Integer, Partition<Operator>> operatorIdToPartition = Maps.newHashMapWithExpectedSize(partitions.size()); for (Partition<Operator> partition : partitions) { PTOperator p = addPTOperator(m, partition, Checkpoint.INITIAL_CHECKPOINT); operatorIdToPartition.put(p.getId(), partition); } if (partitioner != null) { partitioner.partitioned(operatorIdToPartition); } } private class RepartitionContext extends PartitioningContextImpl { final List<PTOperator> operators; final List<DefaultPartition<Operator>> currentPartitions; final Map<Partition<?>, PTOperator> currentPartitionMap; final Map<Integer, Partition<Operator>> operatorIdToPartition; final List<Partition<Operator>> addedPartitions = new ArrayList<Partition<Operator>>(); Checkpoint minCheckpoint = null; Collection<Partition<Operator>> newPartitions = null; RepartitionContext(Partitioner<Operator> partitioner, PMapping currentMapping, int partitionCount) { super(currentMapping, partitionCount); this.operators = currentMapping.partitions; this.currentPartitions = new ArrayList<DefaultPartition<Operator>>(operators.size()); this.currentPartitionMap = Maps.newHashMapWithExpectedSize(operators.size()); this.operatorIdToPartition = Maps.newHashMapWithExpectedSize(operators.size()); // collect current partitions with committed operator state // those will be needed by the partitioner for split/merge for (PTOperator pOperator : operators) { Map<InputPort<?>, PartitionKeys> pks = pOperator.getPartitionKeys(); if (pks == null) { throw new AssertionError("Null partition: " + pOperator); } // if partitions checkpoint at different windows, processing for new or modified // partitions will start from earliest checkpoint found (at least once semantics) if (minCheckpoint == null) { minCheckpoint = pOperator.recoveryCheckpoint; } else if (minCheckpoint.windowId > pOperator.recoveryCheckpoint.windowId) { minCheckpoint = pOperator.recoveryCheckpoint; } Operator partitionedOperator = loadOperator(pOperator); DefaultPartition<Operator> partition = new DefaultPartition<Operator>(partitionedOperator, pks, pOperator.loadIndicator, pOperator.stats); currentPartitions.add(partition); currentPartitionMap.put(partition, pOperator); LOG.debug("partition load: {} {} {}", pOperator, partition.getPartitionKeys(), partition.getLoad()); operatorIdToPartition.put(pOperator.getId(), partition); } newPartitions = partitioner.definePartitions(new ArrayList<Partition<Operator>>(currentPartitions), this); } } private Partitioner<Operator> getPartitioner(PMapping currentMapping) { Operator operator = currentMapping.logicalOperator.getOperator(); Partitioner<Operator> partitioner = null; if (currentMapping.logicalOperator.getAttributes().contains(OperatorContext.PARTITIONER)) { @SuppressWarnings("unchecked") Partitioner<Operator> tmp = (Partitioner<Operator>)currentMapping.logicalOperator.getValue(OperatorContext.PARTITIONER); partitioner = tmp; } else if (operator instanceof Partitioner) { @SuppressWarnings("unchecked") Partitioner<Operator> tmp = (Partitioner<Operator>)operator; partitioner = tmp; } return partitioner; } private void redoPartitions(PMapping currentMapping, String note) { Partitioner<Operator> partitioner = getPartitioner(currentMapping); if (partitioner == null) { LOG.warn("No partitioner for {}", currentMapping.logicalOperator); return; } RepartitionContext mainPC = new RepartitionContext(partitioner, currentMapping, 0); if (mainPC.newPartitions.isEmpty()) { LOG.warn("Empty partition list after repartition: {}", currentMapping.logicalOperator); return; } int memoryPerPartition = currentMapping.logicalOperator.getValue(OperatorContext.MEMORY_MB); for (Map.Entry<OutputPortMeta, StreamMeta> stream : currentMapping.logicalOperator.getOutputStreams().entrySet()) { if (stream.getValue().getLocality() != Locality.THREAD_LOCAL && stream.getValue().getLocality() != Locality.CONTAINER_LOCAL) { memoryPerPartition += stream.getKey().getValue(PortContext.BUFFER_MEMORY_MB); } } for (OperatorMeta pp : currentMapping.parallelPartitions) { for (Map.Entry<OutputPortMeta, StreamMeta> stream : pp.getOutputStreams().entrySet()) { if (stream.getValue().getLocality() != Locality.THREAD_LOCAL && stream.getValue().getLocality() != Locality.CONTAINER_LOCAL) { memoryPerPartition += stream.getKey().getValue(PortContext.BUFFER_MEMORY_MB); } } memoryPerPartition += pp.getValue(OperatorContext.MEMORY_MB); } int requiredMemoryMB = (mainPC.newPartitions.size() - mainPC.currentPartitions.size()) * memoryPerPartition; if (requiredMemoryMB > availableMemoryMB) { LOG.warn("Insufficient headroom for repartitioning: available {}m required {}m", availableMemoryMB, requiredMemoryMB); return; } List<Partition<Operator>> addedPartitions = new ArrayList<Partition<Operator>>(); // determine modifications of partition set, identify affected operator instance(s) for (Partition<Operator> newPartition : mainPC.newPartitions) { PTOperator op = mainPC.currentPartitionMap.remove(newPartition); if (op == null) { addedPartitions.add(newPartition); } else { // check whether mapping was changed for (DefaultPartition<Operator> pi : mainPC.currentPartitions) { if (pi == newPartition && pi.isModified()) { // existing partition changed (operator or partition keys) // remove/add to update subscribers and state mainPC.currentPartitionMap.put(newPartition, op); addedPartitions.add(newPartition); } } } } // remaining entries represent deprecated partitions this.undeployOpers.addAll(mainPC.currentPartitionMap.values()); // downstream dependencies require redeploy, resolve prior to modifying plan Set<PTOperator> deps = this.getDependents(mainPC.currentPartitionMap.values()); this.undeployOpers.addAll(deps); // dependencies need redeploy, except operators excluded in remove this.deployOpers.addAll(deps); // process parallel partitions before removing operators from the plan LinkedHashMap<PMapping, RepartitionContext> partitionContexts = Maps.newLinkedHashMap(); Stack<OperatorMeta> parallelPartitions = new Stack<LogicalPlan.OperatorMeta>(); parallelPartitions.addAll(currentMapping.parallelPartitions); pendingLoop: while (!parallelPartitions.isEmpty()) { OperatorMeta ppMeta = parallelPartitions.pop(); for (StreamMeta s : ppMeta.getInputStreams().values()) { if (currentMapping.parallelPartitions.contains(s.getSource().getOperatorMeta()) && parallelPartitions.contains(s.getSource().getOperatorMeta())) { parallelPartitions.push(ppMeta); parallelPartitions.remove(s.getSource().getOperatorMeta()); parallelPartitions.push(s.getSource().getOperatorMeta()); continue pendingLoop; } } LOG.debug("Processing parallel partition {}", ppMeta); PMapping ppm = this.logicalToPTOperator.get(ppMeta); Partitioner<Operator> ppp = getPartitioner(ppm); if (ppp == null) { partitionContexts.put(ppm, null); } else { RepartitionContext pc = new RepartitionContext(ppp, ppm, mainPC.newPartitions.size()); if (pc.newPartitions == null) { throw new IllegalStateException("Partitioner returns null for parallel partition " + ppm.logicalOperator); } partitionContexts.put(ppm, pc); } } // plan updates start here, after all changes were identified // remove obsolete operators first, any freed resources // can subsequently be used for new/modified partitions List<PTOperator> copyPartitions = Lists.newArrayList(currentMapping.partitions); // remove deprecated partitions from plan for (PTOperator p : mainPC.currentPartitionMap.values()) { copyPartitions.remove(p); removePartition(p, currentMapping); mainPC.operatorIdToPartition.remove(p.getId()); } currentMapping.partitions = copyPartitions; // add new operators for (Partition<Operator> newPartition : addedPartitions) { PTOperator p = addPTOperator(currentMapping, newPartition, mainPC.minCheckpoint); mainPC.operatorIdToPartition.put(p.getId(), newPartition); } // process parallel partition changes for (Map.Entry<PMapping, RepartitionContext> e : partitionContexts.entrySet()) { if (e.getValue() == null) { // no partitioner, add required operators for (int i=0; i<addedPartitions.size(); i++) { LOG.debug("Automatically adding to parallel partition {}", e.getKey()); // set activation windowId to confirm to upstream checkpoints addPTOperator(e.getKey(), null, mainPC.minCheckpoint); } } else { RepartitionContext pc = e.getValue(); // track previous parallel partition mapping Map<Partition<Operator>, Partition<Operator>> prevMapping = Maps.newHashMap(); for (int i=0; i<mainPC.currentPartitions.size(); i++) { prevMapping.put(pc.currentPartitions.get(i), mainPC.currentPartitions.get(i)); } // determine which new partitions match upstream, remaining to be treated as new operator Map<Partition<Operator>, Partition<Operator>> newMapping = Maps.newHashMap(); Iterator<Partition<Operator>> itMain = mainPC.newPartitions.iterator(); Iterator<Partition<Operator>> itParallel = pc.newPartitions.iterator(); while (itMain.hasNext() && itParallel.hasNext()) { newMapping.put(itParallel.next(), itMain.next()); } for (Partition<Operator> newPartition : pc.newPartitions) { PTOperator op = pc.currentPartitionMap.remove(newPartition); if (op == null) { pc.addedPartitions.add(newPartition); } else if (prevMapping.get(newPartition) != newMapping.get(newPartition)) { // upstream partitions don't match, remove/add to replace with new operator pc.currentPartitionMap.put(newPartition, op); pc.addedPartitions.add(newPartition); } else { // check whether mapping was changed - based on DefaultPartition implementation for (DefaultPartition<Operator> pi : pc.currentPartitions) { if (pi == newPartition && pi.isModified()) { // existing partition changed (operator or partition keys) // remove/add to update subscribers and state mainPC.currentPartitionMap.put(newPartition, op); pc.addedPartitions.add(newPartition); } } } } if (!pc.currentPartitionMap.isEmpty()) { // remove obsolete partitions List<PTOperator> cowPartitions = Lists.newArrayList(e.getKey().partitions); for (PTOperator p : pc.currentPartitionMap.values()) { cowPartitions.remove(p); removePartition(p, e.getKey()); pc.operatorIdToPartition.remove(p.getId()); } e.getKey().partitions = cowPartitions; } // add new partitions for (Partition<Operator> newPartition : pc.addedPartitions) { PTOperator oper = addPTOperator(e.getKey(), newPartition, mainPC.minCheckpoint); pc.operatorIdToPartition.put(oper.getId(), newPartition); } getPartitioner(e.getKey()).partitioned(pc.operatorIdToPartition); } } updateStreamMappings(currentMapping); for (PMapping pp : partitionContexts.keySet()) { updateStreamMappings(pp); } deployChanges(); if (mainPC.currentPartitions.size() != mainPC.newPartitions.size()) { StramEvent ev = new StramEvent.PartitionEvent(currentMapping.logicalOperator.getName(), mainPC.currentPartitions.size(), mainPC.newPartitions.size()); ev.setReason(note); this.ctx.recordEventAsync(ev); } partitioner.partitioned(mainPC.operatorIdToPartition); } private void updateStreamMappings(PMapping m) { for (Map.Entry<OutputPortMeta, StreamMeta> opm : m.logicalOperator.getOutputStreams().entrySet()) { StreamMapping ug = m.outputStreams.get(opm.getKey()); if (ug == null) { ug = new StreamMapping(opm.getValue(), this); m.outputStreams.put(opm.getKey(), ug); } LOG.debug("update stream mapping for {} {}", opm.getKey().getOperatorMeta(), opm.getKey().getPortName()); ug.setSources(m.partitions); } for (Map.Entry<InputPortMeta, StreamMeta> ipm : m.logicalOperator.getInputStreams().entrySet()) { PMapping sourceMapping = this.logicalToPTOperator.get(ipm.getValue().getSource().getOperatorMeta()); if (ipm.getKey().getValue(PortContext.PARTITION_PARALLEL)) { if (sourceMapping.partitions.size() < m.partitions.size()) { throw new AssertionError("Number of partitions don't match in parallel mapping " + sourceMapping.logicalOperator.getName() + " -> " + m.logicalOperator.getName() + ", " + sourceMapping.partitions.size() + " -> " + m.partitions.size()); } int slidingWindowCount = 0; OperatorMeta sourceOM = sourceMapping.logicalOperator; if (sourceOM.getAttributes().contains(Context.OperatorContext.SLIDE_BY_WINDOW_COUNT)) { if (sourceOM.getValue(Context.OperatorContext.SLIDE_BY_WINDOW_COUNT) < sourceOM.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT)) { slidingWindowCount = sourceOM.getValue(OperatorContext.SLIDE_BY_WINDOW_COUNT); } else { LOG.warn("Sliding Window Count {} should be less than APPLICATION WINDOW COUNT {}", sourceOM.getValue(Context.OperatorContext.SLIDE_BY_WINDOW_COUNT), sourceOM.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT)); } } for (int i=0; i<m.partitions.size(); i++) { PTOperator oper = m.partitions.get(i); PTOperator sourceOper = sourceMapping.partitions.get(i); for (PTOutput sourceOut : sourceOper.outputs) { nextSource: if (sourceOut.logicalStream == ipm.getValue()) { //avoid duplicate entries in case of parallel partitions for (PTInput sinkIn : sourceOut.sinks) { //check if the operator is already in the sinks list and also the port name of that sink is same as the // input-port-meta currently being looked at since we allow an output port to connect to multiple inputs of the same operator. if (sinkIn.target == oper && sinkIn.portName.equals(ipm.getKey().getPortName())) { break nextSource; } } PTInput input; if (slidingWindowCount > 0) { PTOperator slidingUnifier = StreamMapping.createSlidingUnifier(sourceOut.logicalStream, this, sourceOM.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT), slidingWindowCount); StreamMapping.addInput(slidingUnifier, sourceOut, null); input = new PTInput(ipm.getKey().getPortName(), ipm.getValue(), oper, null, slidingUnifier.outputs.get(0)); sourceMapping.outputStreams.get(ipm.getValue().getSource()).slidingUnifiers.add(slidingUnifier); } else { input = new PTInput(ipm.getKey().getPortName(), ipm.getValue(), oper, null, sourceOut); } oper.inputs.add(input); } } } } else { StreamMapping ug = sourceMapping.outputStreams.get(ipm.getValue().getSource()); if (ug == null) { ug = new StreamMapping(ipm.getValue(), this); m.outputStreams.put(ipm.getValue().getSource(), ug); } LOG.debug("update upstream stream mapping for {} {}", sourceMapping.logicalOperator, ipm.getValue().getSource().getPortName()); ug.setSources(sourceMapping.partitions); } } } public void deployChanges() { Set<PTContainer> newContainers = Sets.newHashSet(); Set<PTContainer> releaseContainers = Sets.newHashSet(); assignContainers(newContainers, releaseContainers); updatePartitionsInfoForPersistOperator(this.dag); this.undeployOpers.removeAll(newOpers.keySet()); //make sure all the new operators are included in deploy operator list this.deployOpers.addAll(this.newOpers.keySet()); // include downstream dependencies of affected operators into redeploy Set<PTOperator> deployOperators = this.getDependents(this.deployOpers); ctx.deploy(releaseContainers, this.undeployOpers, newContainers, deployOperators); this.newOpers.clear(); this.deployOpers.clear(); this.undeployOpers.clear(); } private void assignContainers(Set<PTContainer> newContainers, Set<PTContainer> releaseContainers) { Set<PTOperator> mxnUnifiers = Sets.newHashSet(); for (PTOperator o : this.newOpers.keySet()) { mxnUnifiers.addAll(o.upstreamMerge.values()); } Set<PTContainer> updatedContainers = Sets.newHashSet(); for (Map.Entry<PTOperator, Operator> operEntry : this.newOpers.entrySet()) { PTOperator oper = operEntry.getKey(); Checkpoint checkpoint = getActivationCheckpoint(operEntry.getKey()); initCheckpoint(oper, operEntry.getValue(), checkpoint); if (mxnUnifiers.contains(operEntry.getKey())) { // MxN unifiers are assigned with the downstream operator continue; } PTContainer newContainer = null; int memoryMB = 0; // handle container locality for (PTOperator inlineOper : oper.getGrouping(Locality.CONTAINER_LOCAL).getOperatorSet()) { if (inlineOper.container != null) { newContainer = inlineOper.container; break; } memoryMB += inlineOper.operatorMeta.getValue(OperatorContext.MEMORY_MB); memoryMB += inlineOper.getBufferServerMemory(); } if (newContainer == null) { int vCores = getVCores(oper.getGrouping(Locality.CONTAINER_LOCAL).getOperatorSet()); // attempt to find empty container with required size for (PTContainer c : this.containers) { if (c.operators.isEmpty() && c.getState() == PTContainer.State.ACTIVE && c.getAllocatedMemoryMB() == memoryMB && c.getAllocatedVCores() == vCores) { LOG.debug("Reusing existing container {} for {}", c, oper); c.setRequiredMemoryMB(0); c.setRequiredVCores(0); newContainer = c; break; } } if (newContainer == null) { // get new container LOG.debug("New container for: " + oper); newContainer = new PTContainer(this); newContainers.add(newContainer); containers.add(newContainer); } updatedContainers.add(newContainer); } setContainer(oper, newContainer); } // release containers that are no longer used for (PTContainer c : this.containers) { if (c.operators.isEmpty()) { LOG.debug("Container {} to be released", c); releaseContainers.add(c); containers.remove(c); } } for (PTContainer c : updatedContainers) { updateContainerMemoryWithBufferServer(c); c.setRequiredVCores(getVCores(c.getOperators())); } } private void initCheckpoint(PTOperator oper, Operator oo, Checkpoint checkpoint) { try { LOG.debug("Writing activation checkpoint {} {} {}", checkpoint, oper, oo); long windowId = oper.isOperatorStateLess() ? Stateless.WINDOW_ID : checkpoint.windowId; StorageAgent agent = oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT); agent.save(oo, oper.id, windowId); if (agent instanceof AsyncFSStorageAgent) { AsyncFSStorageAgent asyncFSStorageAgent = (AsyncFSStorageAgent)agent; if(!asyncFSStorageAgent.isSyncCheckpoint()) { asyncFSStorageAgent.copyToHDFS(oper.id, windowId); } } } catch (IOException e) { // inconsistent state, no recovery option, requires shutdown throw new IllegalStateException("Failed to write operator state after partition change " + oper, e); } oper.setRecoveryCheckpoint(checkpoint); if (!Checkpoint.INITIAL_CHECKPOINT.equals(checkpoint)) { oper.checkpoints.add(checkpoint); } } public Operator loadOperator(PTOperator oper) { try { LOG.debug("Loading state for {}", oper); return (Operator)oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT).load(oper.id, oper.isOperatorStateLess() ? Stateless.WINDOW_ID : oper.recoveryCheckpoint.windowId); } catch (IOException e) { throw new RuntimeException("Failed to read partition state for " + oper, e); } } /** * Initialize the activation checkpoint for the given operator. * Recursively traverses inputs until existing checkpoint or root operator is found. * NoOp when already initialized. * @param oper */ private Checkpoint getActivationCheckpoint(PTOperator oper) { if (oper.recoveryCheckpoint == null && oper.checkpoints.isEmpty()) { Checkpoint activationCheckpoint = Checkpoint.INITIAL_CHECKPOINT; for (PTInput input : oper.inputs) { PTOperator sourceOper = input.source.source; if (sourceOper.checkpoints.isEmpty()) { getActivationCheckpoint(sourceOper); } activationCheckpoint = Checkpoint.max(activationCheckpoint, sourceOper.recoveryCheckpoint); } return activationCheckpoint; } return oper.recoveryCheckpoint; } /** * Remove a partition that was reported as terminated by the execution layer. * Recursively removes all downstream operators with no remaining input. * @param p */ public void removeTerminatedPartition(PTOperator p) { // keep track of downstream operators for cascading remove Set<PTOperator> downstreamOpers = new HashSet<>(p.outputs.size()); for (PTOutput out : p.outputs) { for (PTInput sinkIn : out.sinks) { downstreamOpers.add(sinkIn.target); } } PMapping currentMapping = this.logicalToPTOperator.get(p.operatorMeta); if (currentMapping != null) { List<PTOperator> copyPartitions = Lists.newArrayList(currentMapping.partitions); copyPartitions.remove(p); removePartition(p, currentMapping); currentMapping.partitions = copyPartitions; } else { // remove the operator removePTOperator(p); } // remove orphaned downstream operators for (PTOperator dop : downstreamOpers) { if (dop.inputs.isEmpty()) { removeTerminatedPartition(dop); } } deployChanges(); } /** * Remove the given partition with any associated parallel partitions and * per-partition outputStreams. * * @param oper * @return */ private void removePartition(PTOperator oper, PMapping operatorMapping) { // remove any parallel partition for (PTOutput out : oper.outputs) { // copy list as it is modified by recursive remove for (PTInput in : Lists.newArrayList(out.sinks)) { for (LogicalPlan.InputPortMeta im : in.logicalStream.getSinks()) { PMapping m = this.logicalToPTOperator.get(im.getOperatorWrapper()); if (m.parallelPartitions == operatorMapping.parallelPartitions) { // associated operator parallel partitioned removePartition(in.target, operatorMapping); m.partitions.remove(in.target); } } } } // remove the operator removePTOperator(oper); } private PTOperator addPTOperator(PMapping nodeDecl, Partition<? extends Operator> partition, Checkpoint checkpoint) { PTOperator oper = newOperator(nodeDecl.logicalOperator, nodeDecl.logicalOperator.getName()); oper.recoveryCheckpoint = checkpoint; // output port objects for (Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry : nodeDecl.logicalOperator.getOutputStreams().entrySet()) { setupOutput(nodeDecl, oper, outputEntry); } String host = null; if (partition != null) { oper.setPartitionKeys(partition.getPartitionKeys()); host = partition.getAttributes().get(OperatorContext.LOCALITY_HOST); } if (host == null) { host = nodeDecl.logicalOperator.getValue(OperatorContext.LOCALITY_HOST); } nodeDecl.addPartition(oper); this.newOpers.put(oper, partition != null ? partition.getPartitionedInstance() : nodeDecl.logicalOperator.getOperator()); // // update locality // setLocalityGrouping(nodeDecl, oper, inlinePrefs, Locality.CONTAINER_LOCAL, host); setLocalityGrouping(nodeDecl, oper, localityPrefs, Locality.NODE_LOCAL, host); return oper; } /** * Create output port mapping for given operator and port. * Occurs when adding new partition or new logical stream. * Does nothing if source was already setup (on add sink to existing stream). * @param mapping * @param oper * @param outputEntry */ private void setupOutput(PMapping mapping, PTOperator oper, Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry) { for (PTOutput out : oper.outputs) { if (out.logicalStream == outputEntry.getValue()) { // already processed return; } } PTOutput out = new PTOutput(outputEntry.getKey().getPortName(), outputEntry.getValue(), oper); oper.outputs.add(out); } PTOperator newOperator(OperatorMeta om, String name) { PTOperator oper = new PTOperator(this, idSequence.incrementAndGet(), name, om); allOperators.put(oper.id, oper); oper.inputs = new ArrayList<PTInput>(); oper.outputs = new ArrayList<PTOutput>(); this.ctx.recordEventAsync(new StramEvent.CreateOperatorEvent(oper.getName(), oper.getId())); return oper; } private void setLocalityGrouping(PMapping pnodes, PTOperator newOperator, LocalityPrefs localityPrefs, Locality ltype,String host) { HostOperatorSet grpObj = newOperator.getGrouping(ltype); if(host!= null) { grpObj.setHost(host); } Set<PTOperator> s = grpObj.getOperatorSet(); s.add(newOperator); LocalityPref loc = localityPrefs.prefs.get(pnodes); if (loc != null) { for (PMapping localPM : loc.operators) { if (pnodes.parallelPartitions == localPM.parallelPartitions) { if (localPM.partitions.size() >= pnodes.partitions.size()) { // apply locality setting per partition s.addAll(localPM.partitions.get(pnodes.partitions.size()-1).getGrouping(ltype).getOperatorSet()); } } else { for (PTOperator otherNode : localPM.partitions) { s.addAll(otherNode.getGrouping(ltype).getOperatorSet()); } } } for (PTOperator localOper : s) { if(grpObj.getHost() == null){ grpObj.setHost(localOper.groupings.get(ltype).getHost()); } localOper.groupings.put(ltype, grpObj); } } } private List<InputPort<?>> getInputPortList(LogicalPlan.OperatorMeta operatorMeta) { List<InputPort<?>> inputPortList = Lists.newArrayList(); for (InputPortMeta inputPortMeta: operatorMeta.getInputStreams().keySet()) { inputPortList.add(inputPortMeta.getPortObject()); } return inputPortList; } void removePTOperator(PTOperator oper) { LOG.debug("Removing operator " + oper); // per partition merge operators if (!oper.upstreamMerge.isEmpty()) { for (PTOperator unifier : oper.upstreamMerge.values()) { removePTOperator(unifier); } } // remove inputs from downstream operators for (PTOutput out : oper.outputs) { for (PTInput sinkIn : out.sinks) { if (sinkIn.source.source == oper) { ArrayList<PTInput> cowInputs = Lists.newArrayList(sinkIn.target.inputs); cowInputs.remove(sinkIn); sinkIn.target.inputs = cowInputs; } } } // remove from upstream operators for (PTInput in : oper.inputs) { in.source.sinks.remove(in); } for (HostOperatorSet s : oper.groupings.values()) { s.getOperatorSet().remove(oper); } // remove checkpoint states try { synchronized (oper.checkpoints) { for (Checkpoint checkpoint : oper.checkpoints) { oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT).delete(oper.id, checkpoint.windowId); } } } catch (IOException e) { LOG.warn("Failed to remove state for " + oper, e); } List<PTOperator> cowList = Lists.newArrayList(oper.container.operators); cowList.remove(oper); oper.container.operators = cowList; this.deployOpers.remove(oper); this.undeployOpers.add(oper); this.allOperators.remove(oper.id); this.ctx.recordEventAsync(new StramEvent.RemoveOperatorEvent(oper.getName(), oper.getId())); } public PlanContext getContext() { return ctx; } public LogicalPlan getLogicalPlan() { return this.dag; } public List<PTContainer> getContainers() { return this.containers; } public Map<Integer, PTOperator> getAllOperators() { return this.allOperators; } /** * Get the partitions for the logical operator. * Partitions represent instances of the operator and do not include any unifiers. * @param logicalOperator * @return */ public List<PTOperator> getOperators(OperatorMeta logicalOperator) { return this.logicalToPTOperator.get(logicalOperator).partitions; } public Collection<PTOperator> getAllOperators(OperatorMeta logicalOperator) { return this.logicalToPTOperator.get(logicalOperator).getAllOperators(); } public boolean hasMapping(OperatorMeta om) { return this.logicalToPTOperator.containsKey(om); } // used for testing only @VisibleForTesting public List<PTOperator> getMergeOperators(OperatorMeta logicalOperator) { List<PTOperator> opers = Lists.newArrayList(); for (StreamMapping ug : this.logicalToPTOperator.get(logicalOperator).outputStreams.values()) { ug.addTo(opers); } return opers; } protected List<OperatorMeta> getRootOperators() { return dag.getRootOperators(); } private void getDeps(PTOperator operator, Set<PTOperator> visited) { visited.add(operator); for (PTInput in : operator.inputs) { if (in.source.isDownStreamInline()) { PTOperator sourceOperator = in.source.source; if (!visited.contains(sourceOperator)) { getDeps(sourceOperator, visited); } } } // downstream traversal for (PTOutput out: operator.outputs) { for (PTInput sink : out.sinks) { PTOperator sinkOperator = sink.target; if (!visited.contains(sinkOperator)) { getDeps(sinkOperator, visited); } } } } /** * Get all operator instances that depend on the specified operator instance(s). * Dependencies are all downstream and upstream inline operators. * @param operators * @return */ public Set<PTOperator> getDependents(Collection<PTOperator> operators) { Set<PTOperator> visited = new LinkedHashSet<PTOperator>(); if (operators != null) { for (PTOperator operator: operators) { getDeps(operator, visited); } } visited.addAll(getDependentPersistOperators(operators)); return visited; } private Set<PTOperator> getDependentPersistOperators(Collection<PTOperator> operators) { Set<PTOperator> persistOperators = new LinkedHashSet<PTOperator>(); if (operators != null) { for (PTOperator operator : operators) { for (PTInput in : operator.inputs) { if (in.logicalStream.getPersistOperator() != null) { for (InputPortMeta inputPort : in.logicalStream.getSinksToPersist()) { if (inputPort.getOperatorWrapper().equals(operator.operatorMeta)) { // Redeploy the stream wide persist operator only if the current sink is being persisted persistOperators.addAll(getOperators(in.logicalStream.getPersistOperator())); break; } } } for (Entry<InputPortMeta, OperatorMeta> entry : in.logicalStream.sinkSpecificPersistOperatorMap.entrySet()) { // Redeploy sink specific persist operators persistOperators.addAll(getOperators(entry.getValue())); } } } } return persistOperators; } /** * Add logical operator to the plan. Assumes that upstream operators have been added before. * @param om */ public final void addLogicalOperator(OperatorMeta om) { PMapping pnodes = new PMapping(om); String host = pnodes.logicalOperator.getValue(OperatorContext.LOCALITY_HOST); localityPrefs.add(pnodes, host); PMapping upstreamPartitioned = null; for (Map.Entry<LogicalPlan.InputPortMeta, StreamMeta> e : om.getInputStreams().entrySet()) { PMapping m = logicalToPTOperator.get(e.getValue().getSource().getOperatorMeta()); if (e.getKey().getValue(PortContext.PARTITION_PARALLEL).equals(true)) { // operator partitioned with upstream if (upstreamPartitioned != null) { // need to have common root if (!upstreamPartitioned.parallelPartitions.contains(m.logicalOperator) && upstreamPartitioned != m) { String msg = String.format("operator cannot extend multiple partitions (%s and %s)", upstreamPartitioned.logicalOperator, m.logicalOperator); throw new AssertionError(msg); } } m.parallelPartitions.add(pnodes.logicalOperator); pnodes.parallelPartitions = m.parallelPartitions; upstreamPartitioned = m; } if (Locality.CONTAINER_LOCAL == e.getValue().getLocality() || Locality.THREAD_LOCAL == e.getValue().getLocality()) { inlinePrefs.setLocal(m, pnodes); } else if (Locality.NODE_LOCAL == e.getValue().getLocality()) { localityPrefs.setLocal(m, pnodes); } } // // create operator instances // this.logicalToPTOperator.put(om, pnodes); if (upstreamPartitioned != null) { // parallel partition //LOG.debug("Operator {} should be partitioned to {} partitions", pnodes.logicalOperator.getName(), upstreamPartitioned.partitions.size()); initPartitioning(pnodes, upstreamPartitioned.partitions.size()); } else { initPartitioning(pnodes, 0); } updateStreamMappings(pnodes); } /** * Remove physical representation of given stream. Operators that are affected * in the execution layer will be added to the set. This method does not * automatically remove operators from the plan. * * @param sm */ public void removeLogicalStream(StreamMeta sm) { // remove incoming connections for logical stream for (InputPortMeta ipm : sm.getSinks()) { OperatorMeta om = ipm.getOperatorWrapper(); PMapping m = this.logicalToPTOperator.get(om); if (m == null) { throw new AssertionError("Unknown operator " + om); } for (PTOperator oper : m.partitions) { List<PTInput> inputsCopy = Lists.newArrayList(oper.inputs); for (PTInput input : oper.inputs) { if (input.logicalStream == sm) { input.source.sinks.remove(input); inputsCopy.remove(input); undeployOpers.add(oper); deployOpers.add(oper); } } oper.inputs = inputsCopy; } } // remove outgoing connections for logical stream PMapping m = this.logicalToPTOperator.get(sm.getSource().getOperatorMeta()); for (PTOperator oper : m.partitions) { List<PTOutput> outputsCopy = Lists.newArrayList(oper.outputs); for (PTOutput out : oper.outputs) { if (out.logicalStream == sm) { for (PTInput input : out.sinks) { PTOperator downstreamOper = input.source.source; downstreamOper.inputs.remove(input); Set<PTOperator> deps = this.getDependents(Collections.singletonList(downstreamOper)); undeployOpers.addAll(deps); deployOpers.addAll(deps); } outputsCopy.remove(out); undeployOpers.add(oper); deployOpers.add(oper); } } oper.outputs = outputsCopy; } } /** * Connect operators through stream. Currently new stream will not affect locality. * @param ipm Meta information about the input port */ public void connectInput(InputPortMeta ipm) { for (Map.Entry<LogicalPlan.InputPortMeta, StreamMeta> inputEntry : ipm.getOperatorWrapper().getInputStreams().entrySet()) { if (inputEntry.getKey() == ipm) { // initialize outputs for existing operators for (Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry : inputEntry.getValue().getSource().getOperatorMeta().getOutputStreams().entrySet()) { PMapping sourceOpers = this.logicalToPTOperator.get(outputEntry.getKey().getOperatorMeta()); for (PTOperator oper : sourceOpers.partitions) { setupOutput(sourceOpers, oper, outputEntry); // idempotent undeployOpers.add(oper); deployOpers.add(oper); } } PMapping m = this.logicalToPTOperator.get(ipm.getOperatorWrapper()); updateStreamMappings(m); for (PTOperator oper : m.partitions) { undeployOpers.add(oper); deployOpers.add(oper); } } } } /** * Remove all physical operators for the given logical operator. * All connected streams must have been previously removed. * @param om */ public void removeLogicalOperator(OperatorMeta om) { PMapping opers = this.logicalToPTOperator.get(om); if (opers == null) { throw new AssertionError("Operator not in physical plan: " + om.getName()); } for (PTOperator oper : opers.partitions) { removePartition(oper, opers); } for (StreamMapping ug : opers.outputStreams.values()) { for (PTOperator oper : ug.cascadingUnifiers) { removePTOperator(oper); } if (ug.finalUnifier != null) { removePTOperator(ug.finalUnifier); } } LinkedHashMap<OperatorMeta, PMapping> copyMap = Maps.newLinkedHashMap(this.logicalToPTOperator); copyMap.remove(om); this.logicalToPTOperator = copyMap; } public void setAvailableResources(int memoryMB) { this.availableMemoryMB = memoryMB; } public void onStatusUpdate(PTOperator oper) { for (StatsListener l : oper.statsListeners) { final StatsListener.Response rsp = l.processStats(oper.stats); if (rsp != null) { //LOG.debug("Response to processStats = {}", rsp.repartitionRequired); oper.loadIndicator = rsp.loadIndicator; if (rsp.repartitionRequired) { final OperatorMeta om = oper.getOperatorMeta(); // concurrent heartbeat processing if (this.pendingRepartition.putIfAbsent(om, om) != null) { LOG.debug("Skipping repartitioning for {} load {}", oper, oper.loadIndicator); } else { LOG.debug("Scheduling repartitioning for {} load {}", oper, oper.loadIndicator); // hand over to monitor thread Runnable r = new Runnable() { @Override public void run() { redoPartitions(logicalToPTOperator.get(om), rsp.repartitionNote); pendingRepartition.remove(om); } }; ctx.dispatch(r); } } if (rsp.operatorRequests != null) { for (OperatorRequest cmd : rsp.operatorRequests) { StramToNodeRequest request = new StramToNodeRequest(); request.operatorId = oper.getId(); request.requestType = StramToNodeRequest.RequestType.CUSTOM; request.cmd = cmd; ctx.addOperatorRequest(oper, request); } } // for backward compatibility if(rsp.operatorCommands != null){ for(@SuppressWarnings("deprecation") com.datatorrent.api.StatsListener.OperatorCommand cmd: rsp.operatorCommands){ StramToNodeRequest request = new StramToNodeRequest(); request.operatorId = oper.getId(); request.requestType = StramToNodeRequest.RequestType.CUSTOM; OperatorCommandConverter converter = new OperatorCommandConverter(); converter.cmd = cmd; request.cmd = converter; ctx.addOperatorRequest(oper, request); } } } } } /** * Read available checkpoints from storage agent for all operators. * @param startTime * @param currentTime * @throws IOException */ public void syncCheckpoints(long startTime, long currentTime) throws IOException { for (PTOperator oper : getAllOperators().values()) { StorageAgent sa = oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT); long[] windowIds = sa.getWindowIds(oper.getId()); Arrays.sort(windowIds); oper.checkpoints.clear(); for (long wid : windowIds) { if (wid != Stateless.WINDOW_ID) { oper.addCheckpoint(wid, startTime); } } } } public Integer getStreamCodecIdentifier(StreamCodec<?> streamCodecInfo) { Integer id; synchronized (streamCodecIdentifiers) { id = streamCodecIdentifiers.get(streamCodecInfo); if (id == null) { id = strCodecIdSequence.incrementAndGet(); streamCodecIdentifiers.put(streamCodecInfo, id); } } return id; } @VisibleForTesting public Map<StreamCodec<?>, Integer> getStreamCodecIdentifiers() { return Collections.unmodifiableMap(streamCodecIdentifiers); } /** * This is for backward compatibility */ public static class OperatorCommandConverter implements OperatorRequest,Serializable { private static final long serialVersionUID = 1L; @SuppressWarnings("deprecation") public com.datatorrent.api.StatsListener.OperatorCommand cmd; @SuppressWarnings("deprecation") @Override public StatsListener.OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException { cmd.execute(operator,operatorId,windowId); return null; } } }
engine/src/main/java/com/datatorrent/stram/plan/physical/PhysicalPlan.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.datatorrent.stram.plan.physical; import java.io.IOException; import java.io.Serializable; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.datatorrent.api.Context.OperatorContext; import com.datatorrent.api.Context.PortContext; import com.datatorrent.api.*; import com.datatorrent.api.DAG.Locality; import com.datatorrent.api.Operator.InputPort; import com.datatorrent.api.Partitioner.Partition; import com.datatorrent.api.Partitioner.PartitionKeys; import com.datatorrent.api.StatsListener.OperatorRequest; import com.datatorrent.api.annotation.Stateless; import com.datatorrent.common.util.AsyncFSStorageAgent; import com.datatorrent.netlet.util.DTThrowable; import com.datatorrent.stram.Journal.Recoverable; import com.datatorrent.stram.api.Checkpoint; import com.datatorrent.stram.api.StramEvent; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol.StramToNodeRequest; import com.datatorrent.stram.plan.logical.LogicalPlan; import com.datatorrent.stram.plan.logical.LogicalPlan.InputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OutputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.StreamMeta; import com.datatorrent.stram.plan.logical.StreamCodecWrapperForPersistance; import com.datatorrent.stram.plan.physical.PTOperator.HostOperatorSet; import com.datatorrent.stram.plan.physical.PTOperator.PTInput; import com.datatorrent.stram.plan.physical.PTOperator.PTOutput; /** * Translates the logical DAG into physical model. Is the initial query planner * and performs dynamic changes. * <p> * Attributes in the logical DAG affect how the physical plan is derived. * Examples include partitioning schemes, resource allocation, recovery * semantics etc.<br> * * The current implementation does not dynamically change or optimize allocation * of containers. The maximum number of containers and container size can be * specified per application, but all containers are requested at the same size * and execution will block until all containers were allocated by the resource * manager. Future enhancements will allow to define resource constraints at the * operator level and elasticity in resource allocation.<br> * * @since 0.3.2 */ public class PhysicalPlan implements Serializable { private static final long serialVersionUID = 201312112033L; private static final Logger LOG = LoggerFactory.getLogger(PhysicalPlan.class); public static class LoadIndicator { public final int indicator; public final String note; LoadIndicator(int indicator, String note) { this.indicator = indicator; this.note = note; } } private final AtomicInteger idSequence = new AtomicInteger(); final AtomicInteger containerSeq = new AtomicInteger(); private LinkedHashMap<OperatorMeta, PMapping> logicalToPTOperator = new LinkedHashMap<OperatorMeta, PMapping>(); private final List<PTContainer> containers = new CopyOnWriteArrayList<PTContainer>(); private final LogicalPlan dag; private transient final PlanContext ctx; private int maxContainers = 1; private int availableMemoryMB = Integer.MAX_VALUE; private final LocalityPrefs localityPrefs = new LocalityPrefs(); private final LocalityPrefs inlinePrefs = new LocalityPrefs(); final Set<PTOperator> deployOpers = Sets.newHashSet(); final Map<PTOperator, Operator> newOpers = Maps.newHashMap(); final Set<PTOperator> undeployOpers = Sets.newHashSet(); final ConcurrentMap<Integer, PTOperator> allOperators = Maps.newConcurrentMap(); private final ConcurrentMap<OperatorMeta, OperatorMeta> pendingRepartition = Maps.newConcurrentMap(); private final AtomicInteger strCodecIdSequence = new AtomicInteger(); private final Map<StreamCodec<?>, Integer> streamCodecIdentifiers = Maps.newHashMap(); private PTContainer getContainer(int index) { if (index >= containers.size()) { if (index >= maxContainers) { index = maxContainers - 1; } for (int i=containers.size(); i<index+1; i++) { containers.add(i, new PTContainer(this)); } } return containers.get(index); } /** * Interface to execution context that can be mocked for plan testing. */ public interface PlanContext { /** * Record an event in the event log * * @param ev The event * */ public void recordEventAsync(StramEvent ev); /** * Request deployment change as sequence of undeploy, container start and deploy groups with dependency. * Called on initial plan and on dynamic changes during execution. * @param releaseContainers * @param undeploy * @param startContainers * @param deploy */ public void deploy(Set<PTContainer> releaseContainers, Collection<PTOperator> undeploy, Set<PTContainer> startContainers, Collection<PTOperator> deploy); /** * Trigger event to perform plan modification. * @param r */ public void dispatch(Runnable r); /** * Write the recoverable operation to the log. * @param operation */ public void writeJournal(Recoverable operation); public void addOperatorRequest(PTOperator oper, StramToNodeRequest request); } private static class StatsListenerProxy implements StatsListener, Serializable { private static final long serialVersionUID = 201312112033L; final private OperatorMeta om; private StatsListenerProxy(OperatorMeta om) { this.om = om; } @Override public Response processStats(BatchedOperatorStats stats) { return ((StatsListener)om.getOperator()).processStats(stats); } } /** * The logical operator with physical plan info tagged on. */ public static class PMapping implements java.io.Serializable { private static final long serialVersionUID = 201312112033L; final private OperatorMeta logicalOperator; private List<PTOperator> partitions = new LinkedList<PTOperator>(); private final Map<LogicalPlan.OutputPortMeta, StreamMapping> outputStreams = Maps.newHashMap(); private List<StatsListener> statsHandlers; /** * Operators that form a parallel partition */ private Set<OperatorMeta> parallelPartitions = Sets.newHashSet(); private PMapping(OperatorMeta om) { this.logicalOperator = om; } private void addPartition(PTOperator p) { partitions.add(p); p.statsListeners = this.statsHandlers; } private Collection<PTOperator> getAllOperators() { // if (partitions.size() == 1) { // return Collections.singletonList(partitions.get(0)); // } Collection<PTOperator> c = new ArrayList<PTOperator>(partitions.size() + 1); c.addAll(partitions); for (StreamMapping ug : outputStreams.values()) { ug.addTo(c); } return c; } @Override public String toString() { return logicalOperator.toString(); } } private class LocalityPref implements java.io.Serializable { private static final long serialVersionUID = 201312112033L; String host; Set<PMapping> operators = Sets.newHashSet(); } /** * Group logical operators by locality constraint. Used to derive locality * groupings for physical operators, which are used when assigning containers * and requesting resources from the scheduler. */ private class LocalityPrefs implements java.io.Serializable { private static final long serialVersionUID = 201312112033L; private final Map<PMapping, LocalityPref> prefs = Maps.newHashMap(); private final AtomicInteger groupSeq = new AtomicInteger(); void add(PMapping m, String group) { if (group != null) { LocalityPref pref = null; for (LocalityPref lp : prefs.values()) { if (group.equals(lp.host)) { lp.operators.add(m); pref = lp; break; } } if (pref == null) { pref = new LocalityPref(); pref.host = group; pref.operators.add(m); this.prefs.put(m, pref); } } } // if netbeans is not smart, don't produce warnings in other IDE //@SuppressWarnings("null") /* for lp2.operators.add(m1); line below - netbeans is not very smart; you don't be an idiot! */ void setLocal(PMapping m1, PMapping m2) { LocalityPref lp1 = prefs.get(m1); LocalityPref lp2 = prefs.get(m2); if (lp1 == null && lp2 == null) { lp1 = lp2 = new LocalityPref(); lp1.host = "host" + groupSeq.incrementAndGet(); lp1.operators.add(m1); lp1.operators.add(m2); } else if (lp1 != null && lp2 != null) { // check if we can combine if (StringUtils.equals(lp1.host, lp2.host)) { lp1.operators.addAll(lp2.operators); lp2.operators.addAll(lp1.operators); } else { LOG.warn("Node locality conflict {} {}", m1, m2); } } else { if (lp1 == null) { lp2.operators.add(m1); lp1 = lp2; } else { lp1.operators.add(m2); lp2 = lp1; } } prefs.put(m1, lp1); prefs.put(m2, lp2); } } /** * * @param dag * @param ctx */ public PhysicalPlan(LogicalPlan dag, PlanContext ctx) { this.dag = dag; this.ctx = ctx; this.maxContainers = Math.max(dag.getMaxContainerCount(), 1); LOG.debug("Max containers: {}", this.maxContainers); Stack<OperatorMeta> pendingNodes = new Stack<OperatorMeta>(); // Add logging operators for streams if not added already updatePersistOperatorStreamCodec(dag); for (OperatorMeta n : dag.getAllOperators()) { pendingNodes.push(n); } while (!pendingNodes.isEmpty()) { OperatorMeta n = pendingNodes.pop(); if (this.logicalToPTOperator.containsKey(n)) { // already processed as upstream dependency continue; } boolean upstreamDeployed = true; for (StreamMeta s : n.getInputStreams().values()) { if (s.getSource() != null && !this.logicalToPTOperator.containsKey(s.getSource().getOperatorMeta())) { pendingNodes.push(n); pendingNodes.push(s.getSource().getOperatorMeta()); upstreamDeployed = false; break; } } if (upstreamDeployed) { addLogicalOperator(n); } } updatePartitionsInfoForPersistOperator(dag); // assign operators to containers int groupCount = 0; Set<PTOperator> deployOperators = Sets.newHashSet(); for (Map.Entry<OperatorMeta, PMapping> e : logicalToPTOperator.entrySet()) { for (PTOperator oper : e.getValue().getAllOperators()) { if (oper.container == null) { PTContainer container = getContainer((groupCount++) % maxContainers); if (!container.operators.isEmpty()) { LOG.warn("Operator {} shares container without locality contraint due to insufficient resources.", oper); } Set<PTOperator> inlineSet = oper.getGrouping(Locality.CONTAINER_LOCAL).getOperatorSet(); if (!inlineSet.isEmpty()) { // process inline operators for (PTOperator inlineOper : inlineSet) { setContainer(inlineOper, container); } } else { setContainer(oper, container); } deployOperators.addAll(container.operators); } } } for (PTContainer container : containers) { updateContainerMemoryWithBufferServer(container); container.setRequiredVCores(getVCores(container.getOperators())); } for (Map.Entry<PTOperator, Operator> operEntry : this.newOpers.entrySet()) { initCheckpoint(operEntry.getKey(), operEntry.getValue(), Checkpoint.INITIAL_CHECKPOINT); } // request initial deployment ctx.deploy(Collections.<PTContainer>emptySet(), Collections.<PTOperator>emptySet(), Sets.newHashSet(containers), deployOperators); this.newOpers.clear(); this.deployOpers.clear(); this.undeployOpers.clear(); } private void updatePartitionsInfoForPersistOperator(LogicalPlan dag) { // Add Partition mask and partition keys of Sinks to persist to Wrapper // StreamCodec for persist operator try { for (OperatorMeta n : dag.getAllOperators()) { for (StreamMeta s : n.getOutputStreams().values()) { if (s.getPersistOperator() != null) { InputPortMeta persistInputPort = s.getPersistOperatorInputPort(); StreamCodecWrapperForPersistance persistCodec = (StreamCodecWrapperForPersistance) persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); if (persistCodec == null) continue; // Logging is enabled for the stream for (InputPortMeta portMeta : s.getSinksToPersist()) { updatePersistOperatorWithSinkPartitions(persistInputPort, s.getPersistOperator(), persistCodec, portMeta); } } // Check partitioning for persist operators per sink too for (Entry<InputPortMeta, InputPortMeta> entry : s.sinkSpecificPersistInputPortMap.entrySet()) { InputPortMeta persistInputPort = entry.getValue(); StreamCodec codec = persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); if (codec != null) { if (codec instanceof StreamCodecWrapperForPersistance) { StreamCodecWrapperForPersistance persistCodec = (StreamCodecWrapperForPersistance) codec; updatePersistOperatorWithSinkPartitions(persistInputPort, s.sinkSpecificPersistOperatorMap.get(entry.getKey()), persistCodec, entry.getKey()); } } } } } } catch (Exception e) { DTThrowable.wrapIfChecked(e); } } private void updatePersistOperatorWithSinkPartitions(InputPortMeta persistInputPort, OperatorMeta persistOperatorMeta, StreamCodecWrapperForPersistance persistCodec, InputPortMeta sinkPortMeta) { Collection<PTOperator> ptOperators = getOperators(sinkPortMeta.getOperatorWrapper()); Collection<PartitionKeys> partitionKeysList = new ArrayList<PartitionKeys>(); for (PTOperator p : ptOperators) { PartitionKeys keys = p.partitionKeys.get(sinkPortMeta); partitionKeysList.add(keys); } persistCodec.inputPortToPartitionMap.put(sinkPortMeta, partitionKeysList); } private void updatePersistOperatorStreamCodec(LogicalPlan dag) { HashMap<StreamMeta, StreamCodec<?>> streamMetaToCodecMap = new HashMap<StreamMeta, StreamCodec<?>>(); try { for (OperatorMeta n : dag.getAllOperators()) { for (StreamMeta s : n.getOutputStreams().values()) { if (s.getPersistOperator() != null) { Map<InputPortMeta, StreamCodec<Object>> inputStreamCodecs = new HashMap<InputPortMeta, StreamCodec<Object>>(); // Logging is enabled for the stream for (InputPortMeta portMeta : s.getSinksToPersist()) { InputPort<?> port = portMeta.getPortObject(); StreamCodec<?> inputStreamCodec = (portMeta.getValue(PortContext.STREAM_CODEC) != null) ? portMeta.getValue(PortContext.STREAM_CODEC) : port.getStreamCodec(); if (inputStreamCodec != null) { boolean alreadyAdded = false; for (StreamCodec<?> codec : inputStreamCodecs.values()) { if (inputStreamCodec.equals(codec)) { alreadyAdded = true; break; } } if (!alreadyAdded) { inputStreamCodecs.put(portMeta, (StreamCodec<Object>) inputStreamCodec); } } } if (inputStreamCodecs.isEmpty()) { // Stream codec not specified // So everything out of Source should be captured without any // StreamCodec // Do nothing } else { // Create Wrapper codec for Stream persistence using all unique // stream codecs // Logger should write merged or union of all input stream codecs StreamCodec<Object> specifiedCodecForLogger = (s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) != null) ? (StreamCodec<Object>) s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) : (StreamCodec<Object>) s.getPersistOperatorInputPort().getPortObject().getStreamCodec(); StreamCodecWrapperForPersistance<Object> codec = new StreamCodecWrapperForPersistance<Object>(inputStreamCodecs, specifiedCodecForLogger); streamMetaToCodecMap.put(s, codec); } } } } for (java.util.Map.Entry<StreamMeta, StreamCodec<?>> entry : streamMetaToCodecMap.entrySet()) { dag.setInputPortAttribute(entry.getKey().getPersistOperatorInputPort().getPortObject(), PortContext.STREAM_CODEC, entry.getValue()); } } catch (Exception e) { DTThrowable.wrapIfChecked(e); } } private void setContainer(PTOperator pOperator, PTContainer container) { LOG.debug("Setting container {} for {}", container, pOperator); assert (pOperator.container == null) : "Container already assigned for " + pOperator; pOperator.container = container; container.operators.add(pOperator); int upStreamUnifierMemory = 0; if (!pOperator.upstreamMerge.isEmpty()) { for (Map.Entry<InputPortMeta, PTOperator> mEntry : pOperator.upstreamMerge.entrySet()) { assert (mEntry.getValue().container == null) : "Container already assigned for " + mEntry.getValue(); mEntry.getValue().container = container; container.operators.add(mEntry.getValue()); upStreamUnifierMemory += mEntry.getValue().getOperatorMeta().getValue(OperatorContext.MEMORY_MB); } } int memoryMB = pOperator.getOperatorMeta().getValue(OperatorContext.MEMORY_MB) + upStreamUnifierMemory; container.setRequiredMemoryMB(container.getRequiredMemoryMB() + memoryMB); } private void updateContainerMemoryWithBufferServer(PTContainer container) { int bufferServerMemory = 0; for (PTOperator operator : container.getOperators()) { bufferServerMemory += operator.getBufferServerMemory(); } container.setRequiredMemoryMB(container.getRequiredMemoryMB() + bufferServerMemory); } /** * This returns the vCores for a set of operators in a container. This forms the group of thread_local operators and get the maximum value of the group * * @param operators The container local operators * @return the number of vcores required for a container */ private int getVCores(Collection<PTOperator> operators) { // this forms the groups of thread local operators in the given container HashMap<PTOperator, Set<PTOperator>> groupMap = new HashMap<PTOperator, Set<PTOperator>>(); for (PTOperator operator : operators) { Set<PTOperator> group = new HashSet<PTOperator>(); group.add(operator); groupMap.put(operator, group); } int vCores = 0; for (PTOperator operator : operators) { Set<PTOperator> threadLocal = operator.getThreadLocalOperators(); if (threadLocal != null) { Set<PTOperator> group = groupMap.get(operator); for (PTOperator operator1 : threadLocal) { group.addAll(groupMap.get(operator1)); } for (PTOperator operator1 : group) { groupMap.put(operator1, group); } } } Set<PTOperator> visitedOperators = new HashSet<PTOperator>(); for (Map.Entry<PTOperator, Set<PTOperator>> group : groupMap.entrySet()) { if (!visitedOperators.contains(group.getKey())) { visitedOperators.addAll(group.getValue()); int tempCores = 0; for (PTOperator operator : group.getValue()) { tempCores = Math.max(tempCores, operator.getOperatorMeta().getValue(OperatorContext.VCORES)); } vCores += tempCores; } } return vCores; } private class PartitioningContextImpl implements Partitioner.PartitioningContext { private List<InputPort<?>> inputPorts; private final int parallelPartitionCount; private final PMapping om; private PartitioningContextImpl(PMapping om, int parallelPartitionCount) { this.om = om; this.parallelPartitionCount = parallelPartitionCount; } @Override public int getParallelPartitionCount() { return parallelPartitionCount; } @Override public List<InputPort<?>> getInputPorts() { if (inputPorts == null) { inputPorts = getInputPortList(om.logicalOperator); } return inputPorts; } } private void initPartitioning(PMapping m, int partitionCnt) { Operator operator = m.logicalOperator.getOperator(); Collection<Partition<Operator>> partitions; @SuppressWarnings("unchecked") Partitioner<Operator> partitioner = m.logicalOperator.getAttributes().contains(OperatorContext.PARTITIONER) ? (Partitioner<Operator>)m.logicalOperator.getValue(OperatorContext.PARTITIONER) : operator instanceof Partitioner? (Partitioner<Operator>)operator: null; Collection<Partition<Operator>> collection = new ArrayList<Partition<Operator>>(1); DefaultPartition<Operator> firstPartition = new DefaultPartition<Operator>(operator); collection.add(firstPartition); if (partitioner != null) { partitions = partitioner.definePartitions(collection, new PartitioningContextImpl(m, partitionCnt)); if(partitions == null || partitions.isEmpty()) { throw new IllegalStateException("Partitioner returns null or empty."); } } else { //This handles the case when parallel partitioning is occurring. Partition count will be //Non zero in the case of parallel partitioning. for (int partitionCounter = 0; partitionCounter < partitionCnt - 1; partitionCounter++) { collection.add(firstPartition); } partitions = collection; } Collection<StatsListener> statsListeners = m.logicalOperator.getValue(OperatorContext.STATS_LISTENERS); if (statsListeners != null && !statsListeners.isEmpty()) { if (m.statsHandlers == null) { m.statsHandlers = new ArrayList<StatsListener>(statsListeners.size()); } m.statsHandlers.addAll(statsListeners); } if (m.logicalOperator.getOperator() instanceof StatsListener) { if (m.statsHandlers == null) { m.statsHandlers = new ArrayList<StatsListener>(1); } m.statsHandlers.add(new StatsListenerProxy(m.logicalOperator)); } // create operator instance per partition Map<Integer, Partition<Operator>> operatorIdToPartition = Maps.newHashMapWithExpectedSize(partitions.size()); for (Partition<Operator> partition : partitions) { PTOperator p = addPTOperator(m, partition, Checkpoint.INITIAL_CHECKPOINT); operatorIdToPartition.put(p.getId(), partition); } if (partitioner != null) { partitioner.partitioned(operatorIdToPartition); } } private class RepartitionContext extends PartitioningContextImpl { final List<PTOperator> operators; final List<DefaultPartition<Operator>> currentPartitions; final Map<Partition<?>, PTOperator> currentPartitionMap; final Map<Integer, Partition<Operator>> operatorIdToPartition; final List<Partition<Operator>> addedPartitions = new ArrayList<Partition<Operator>>(); Checkpoint minCheckpoint = null; Collection<Partition<Operator>> newPartitions = null; RepartitionContext(Partitioner<Operator> partitioner, PMapping currentMapping, int partitionCount) { super(currentMapping, partitionCount); this.operators = currentMapping.partitions; this.currentPartitions = new ArrayList<DefaultPartition<Operator>>(operators.size()); this.currentPartitionMap = Maps.newHashMapWithExpectedSize(operators.size()); this.operatorIdToPartition = Maps.newHashMapWithExpectedSize(operators.size()); // collect current partitions with committed operator state // those will be needed by the partitioner for split/merge for (PTOperator pOperator : operators) { Map<InputPort<?>, PartitionKeys> pks = pOperator.getPartitionKeys(); if (pks == null) { throw new AssertionError("Null partition: " + pOperator); } // if partitions checkpoint at different windows, processing for new or modified // partitions will start from earliest checkpoint found (at least once semantics) if (minCheckpoint == null) { minCheckpoint = pOperator.recoveryCheckpoint; } else if (minCheckpoint.windowId > pOperator.recoveryCheckpoint.windowId) { minCheckpoint = pOperator.recoveryCheckpoint; } Operator partitionedOperator = loadOperator(pOperator); DefaultPartition<Operator> partition = new DefaultPartition<Operator>(partitionedOperator, pks, pOperator.loadIndicator, pOperator.stats); currentPartitions.add(partition); currentPartitionMap.put(partition, pOperator); LOG.debug("partition load: {} {} {}", pOperator, partition.getPartitionKeys(), partition.getLoad()); operatorIdToPartition.put(pOperator.getId(), partition); } newPartitions = partitioner.definePartitions(new ArrayList<Partition<Operator>>(currentPartitions), this); } } private Partitioner<Operator> getPartitioner(PMapping currentMapping) { Operator operator = currentMapping.logicalOperator.getOperator(); Partitioner<Operator> partitioner = null; if (currentMapping.logicalOperator.getAttributes().contains(OperatorContext.PARTITIONER)) { @SuppressWarnings("unchecked") Partitioner<Operator> tmp = (Partitioner<Operator>)currentMapping.logicalOperator.getValue(OperatorContext.PARTITIONER); partitioner = tmp; } else if (operator instanceof Partitioner) { @SuppressWarnings("unchecked") Partitioner<Operator> tmp = (Partitioner<Operator>)operator; partitioner = tmp; } return partitioner; } private void redoPartitions(PMapping currentMapping, String note) { Partitioner<Operator> partitioner = getPartitioner(currentMapping); if (partitioner == null) { LOG.warn("No partitioner for {}", currentMapping.logicalOperator); return; } RepartitionContext mainPC = new RepartitionContext(partitioner, currentMapping, 0); if (mainPC.newPartitions.isEmpty()) { LOG.warn("Empty partition list after repartition: {}", currentMapping.logicalOperator); return; } int memoryPerPartition = currentMapping.logicalOperator.getValue(OperatorContext.MEMORY_MB); for (Map.Entry<OutputPortMeta, StreamMeta> stream : currentMapping.logicalOperator.getOutputStreams().entrySet()) { if (stream.getValue().getLocality() != Locality.THREAD_LOCAL && stream.getValue().getLocality() != Locality.CONTAINER_LOCAL) { memoryPerPartition += stream.getKey().getValue(PortContext.BUFFER_MEMORY_MB); } } for (OperatorMeta pp : currentMapping.parallelPartitions) { for (Map.Entry<OutputPortMeta, StreamMeta> stream : pp.getOutputStreams().entrySet()) { if (stream.getValue().getLocality() != Locality.THREAD_LOCAL && stream.getValue().getLocality() != Locality.CONTAINER_LOCAL) { memoryPerPartition += stream.getKey().getValue(PortContext.BUFFER_MEMORY_MB); } } memoryPerPartition += pp.getValue(OperatorContext.MEMORY_MB); } int requiredMemoryMB = (mainPC.newPartitions.size() - mainPC.currentPartitions.size()) * memoryPerPartition; if (requiredMemoryMB > availableMemoryMB) { LOG.warn("Insufficient headroom for repartitioning: available {}m required {}m", availableMemoryMB, requiredMemoryMB); return; } List<Partition<Operator>> addedPartitions = new ArrayList<Partition<Operator>>(); // determine modifications of partition set, identify affected operator instance(s) for (Partition<Operator> newPartition : mainPC.newPartitions) { PTOperator op = mainPC.currentPartitionMap.remove(newPartition); if (op == null) { addedPartitions.add(newPartition); } else { // check whether mapping was changed for (DefaultPartition<Operator> pi : mainPC.currentPartitions) { if (pi == newPartition && pi.isModified()) { // existing partition changed (operator or partition keys) // remove/add to update subscribers and state mainPC.currentPartitionMap.put(newPartition, op); addedPartitions.add(newPartition); } } } } // remaining entries represent deprecated partitions this.undeployOpers.addAll(mainPC.currentPartitionMap.values()); // downstream dependencies require redeploy, resolve prior to modifying plan Set<PTOperator> deps = this.getDependents(mainPC.currentPartitionMap.values()); this.undeployOpers.addAll(deps); // dependencies need redeploy, except operators excluded in remove this.deployOpers.addAll(deps); // process parallel partitions before removing operators from the plan LinkedHashMap<PMapping, RepartitionContext> partitionContexts = Maps.newLinkedHashMap(); Stack<OperatorMeta> parallelPartitions = new Stack<LogicalPlan.OperatorMeta>(); parallelPartitions.addAll(currentMapping.parallelPartitions); pendingLoop: while (!parallelPartitions.isEmpty()) { OperatorMeta ppMeta = parallelPartitions.pop(); for (StreamMeta s : ppMeta.getInputStreams().values()) { if (currentMapping.parallelPartitions.contains(s.getSource().getOperatorMeta()) && parallelPartitions.contains(s.getSource().getOperatorMeta())) { parallelPartitions.push(ppMeta); parallelPartitions.remove(s.getSource().getOperatorMeta()); parallelPartitions.push(s.getSource().getOperatorMeta()); continue pendingLoop; } } LOG.debug("Processing parallel partition {}", ppMeta); PMapping ppm = this.logicalToPTOperator.get(ppMeta); Partitioner<Operator> ppp = getPartitioner(ppm); if (ppp == null) { partitionContexts.put(ppm, null); } else { RepartitionContext pc = new RepartitionContext(ppp, ppm, mainPC.newPartitions.size()); if (pc.newPartitions == null) { throw new IllegalStateException("Partitioner returns null for parallel partition " + ppm.logicalOperator); } partitionContexts.put(ppm, pc); } } // plan updates start here, after all changes were identified // remove obsolete operators first, any freed resources // can subsequently be used for new/modified partitions List<PTOperator> copyPartitions = Lists.newArrayList(currentMapping.partitions); // remove deprecated partitions from plan for (PTOperator p : mainPC.currentPartitionMap.values()) { copyPartitions.remove(p); removePartition(p, currentMapping); mainPC.operatorIdToPartition.remove(p.getId()); } currentMapping.partitions = copyPartitions; // add new operators for (Partition<Operator> newPartition : addedPartitions) { PTOperator p = addPTOperator(currentMapping, newPartition, mainPC.minCheckpoint); mainPC.operatorIdToPartition.put(p.getId(), newPartition); } // process parallel partition changes for (Map.Entry<PMapping, RepartitionContext> e : partitionContexts.entrySet()) { if (e.getValue() == null) { // no partitioner, add required operators for (int i=0; i<addedPartitions.size(); i++) { LOG.debug("Automatically adding to parallel partition {}", e.getKey()); // set activation windowId to confirm to upstream checkpoints addPTOperator(e.getKey(), null, mainPC.minCheckpoint); } } else { RepartitionContext pc = e.getValue(); // track previous parallel partition mapping Map<Partition<Operator>, Partition<Operator>> prevMapping = Maps.newHashMap(); for (int i=0; i<mainPC.currentPartitions.size(); i++) { prevMapping.put(pc.currentPartitions.get(i), mainPC.currentPartitions.get(i)); } // determine which new partitions match upstream, remaining to be treated as new operator Map<Partition<Operator>, Partition<Operator>> newMapping = Maps.newHashMap(); Iterator<Partition<Operator>> itMain = mainPC.newPartitions.iterator(); Iterator<Partition<Operator>> itParallel = pc.newPartitions.iterator(); while (itMain.hasNext() && itParallel.hasNext()) { newMapping.put(itParallel.next(), itMain.next()); } for (Partition<Operator> newPartition : pc.newPartitions) { PTOperator op = pc.currentPartitionMap.remove(newPartition); if (op == null) { pc.addedPartitions.add(newPartition); } else if (prevMapping.get(newPartition) != newMapping.get(newPartition)) { // upstream partitions don't match, remove/add to replace with new operator pc.currentPartitionMap.put(newPartition, op); pc.addedPartitions.add(newPartition); } else { // check whether mapping was changed - based on DefaultPartition implementation for (DefaultPartition<Operator> pi : pc.currentPartitions) { if (pi == newPartition && pi.isModified()) { // existing partition changed (operator or partition keys) // remove/add to update subscribers and state mainPC.currentPartitionMap.put(newPartition, op); pc.addedPartitions.add(newPartition); } } } } if (!pc.currentPartitionMap.isEmpty()) { // remove obsolete partitions List<PTOperator> cowPartitions = Lists.newArrayList(e.getKey().partitions); for (PTOperator p : pc.currentPartitionMap.values()) { cowPartitions.remove(p); removePartition(p, e.getKey()); pc.operatorIdToPartition.remove(p.getId()); } e.getKey().partitions = cowPartitions; } // add new partitions for (Partition<Operator> newPartition : pc.addedPartitions) { PTOperator oper = addPTOperator(e.getKey(), newPartition, mainPC.minCheckpoint); pc.operatorIdToPartition.put(oper.getId(), newPartition); } getPartitioner(e.getKey()).partitioned(pc.operatorIdToPartition); } } updateStreamMappings(currentMapping); for (PMapping pp : partitionContexts.keySet()) { updateStreamMappings(pp); } deployChanges(); if (mainPC.currentPartitions.size() != mainPC.newPartitions.size()) { StramEvent ev = new StramEvent.PartitionEvent(currentMapping.logicalOperator.getName(), mainPC.currentPartitions.size(), mainPC.newPartitions.size()); ev.setReason(note); this.ctx.recordEventAsync(ev); } partitioner.partitioned(mainPC.operatorIdToPartition); } private void updateStreamMappings(PMapping m) { for (Map.Entry<OutputPortMeta, StreamMeta> opm : m.logicalOperator.getOutputStreams().entrySet()) { StreamMapping ug = m.outputStreams.get(opm.getKey()); if (ug == null) { ug = new StreamMapping(opm.getValue(), this); m.outputStreams.put(opm.getKey(), ug); } LOG.debug("update stream mapping for {} {}", opm.getKey().getOperatorMeta(), opm.getKey().getPortName()); ug.setSources(m.partitions); } for (Map.Entry<InputPortMeta, StreamMeta> ipm : m.logicalOperator.getInputStreams().entrySet()) { PMapping sourceMapping = this.logicalToPTOperator.get(ipm.getValue().getSource().getOperatorMeta()); if (ipm.getKey().getValue(PortContext.PARTITION_PARALLEL)) { if (sourceMapping.partitions.size() < m.partitions.size()) { throw new AssertionError("Number of partitions don't match in parallel mapping " + sourceMapping.logicalOperator.getName() + " -> " + m.logicalOperator.getName() + ", " + sourceMapping.partitions.size() + " -> " + m.partitions.size()); } int slidingWindowCount = 0; OperatorMeta sourceOM = sourceMapping.logicalOperator; if (sourceOM.getAttributes().contains(Context.OperatorContext.SLIDE_BY_WINDOW_COUNT)) { if (sourceOM.getValue(Context.OperatorContext.SLIDE_BY_WINDOW_COUNT) < sourceOM.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT)) { slidingWindowCount = sourceOM.getValue(OperatorContext.SLIDE_BY_WINDOW_COUNT); } else { LOG.warn("Sliding Window Count {} should be less than APPLICATION WINDOW COUNT {}", sourceOM.getValue(Context.OperatorContext.SLIDE_BY_WINDOW_COUNT), sourceOM.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT)); } } for (int i=0; i<m.partitions.size(); i++) { PTOperator oper = m.partitions.get(i); PTOperator sourceOper = sourceMapping.partitions.get(i); for (PTOutput sourceOut : sourceOper.outputs) { nextSource: if (sourceOut.logicalStream == ipm.getValue()) { //avoid duplicate entries in case of parallel partitions for (PTInput sinkIn : sourceOut.sinks) { //check if the operator is already in the sinks list and also the port name of that sink is same as the // input-port-meta currently being looked at since we allow an output port to connect to multiple inputs of the same operator. if (sinkIn.target == oper && sinkIn.portName.equals(ipm.getKey().getPortName())) { break nextSource; } } PTInput input; if (slidingWindowCount > 0) { PTOperator slidingUnifier = StreamMapping.createSlidingUnifier(sourceOut.logicalStream, this, sourceOM.getValue(Context.OperatorContext.APPLICATION_WINDOW_COUNT), slidingWindowCount); StreamMapping.addInput(slidingUnifier, sourceOut, null); input = new PTInput(ipm.getKey().getPortName(), ipm.getValue(), oper, null, slidingUnifier.outputs.get(0)); sourceMapping.outputStreams.get(ipm.getValue().getSource()).slidingUnifiers.add(slidingUnifier); } else { input = new PTInput(ipm.getKey().getPortName(), ipm.getValue(), oper, null, sourceOut); } oper.inputs.add(input); } } } } else { StreamMapping ug = sourceMapping.outputStreams.get(ipm.getValue().getSource()); if (ug == null) { ug = new StreamMapping(ipm.getValue(), this); m.outputStreams.put(ipm.getValue().getSource(), ug); } LOG.debug("update upstream stream mapping for {} {}", sourceMapping.logicalOperator, ipm.getValue().getSource().getPortName()); ug.setSources(sourceMapping.partitions); } } } public void deployChanges() { Set<PTContainer> newContainers = Sets.newHashSet(); Set<PTContainer> releaseContainers = Sets.newHashSet(); assignContainers(newContainers, releaseContainers); updatePartitionsInfoForPersistOperator(this.dag); this.undeployOpers.removeAll(newOpers.keySet()); //make sure all the new operators are included in deploy operator list this.deployOpers.addAll(this.newOpers.keySet()); // include downstream dependencies of affected operators into redeploy Set<PTOperator> deployOperators = this.getDependents(this.deployOpers); ctx.deploy(releaseContainers, this.undeployOpers, newContainers, deployOperators); this.newOpers.clear(); this.deployOpers.clear(); this.undeployOpers.clear(); } private void assignContainers(Set<PTContainer> newContainers, Set<PTContainer> releaseContainers) { Set<PTOperator> mxnUnifiers = Sets.newHashSet(); for (PTOperator o : this.newOpers.keySet()) { mxnUnifiers.addAll(o.upstreamMerge.values()); } Set<PTContainer> updatedContainers = Sets.newHashSet(); for (Map.Entry<PTOperator, Operator> operEntry : this.newOpers.entrySet()) { PTOperator oper = operEntry.getKey(); Checkpoint checkpoint = getActivationCheckpoint(operEntry.getKey()); initCheckpoint(oper, operEntry.getValue(), checkpoint); if (mxnUnifiers.contains(operEntry.getKey())) { // MxN unifiers are assigned with the downstream operator continue; } PTContainer newContainer = null; int memoryMB = 0; // handle container locality for (PTOperator inlineOper : oper.getGrouping(Locality.CONTAINER_LOCAL).getOperatorSet()) { if (inlineOper.container != null) { newContainer = inlineOper.container; break; } memoryMB += inlineOper.operatorMeta.getValue(OperatorContext.MEMORY_MB); memoryMB += inlineOper.getBufferServerMemory(); } if (newContainer == null) { int vCores = getVCores(oper.getGrouping(Locality.CONTAINER_LOCAL).getOperatorSet()); // attempt to find empty container with required size for (PTContainer c : this.containers) { if (c.operators.isEmpty() && c.getState() == PTContainer.State.ACTIVE && c.getAllocatedMemoryMB() == memoryMB && c.getAllocatedVCores() == vCores) { LOG.debug("Reusing existing container {} for {}", c, oper); c.setRequiredMemoryMB(0); c.setRequiredVCores(0); newContainer = c; break; } } if (newContainer == null) { // get new container LOG.debug("New container for: " + oper); newContainer = new PTContainer(this); newContainers.add(newContainer); containers.add(newContainer); } updatedContainers.add(newContainer); } setContainer(oper, newContainer); } // release containers that are no longer used for (PTContainer c : this.containers) { if (c.operators.isEmpty()) { LOG.debug("Container {} to be released", c); releaseContainers.add(c); containers.remove(c); } } for (PTContainer c : updatedContainers) { updateContainerMemoryWithBufferServer(c); c.setRequiredVCores(getVCores(c.getOperators())); } } private void initCheckpoint(PTOperator oper, Operator oo, Checkpoint checkpoint) { try { LOG.debug("Writing activation checkpoint {} {} {}", checkpoint, oper, oo); long windowId = oper.isOperatorStateLess() ? Stateless.WINDOW_ID : checkpoint.windowId; StorageAgent agent = oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT); agent.save(oo, oper.id, windowId); if (agent instanceof AsyncFSStorageAgent) { AsyncFSStorageAgent asyncFSStorageAgent = (AsyncFSStorageAgent)agent; if(!asyncFSStorageAgent.isSyncCheckpoint()) { asyncFSStorageAgent.copyToHDFS(oper.id, windowId); } } } catch (IOException e) { // inconsistent state, no recovery option, requires shutdown throw new IllegalStateException("Failed to write operator state after partition change " + oper, e); } oper.setRecoveryCheckpoint(checkpoint); if (!Checkpoint.INITIAL_CHECKPOINT.equals(checkpoint)) { oper.checkpoints.add(checkpoint); } } public Operator loadOperator(PTOperator oper) { try { LOG.debug("Loading state for {}", oper); return (Operator)oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT).load(oper.id, oper.isOperatorStateLess() ? Stateless.WINDOW_ID : oper.recoveryCheckpoint.windowId); } catch (IOException e) { throw new RuntimeException("Failed to read partition state for " + oper, e); } } /** * Initialize the activation checkpoint for the given operator. * Recursively traverses inputs until existing checkpoint or root operator is found. * NoOp when already initialized. * @param oper */ private Checkpoint getActivationCheckpoint(PTOperator oper) { if (oper.recoveryCheckpoint == null && oper.checkpoints.isEmpty()) { Checkpoint activationCheckpoint = Checkpoint.INITIAL_CHECKPOINT; for (PTInput input : oper.inputs) { PTOperator sourceOper = input.source.source; if (sourceOper.checkpoints.isEmpty()) { getActivationCheckpoint(sourceOper); } activationCheckpoint = Checkpoint.max(activationCheckpoint, sourceOper.recoveryCheckpoint); } return activationCheckpoint; } return oper.recoveryCheckpoint; } /** * Remove a partition that was reported as terminated by the execution layer. * Recursively removes all downstream operators with no remaining input. * @param p */ public void removeTerminatedPartition(PTOperator p) { // keep track of downstream operators for cascading remove Set<PTOperator> downstreamOpers = new HashSet<>(p.outputs.size()); for (PTOutput out : p.outputs) { for (PTInput sinkIn : out.sinks) { downstreamOpers.add(sinkIn.target); } } PMapping currentMapping = this.logicalToPTOperator.get(p.operatorMeta); if (currentMapping != null) { List<PTOperator> copyPartitions = Lists.newArrayList(currentMapping.partitions); copyPartitions.remove(p); removePartition(p, currentMapping); currentMapping.partitions = copyPartitions; } else { // remove the operator removePTOperator(p); } // remove orphaned downstream operators for (PTOperator dop : downstreamOpers) { if (dop.inputs.isEmpty()) { removeTerminatedPartition(dop); } } deployChanges(); } /** * Remove the given partition with any associated parallel partitions and * per-partition outputStreams. * * @param oper * @return */ private void removePartition(PTOperator oper, PMapping operatorMapping) { // remove any parallel partition for (PTOutput out : oper.outputs) { // copy list as it is modified by recursive remove for (PTInput in : Lists.newArrayList(out.sinks)) { for (LogicalPlan.InputPortMeta im : in.logicalStream.getSinks()) { PMapping m = this.logicalToPTOperator.get(im.getOperatorWrapper()); if (m.parallelPartitions == operatorMapping.parallelPartitions) { // associated operator parallel partitioned removePartition(in.target, operatorMapping); m.partitions.remove(in.target); } } } } // remove the operator removePTOperator(oper); } private PTOperator addPTOperator(PMapping nodeDecl, Partition<? extends Operator> partition, Checkpoint checkpoint) { PTOperator oper = newOperator(nodeDecl.logicalOperator, nodeDecl.logicalOperator.getName()); oper.recoveryCheckpoint = checkpoint; // output port objects for (Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry : nodeDecl.logicalOperator.getOutputStreams().entrySet()) { setupOutput(nodeDecl, oper, outputEntry); } String host = null; if (partition != null) { oper.setPartitionKeys(partition.getPartitionKeys()); host = partition.getAttributes().get(OperatorContext.LOCALITY_HOST); } if (host == null) { host = nodeDecl.logicalOperator.getValue(OperatorContext.LOCALITY_HOST); } nodeDecl.addPartition(oper); this.newOpers.put(oper, partition != null ? partition.getPartitionedInstance() : nodeDecl.logicalOperator.getOperator()); // // update locality // setLocalityGrouping(nodeDecl, oper, inlinePrefs, Locality.CONTAINER_LOCAL, host); setLocalityGrouping(nodeDecl, oper, localityPrefs, Locality.NODE_LOCAL, host); return oper; } /** * Create output port mapping for given operator and port. * Occurs when adding new partition or new logical stream. * Does nothing if source was already setup (on add sink to existing stream). * @param mapping * @param oper * @param outputEntry */ private void setupOutput(PMapping mapping, PTOperator oper, Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry) { for (PTOutput out : oper.outputs) { if (out.logicalStream == outputEntry.getValue()) { // already processed return; } } PTOutput out = new PTOutput(outputEntry.getKey().getPortName(), outputEntry.getValue(), oper); oper.outputs.add(out); } PTOperator newOperator(OperatorMeta om, String name) { PTOperator oper = new PTOperator(this, idSequence.incrementAndGet(), name, om); allOperators.put(oper.id, oper); oper.inputs = new ArrayList<PTInput>(); oper.outputs = new ArrayList<PTOutput>(); this.ctx.recordEventAsync(new StramEvent.CreateOperatorEvent(oper.getName(), oper.getId())); return oper; } private void setLocalityGrouping(PMapping pnodes, PTOperator newOperator, LocalityPrefs localityPrefs, Locality ltype,String host) { HostOperatorSet grpObj = newOperator.getGrouping(ltype); if(host!= null) { grpObj.setHost(host); } Set<PTOperator> s = grpObj.getOperatorSet(); s.add(newOperator); LocalityPref loc = localityPrefs.prefs.get(pnodes); if (loc != null) { for (PMapping localPM : loc.operators) { if (pnodes.parallelPartitions == localPM.parallelPartitions) { if (localPM.partitions.size() >= pnodes.partitions.size()) { // apply locality setting per partition s.addAll(localPM.partitions.get(pnodes.partitions.size()-1).getGrouping(ltype).getOperatorSet()); } } else { for (PTOperator otherNode : localPM.partitions) { s.addAll(otherNode.getGrouping(ltype).getOperatorSet()); } } } for (PTOperator localOper : s) { if(grpObj.getHost() == null){ grpObj.setHost(localOper.groupings.get(ltype).getHost()); } localOper.groupings.put(ltype, grpObj); } } } private List<InputPort<?>> getInputPortList(LogicalPlan.OperatorMeta operatorMeta) { List<InputPort<?>> inputPortList = Lists.newArrayList(); for (InputPortMeta inputPortMeta: operatorMeta.getInputStreams().keySet()) { inputPortList.add(inputPortMeta.getPortObject()); } return inputPortList; } void removePTOperator(PTOperator oper) { LOG.debug("Removing operator " + oper); // per partition merge operators if (!oper.upstreamMerge.isEmpty()) { for (PTOperator unifier : oper.upstreamMerge.values()) { removePTOperator(unifier); } } // remove inputs from downstream operators for (PTOutput out : oper.outputs) { for (PTInput sinkIn : out.sinks) { if (sinkIn.source.source == oper) { ArrayList<PTInput> cowInputs = Lists.newArrayList(sinkIn.target.inputs); cowInputs.remove(sinkIn); sinkIn.target.inputs = cowInputs; } } } // remove from upstream operators for (PTInput in : oper.inputs) { in.source.sinks.remove(in); } for (HostOperatorSet s : oper.groupings.values()) { s.getOperatorSet().remove(oper); } // remove checkpoint states try { synchronized (oper.checkpoints) { for (Checkpoint checkpoint : oper.checkpoints) { oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT).delete(oper.id, checkpoint.windowId); } } } catch (IOException e) { LOG.warn("Failed to remove state for " + oper, e); } List<PTOperator> cowList = Lists.newArrayList(oper.container.operators); cowList.remove(oper); oper.container.operators = cowList; this.deployOpers.remove(oper); this.undeployOpers.add(oper); this.allOperators.remove(oper.id); this.ctx.recordEventAsync(new StramEvent.RemoveOperatorEvent(oper.getName(), oper.getId())); } public PlanContext getContext() { return ctx; } public LogicalPlan getLogicalPlan() { return this.dag; } public List<PTContainer> getContainers() { return this.containers; } public Map<Integer, PTOperator> getAllOperators() { return this.allOperators; } /** * Get the partitions for the logical operator. * Partitions represent instances of the operator and do not include any unifiers. * @param logicalOperator * @return */ public List<PTOperator> getOperators(OperatorMeta logicalOperator) { return this.logicalToPTOperator.get(logicalOperator).partitions; } public Collection<PTOperator> getAllOperators(OperatorMeta logicalOperator) { return this.logicalToPTOperator.get(logicalOperator).getAllOperators(); } public boolean hasMapping(OperatorMeta om) { return this.logicalToPTOperator.containsKey(om); } // used for testing only @VisibleForTesting public List<PTOperator> getMergeOperators(OperatorMeta logicalOperator) { List<PTOperator> opers = Lists.newArrayList(); for (StreamMapping ug : this.logicalToPTOperator.get(logicalOperator).outputStreams.values()) { ug.addTo(opers); } return opers; } protected List<OperatorMeta> getRootOperators() { return dag.getRootOperators(); } private void getDeps(PTOperator operator, Set<PTOperator> visited) { visited.add(operator); for (PTInput in : operator.inputs) { if (in.source.isDownStreamInline()) { PTOperator sourceOperator = in.source.source; if (!visited.contains(sourceOperator)) { getDeps(sourceOperator, visited); } } } // downstream traversal for (PTOutput out: operator.outputs) { for (PTInput sink : out.sinks) { PTOperator sinkOperator = sink.target; if (!visited.contains(sinkOperator)) { getDeps(sinkOperator, visited); } } } } /** * Get all operator instances that depend on the specified operator instance(s). * Dependencies are all downstream and upstream inline operators. * @param operators * @return */ public Set<PTOperator> getDependents(Collection<PTOperator> operators) { Set<PTOperator> visited = new LinkedHashSet<PTOperator>(); if (operators != null) { for (PTOperator operator: operators) { getDeps(operator, visited); } } visited.addAll(getDependentPersistOperators(operators)); return visited; } private Set<PTOperator> getDependentPersistOperators(Collection<PTOperator> operators) { Set<PTOperator> persistOperators = new LinkedHashSet<PTOperator>(); if (operators != null) { for (PTOperator operator : operators) { for (PTInput in : operator.inputs) { if (in.logicalStream.getPersistOperator() != null) { for (InputPortMeta inputPort : in.logicalStream.getSinksToPersist()) { if (inputPort.getOperatorWrapper().equals(operator.operatorMeta)) { // Redeploy the stream wide persist operator only if the current sink is being persisted persistOperators.addAll(getOperators(in.logicalStream.getPersistOperator())); break; } } } for (Entry<InputPortMeta, OperatorMeta> entry : in.logicalStream.sinkSpecificPersistOperatorMap.entrySet()) { // Redeploy sink specific persist operators persistOperators.addAll(getOperators(entry.getValue())); } } } } return persistOperators; } /** * Add logical operator to the plan. Assumes that upstream operators have been added before. * @param om */ public final void addLogicalOperator(OperatorMeta om) { PMapping pnodes = new PMapping(om); String host = pnodes.logicalOperator.getValue(OperatorContext.LOCALITY_HOST); localityPrefs.add(pnodes, host); PMapping upstreamPartitioned = null; for (Map.Entry<LogicalPlan.InputPortMeta, StreamMeta> e : om.getInputStreams().entrySet()) { PMapping m = logicalToPTOperator.get(e.getValue().getSource().getOperatorMeta()); if (e.getKey().getValue(PortContext.PARTITION_PARALLEL).equals(true)) { // operator partitioned with upstream if (upstreamPartitioned != null) { // need to have common root if (!upstreamPartitioned.parallelPartitions.contains(m.logicalOperator) && upstreamPartitioned != m) { String msg = String.format("operator cannot extend multiple partitions (%s and %s)", upstreamPartitioned.logicalOperator, m.logicalOperator); throw new AssertionError(msg); } } m.parallelPartitions.add(pnodes.logicalOperator); pnodes.parallelPartitions = m.parallelPartitions; upstreamPartitioned = m; } if (Locality.CONTAINER_LOCAL == e.getValue().getLocality() || Locality.THREAD_LOCAL == e.getValue().getLocality()) { inlinePrefs.setLocal(m, pnodes); } else if (Locality.NODE_LOCAL == e.getValue().getLocality()) { localityPrefs.setLocal(m, pnodes); } } // // create operator instances // this.logicalToPTOperator.put(om, pnodes); if (upstreamPartitioned != null) { // parallel partition //LOG.debug("Operator {} should be partitioned to {} partitions", pnodes.logicalOperator.getName(), upstreamPartitioned.partitions.size()); initPartitioning(pnodes, upstreamPartitioned.partitions.size()); } else { initPartitioning(pnodes, 0); } updateStreamMappings(pnodes); } /** * Remove physical representation of given stream. Operators that are affected * in the execution layer will be added to the set. This method does not * automatically remove operators from the plan. * * @param sm */ public void removeLogicalStream(StreamMeta sm) { // remove incoming connections for logical stream for (InputPortMeta ipm : sm.getSinks()) { OperatorMeta om = ipm.getOperatorWrapper(); PMapping m = this.logicalToPTOperator.get(om); if (m == null) { throw new AssertionError("Unknown operator " + om); } for (PTOperator oper : m.partitions) { List<PTInput> inputsCopy = Lists.newArrayList(oper.inputs); for (PTInput input : oper.inputs) { if (input.logicalStream == sm) { input.source.sinks.remove(input); inputsCopy.remove(input); undeployOpers.add(oper); deployOpers.add(oper); } } oper.inputs = inputsCopy; } } // remove outgoing connections for logical stream PMapping m = this.logicalToPTOperator.get(sm.getSource().getOperatorMeta()); for (PTOperator oper : m.partitions) { List<PTOutput> outputsCopy = Lists.newArrayList(oper.outputs); for (PTOutput out : oper.outputs) { if (out.logicalStream == sm) { for (PTInput input : out.sinks) { PTOperator downstreamOper = input.source.source; downstreamOper.inputs.remove(input); Set<PTOperator> deps = this.getDependents(Collections.singletonList(downstreamOper)); undeployOpers.addAll(deps); deployOpers.addAll(deps); } outputsCopy.remove(out); undeployOpers.add(oper); deployOpers.add(oper); } } oper.outputs = outputsCopy; } } /** * Connect operators through stream. Currently new stream will not affect locality. * @param ipm Meta information about the input port */ public void connectInput(InputPortMeta ipm) { for (Map.Entry<LogicalPlan.InputPortMeta, StreamMeta> inputEntry : ipm.getOperatorWrapper().getInputStreams().entrySet()) { if (inputEntry.getKey() == ipm) { // initialize outputs for existing operators for (Map.Entry<LogicalPlan.OutputPortMeta, StreamMeta> outputEntry : inputEntry.getValue().getSource().getOperatorMeta().getOutputStreams().entrySet()) { PMapping sourceOpers = this.logicalToPTOperator.get(outputEntry.getKey().getOperatorMeta()); for (PTOperator oper : sourceOpers.partitions) { setupOutput(sourceOpers, oper, outputEntry); // idempotent undeployOpers.add(oper); deployOpers.add(oper); } } PMapping m = this.logicalToPTOperator.get(ipm.getOperatorWrapper()); updateStreamMappings(m); for (PTOperator oper : m.partitions) { undeployOpers.add(oper); deployOpers.add(oper); } } } } /** * Remove all physical operators for the given logical operator. * All connected streams must have been previously removed. * @param om */ public void removeLogicalOperator(OperatorMeta om) { PMapping opers = this.logicalToPTOperator.get(om); if (opers == null) { throw new AssertionError("Operator not in physical plan: " + om.getName()); } for (PTOperator oper : opers.partitions) { removePartition(oper, opers); } for (StreamMapping ug : opers.outputStreams.values()) { for (PTOperator oper : ug.cascadingUnifiers) { removePTOperator(oper); } if (ug.finalUnifier != null) { removePTOperator(ug.finalUnifier); } } LinkedHashMap<OperatorMeta, PMapping> copyMap = Maps.newLinkedHashMap(this.logicalToPTOperator); copyMap.remove(om); this.logicalToPTOperator = copyMap; } public void setAvailableResources(int memoryMB) { this.availableMemoryMB = memoryMB; } public void onStatusUpdate(PTOperator oper) { for (StatsListener l : oper.statsListeners) { final StatsListener.Response rsp = l.processStats(oper.stats); if (rsp != null) { //LOG.debug("Response to processStats = {}", rsp.repartitionRequired); oper.loadIndicator = rsp.loadIndicator; if (rsp.repartitionRequired) { final OperatorMeta om = oper.getOperatorMeta(); // concurrent heartbeat processing if (this.pendingRepartition.putIfAbsent(om, om) != null) { LOG.debug("Skipping repartitioning for {} load {}", oper, oper.loadIndicator); } else { LOG.debug("Scheduling repartitioning for {} load {}", oper, oper.loadIndicator); // hand over to monitor thread Runnable r = new Runnable() { @Override public void run() { redoPartitions(logicalToPTOperator.get(om), rsp.repartitionNote); pendingRepartition.remove(om); } }; ctx.dispatch(r); } } if (rsp.operatorRequests != null) { for (OperatorRequest cmd : rsp.operatorRequests) { StramToNodeRequest request = new StramToNodeRequest(); request.operatorId = oper.getId(); request.requestType = StramToNodeRequest.RequestType.CUSTOM; request.cmd = cmd; ctx.addOperatorRequest(oper, request); } } // for backward compatibility if(rsp.operatorCommands != null){ for(@SuppressWarnings("deprecation") com.datatorrent.api.StatsListener.OperatorCommand cmd: rsp.operatorCommands){ StramToNodeRequest request = new StramToNodeRequest(); request.operatorId = oper.getId(); request.requestType = StramToNodeRequest.RequestType.CUSTOM; OperatorCommandConverter converter = new OperatorCommandConverter(); converter.cmd = cmd; request.cmd = converter; ctx.addOperatorRequest(oper, request); } } } } } /** * Read available checkpoints from storage agent for all operators. * @param startTime * @param currentTime * @throws IOException */ public void syncCheckpoints(long startTime, long currentTime) throws IOException { for (PTOperator oper : getAllOperators().values()) { StorageAgent sa = oper.operatorMeta.getValue(OperatorContext.STORAGE_AGENT); long[] windowIds = sa.getWindowIds(oper.getId()); Arrays.sort(windowIds); oper.checkpoints.clear(); for (long wid : windowIds) { if (wid != Stateless.WINDOW_ID) { oper.addCheckpoint(wid, startTime); } } } } public Integer getStreamCodecIdentifier(StreamCodec<?> streamCodecInfo) { Integer id; synchronized (streamCodecIdentifiers) { id = streamCodecIdentifiers.get(streamCodecInfo); if (id == null) { id = strCodecIdSequence.incrementAndGet(); streamCodecIdentifiers.put(streamCodecInfo, id); } } return id; } @VisibleForTesting public Map<StreamCodec<?>, Integer> getStreamCodecIdentifiers() { return Collections.unmodifiableMap(streamCodecIdentifiers); } /** * This is for backward compatibility */ public static class OperatorCommandConverter implements OperatorRequest,Serializable { private static final long serialVersionUID = 1L; @SuppressWarnings("deprecation") public com.datatorrent.api.StatsListener.OperatorCommand cmd; @SuppressWarnings("deprecation") @Override public StatsListener.OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException { cmd.execute(operator,operatorId,windowId); return null; } } }
Fix rawtype warnings.
engine/src/main/java/com/datatorrent/stram/plan/physical/PhysicalPlan.java
Fix rawtype warnings.
<ide><path>ngine/src/main/java/com/datatorrent/stram/plan/physical/PhysicalPlan.java <ide> p.statsListeners = this.statsHandlers; <ide> } <ide> <add> /** <add> * Return all partitions and unifiers, except MxN unifiers <add> * @return <add> */ <ide> private Collection<PTOperator> getAllOperators() { <del>// if (partitions.size() == 1) { <del>// return Collections.singletonList(partitions.get(0)); <del>// } <ide> Collection<PTOperator> c = new ArrayList<PTOperator>(partitions.size() + 1); <ide> c.addAll(partitions); <ide> for (StreamMapping ug : outputStreams.values()) { <ide> for (StreamMeta s : n.getOutputStreams().values()) { <ide> if (s.getPersistOperator() != null) { <ide> InputPortMeta persistInputPort = s.getPersistOperatorInputPort(); <del> StreamCodecWrapperForPersistance persistCodec = (StreamCodecWrapperForPersistance) persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); <add> StreamCodecWrapperForPersistance<?> persistCodec = (StreamCodecWrapperForPersistance<?>) persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); <ide> if (persistCodec == null) <ide> continue; <ide> // Logging is enabled for the stream <ide> // Check partitioning for persist operators per sink too <ide> for (Entry<InputPortMeta, InputPortMeta> entry : s.sinkSpecificPersistInputPortMap.entrySet()) { <ide> InputPortMeta persistInputPort = entry.getValue(); <del> StreamCodec codec = persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); <add> StreamCodec<?> codec = persistInputPort.getAttributes().get(PortContext.STREAM_CODEC); <ide> if (codec != null) { <ide> if (codec instanceof StreamCodecWrapperForPersistance) { <del> StreamCodecWrapperForPersistance persistCodec = (StreamCodecWrapperForPersistance) codec; <add> StreamCodecWrapperForPersistance<?> persistCodec = (StreamCodecWrapperForPersistance<?>) codec; <ide> updatePersistOperatorWithSinkPartitions(persistInputPort, s.sinkSpecificPersistOperatorMap.get(entry.getKey()), persistCodec, entry.getKey()); <ide> } <ide> } <ide> } <ide> } <ide> <del> private void updatePersistOperatorWithSinkPartitions(InputPortMeta persistInputPort, OperatorMeta persistOperatorMeta, StreamCodecWrapperForPersistance persistCodec, InputPortMeta sinkPortMeta) <add> private void updatePersistOperatorWithSinkPartitions(InputPortMeta persistInputPort, OperatorMeta persistOperatorMeta, StreamCodecWrapperForPersistance<?> persistCodec, InputPortMeta sinkPortMeta) <ide> { <ide> Collection<PTOperator> ptOperators = getOperators(sinkPortMeta.getOperatorWrapper()); <ide> Collection<PartitionKeys> partitionKeysList = new ArrayList<PartitionKeys>(); <ide> for (OperatorMeta n : dag.getAllOperators()) { <ide> for (StreamMeta s : n.getOutputStreams().values()) { <ide> if (s.getPersistOperator() != null) { <del> Map<InputPortMeta, StreamCodec<Object>> inputStreamCodecs = new HashMap<InputPortMeta, StreamCodec<Object>>(); <add> Map<InputPortMeta, StreamCodec<?>> inputStreamCodecs = new HashMap<>(); <ide> // Logging is enabled for the stream <ide> for (InputPortMeta portMeta : s.getSinksToPersist()) { <ide> InputPort<?> port = portMeta.getPortObject(); <ide> } <ide> } <ide> if (!alreadyAdded) { <del> inputStreamCodecs.put(portMeta, (StreamCodec<Object>) inputStreamCodec); <add> inputStreamCodecs.put(portMeta, inputStreamCodec); <ide> } <ide> } <ide> } <ide> // Create Wrapper codec for Stream persistence using all unique <ide> // stream codecs <ide> // Logger should write merged or union of all input stream codecs <del> StreamCodec<Object> specifiedCodecForLogger = (s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) != null) ? (StreamCodec<Object>) s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) : (StreamCodec<Object>) s.getPersistOperatorInputPort().getPortObject().getStreamCodec(); <del> StreamCodecWrapperForPersistance<Object> codec = new StreamCodecWrapperForPersistance<Object>(inputStreamCodecs, specifiedCodecForLogger); <add> StreamCodec<?> specifiedCodecForLogger = (s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) != null) ? s.getPersistOperatorInputPort().getValue(PortContext.STREAM_CODEC) : s.getPersistOperatorInputPort().getPortObject().getStreamCodec(); <add> @SuppressWarnings({ "unchecked", "rawtypes" }) <add> StreamCodecWrapperForPersistance<Object> codec = new StreamCodecWrapperForPersistance(inputStreamCodecs, specifiedCodecForLogger); <ide> streamMetaToCodecMap.put(s, codec); <ide> } <ide> }
JavaScript
apache-2.0
d03724fd498bf1a9806b4626efa94036767ee33d
0
odf/webGavrog,odf/webGavrog
'use strict'; var I = require('immutable'); var isElement = function isElement(dsImpl, D) { return typeof D == 'number' && D >= 1 && D <= dsImpl.size; }; var elements = function elements(dsImpl) { return I.Range(1, dsImpl.size+1); }; var isIndex = function isIndex(dsImpl, i) { return typeof i == 'number' && i >= 0 && i <= dsImpl.dim; }; var indices = function indices(dsImpl) { return I.Range(0, dsImpl.dim+1); }; var get = function offset(dsImpl, list, i, D) { return list.get(i * dsImpl.size + D - 1); }; var s = function s(dsImpl, i, D) { if (isElement(dsImpl, D) && isIndex(dsImpl, i)) return get(dsImpl, dsImpl.s, i, D); }; var v = function v(dsImpl, i, j, D) { if (isElement(dsImpl, D) && isIndex(dsImpl, i) && isIndex(dsImpl, j)) { if (j == i+1) return get(dsImpl, dsImpl.v, i, D); else if (j == i-1) return get(dsImpl, dsImpl.v, j, D); else if (get(dsImpl, dsImpl.s, i, D) == get(dsImpl, dsImpl.s, j, D)) return 2; else return 1; } }; var fromData = function fromData(dim, sData, vData) { var _s = I.List(sData); var _v = I.List(vData); var _ds = { s : _s, v : _v, dim : dim, size: _v.size / dim }; return { isElement: function(D) { return isElement(_ds, D); }, elements : function() { return elements(_ds); }, isIndex : function(i) { return isIndex(_ds, i); }, indices : function() { return indices(_ds); }, s : function(i, D) { return s(_ds, i, D); }, v : function(i, j, D) { return v(_ds, i, j, D); }, toString : function() { return toString(this); } } }; var parseInts = function parseNumbers(str) { return str.trim().split(/\s+/).map(function(s) { return parseInt(s); }); }; var fromString = function fromString(str) { var parts = str.trim().replace(/^</, '').replace(/>$/, '').split(/:/); if (parts[0].match(/\d+\.\d+/)) parts.shift(); var dims = parseInts(parts[0]); var size = dims[0]; var dim = dims[1] || 2; var gluings = parts[1].split(/,/).map(parseInts); var degrees = parts[2].split(/,/).map(parseInts); var s = new Array((dim+1) * size); var v = new Array(dim * size); var get = function get(a, i, D) { return a[i * size + D - 1]; }; var set = function get(a, i, D, x) { a[i * size + D - 1] = x; }; for (var i = 0; i <= dim; ++i) { var k = -1; for (var D = 1; D <= size; ++D) { if (!get(s, i, D)) { var E = gluings[i][++k]; set(s, i, D, E); set(s, i, E, D); } } } for (var i = 0; i < dim; ++i) { var k = -1; for (var D = 1; D <= size; ++D) { if (!get(v, i, D)) { var m = degrees[i][++k]; var E = D; var r = 0; do { E = get(s, i, E) || E; E = get(s, i+1, E) || E; ++r; } while (E != D); var b = m / r; do { E = get(s, i, E) || E; set(v, i, E, b); E = get(s, i+1, E) || E; set(v, i, E, b); } while (E != D); } } } return fromData(dim, s, v); }; var dimension = function dimension(ds) { return ds.indices().size - 1; }; var size = function size(ds) { return ds.elements().size; }; var orbitReps = function orbitReps(ds, idcs) { idcs = I.List(idcs); switch (idcs.size) { case 0: return ds.elements(); case 1: return orbitReps1(ds, idcs.get(0)); case 2: return orbitReps2(ds, idcs.get(0), idcs.get(1)); default: throw new Error('not yet implemented'); } }; var orbitReps1 = function orbitReps1(ds, i, D) { return ds.elements().filter(function(D) { return ds.s(i, D) >= D; }); }; var orbitReps2 = function orbitReps2(ds, i, j, D) { var seen = new Array(ds.elements().size + 1); var result = []; ds.elements().forEach(function(D) { if (!seen[D]) { var E = D; do { E = ds.s(i, E) || E; seen[E] = true; E = ds.s(i+1, E) || E; seen[E] = true; } while (E != D); result.push(D); } }); return I.List(result); }; var r = function r(ds, i, j, D) { var k = 0; var E = D; do { E = ds.s(i, E) || E; E = ds.s(i+1, E) || E; ++k; } while (E != D); return k; }; var m = function m(ds, i, j, D) { return ds.v(i, j, D) * r(ds, i, j, D); }; var toString = function toString(ds) { var sDefs = ds.indices() .map(function(i) { return orbitReps(ds, [i]) .map(function(D) { return ds.s(i, D); }) .join(' '); }) .join(','); var mDefs = ds.indices() .filter(function(i) { return ds.isIndex(i+1); }) .map(function(i) { return orbitReps(ds, [i, i+1]) .map(function(D) { return m(ds, i, i+1, D); }) .join(' '); }) .join(','); var n = size(ds); var d = dimension(ds); return '<1.1:'+n+(d == 2 ? '' : ' '+d)+':'+sDefs+':'+mDefs+'>'; }; module.exports = { fromData : fromData, fromString: fromString, isElement : function(ds, D) { return ds.isElement(D); }, elements : function(ds) { return ds.elements(); }, isIndex : function(ds, i) { return ds.isIndex(i); }, indices : function(ds) { return ds.indices(); }, s : function(ds, i, D) { return ds.s(i, D); }, v : function(ds, i, j, D) { return ds.v(i, j, D); }, dimension : dimension, size : size, orbitReps : orbitReps, r : r, m : m }; if (require.main == module) console.log('' + fromString('<1.1:3:1 2 3,1 3,2 3:4 8,3>'));
src/dsymbol.js
'use strict'; var I = require('immutable'); var isElement = function isElement(dsImpl, D) { return typeof D == 'number' && D >= 1 && D <= dsImpl.size; }; var elements = function elements(dsImpl) { return I.Range(1, dsImpl.size+1); }; var isIndex = function isIndex(dsImpl, i) { return typeof i == 'number' && i >= 0 && i <= dsImpl.dim; }; var indices = function indices(dsImpl) { return I.Range(0, dsImpl.dim+1); }; var get = function offset(dsImpl, list, i, D) { return list.get(i * dsImpl.size + D - 1); }; var s = function s(dsImpl, i, D) { if (isElement(dsImpl, D) && isIndex(dsImpl, i)) return get(dsImpl, dsImpl.s, i, D); }; var v = function v(dsImpl, i, j, D) { if (isElement(dsImpl, D) && isIndex(dsImpl, i) && isIndex(dsImpl, j)) { if (j == i+1) return get(dsImpl, dsImpl.v, i, D); else if (j == i-1) return get(dsImpl, dsImpl.v, j, D); else if (get(dsImpl, dsImpl.s, i, D) == get(dsImpl, dsImpl.s, j, D)) return 2; else return 1; } }; var fromData = function fromData(dim, sData, vData) { var _s = I.List(sData); var _v = I.List(vData); var _ds = { s : _s, v : _v, dim : dim, size: _v.size / dim }; return { isElement: function(D) { return isElement(_ds, D); }, elements : function() { return elements(_ds); }, isIndex : function(i) { return isIndex(_ds, i); }, indices : function() { return indices(_ds); }, s : function(i, D) { return s(_ds, i, D); }, v : function(i, j, D) { return v(_ds, i, j, D); }, toString : function() { return toString(this); } } }; var parseInts = function parseNumbers(str) { return str.trim().split(/\s+/).map(function(s) { return parseInt(s); }); }; var fromString = function fromString(str) { var parts = str.trim().replace(/^</, '').replace(/>$/, '').split(/:/); if (parts[0].match(/\d+\.\d+/)) parts.shift(); var dims = parseInts(parts[0]); var size = dims[0]; var dim = dims[1] || 2; var gluings = parts[1].split(/,/).map(parseInts); var degrees = parts[2].split(/,/).map(parseInts); var s = new Array((dim+1) * size); var v = new Array(dim * size); var get = function get(a, i, D) { return a[i * size + D - 1]; }; var set = function get(a, i, D, x) { a[i * size + D - 1] = x; }; for (var i = 0; i <= dim; ++i) { var k = -1; for (var D = 1; D <= size; ++D) { if (!get(s, i, D)) { var E = gluings[i][++k]; set(s, i, D, E); set(s, i, E, D); } } } for (var i = 0; i < dim; ++i) { var k = -1; for (var D = 1; D <= size; ++D) { if (!get(v, i, D)) { var m = degrees[i][++k]; var E = D; var r = 0; do { E = get(s, i, E) || E; E = get(s, i+1, E) || E; ++r; } while (E != D); var b = m / r; do { E = get(s, i, E) || E; set(v, i, E, b); E = get(s, i+1, E) || E; set(v, i, E, b); } while (E != D); } } } return fromData(dim, s, v); }; var dimension = function dimension(ds) { return ds.indices().size - 1; }; var size = function size(ds) { return ds.elements().size - 1; }; var orbitReps = function orbitReps(ds, idcs) { idcs = I.List(idcs); switch (idcs.size) { case 0: return ds.elements(); case 1: return orbitReps1(ds, idcs.get(0)); case 2: return orbitReps2(ds, idcs.get(0), idcs.get(1)); default: throw new Error('not yet implemented'); } }; var orbitReps1 = function orbitReps1(ds, i, D) { return ds.elements().filter(function(D) { return ds.s(i, D) >= D; }); }; var orbitReps2 = function orbitReps2(ds, i, j, D) { var seen = new Array(ds.elements().size + 1); var result = []; ds.elements().forEach(function(D) { if (!seen[D]) { var E = D; do { E = ds.s(i, E) || E; seen[E] = true; E = ds.s(i+1, E) || E; seen[E] = true; } while (E != D); result.push(D); } }); return I.List(result); }; var r = function r(ds, i, j, D) { var k = 0; var E = D; do { E = ds.s(i, E) || E; E = ds.s(i+1, E) || E; ++k; } while (E != D); return k; }; var m = function m(ds, i, j, D) { return ds.v(i, j, D) * r(ds, i, j, D); }; var toString = function toString(ds) { var sDefs = ds.indices() .map(function(i) { return orbitReps(ds, [i]) .map(function(D) { return ds.s(i, D); }) .join(' '); }) .join(','); var mDefs = ds.indices() .filter(function(i) { return ds.isIndex(i+1); }) .map(function(i) { return orbitReps(ds, [i, i+1]) .map(function(D) { return m(ds, i, i+1, D); }) .join(' '); }) .join(','); var n = size(ds); var d = dimension(ds); return '<1.1:'+n+(d == 2 ? '' : ' '+d)+':'+sDefs+':'+mDefs+'>'; }; module.exports = { fromData : fromData, fromString: fromString }; if (require.main == module) console.log('' + fromString('<1.1:3:1 2 3,1 3,2 3:4 8,3>'));
fix the size function and export more things
src/dsymbol.js
fix the size function and export more things
<ide><path>rc/dsymbol.js <ide> <ide> <ide> var size = function size(ds) { <del> return ds.elements().size - 1; <add> return ds.elements().size; <ide> }; <ide> <ide> <ide> <ide> module.exports = { <ide> fromData : fromData, <del> fromString: fromString <add> fromString: fromString, <add> <add> isElement : function(ds, D) { return ds.isElement(D); }, <add> elements : function(ds) { return ds.elements(); }, <add> isIndex : function(ds, i) { return ds.isIndex(i); }, <add> indices : function(ds) { return ds.indices(); }, <add> s : function(ds, i, D) { return ds.s(i, D); }, <add> v : function(ds, i, j, D) { return ds.v(i, j, D); }, <add> <add> dimension : dimension, <add> size : size, <add> orbitReps : orbitReps, <add> r : r, <add> m : m <ide> }; <ide> <ide>
Java
apache-2.0
e7a9feeab2ffd07644f6bc83e164552c05be0880
0
awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples
/** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * */ // snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] // snippet-sourcedescription:[DeleteFunction.java demonstrates how to delete an AWS Lambda function by using the LambdaClient object] // snippet-service:[Lambda] // snippet-keyword:[Java] // snippet-keyword:[Amazon Lambda] // snippet-keyword:[Code Sample] // snippet-sourcetype:[full-example] // snippet-sourcedate:[2019-11-19] // snippet-sourceauthor:[AWS-scmacdon] // snippet-start:[lambda.java2.DeleteFunction.complete] package com.example.lambda; // snippet-start:[lambda.java2.delete.import] import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; import software.amazon.awssdk.services.lambda.model.ServiceException; // snippet-end:[lambda.java2.delete.import] public class DeleteFunction { public static void main(String[] args) { if (args.length < 1) { System.out.println("Please specify a function name"); System.exit(1); } // snippet-start:[lambda.java2.delete.main] String functionName = args[0]; try { Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder().region(region).build(); //Setup an DeleteFunctionRequest DeleteFunctionRequest request = DeleteFunctionRequest.builder() .functionName(functionName) .build(); //Invoke the Lambda deleteFunction method awsLambda.deleteFunction(request); System.out.println("Done"); } catch(ServiceException e) { e.getStackTrace(); } // snippet-end:[lambda.java2.delete.main] } } // snippet-end:[lambda.java2.DeleteFunction.complete]
javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java
/** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * */ // snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] // snippet-sourcedescription:[DeleteFunction.java demonstrates how to delete an AWS Lambda function by using the LambdaClient object] // snippet-service:[Lambda] // snippet-keyword:[Java] // snippet-keyword:[Amazon Lambda] // snippet-keyword:[Code Sample] // snippet-sourcetype:[full-example] // snippet-sourcedate:[2019-11-19] // snippet-sourceauthor:[AWS-scmacdon] // snippet-start:[lambda.Java.DeleteFunction.complete] package com.example.lambda; // snippet-start:[lambda.java2.delete.import] import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; import software.amazon.awssdk.services.lambda.model.ServiceException; // snippet-end:[lambda.java2.delete.import] public class DeleteFunction { public static void main(String[] args) { if (args.length < 1) { System.out.println("Please specify a function name"); System.exit(1); } // snippet-start:[lambda.java2.delete.main] String functionName = args[0]; try { Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder().region(region).build(); //Setup a DeleteFunctionRequest DeleteFunctionRequest request = DeleteFunctionRequest.builder() .functionName(functionName) .build(); //Invoke the Lambda deleteFunction method awsLambda.deleteFunction(request); System.out.println("Done"); } catch(ServiceException e) { e.getStackTrace(); } // snippet-end:[lambda.java2.delete.main] } } // snippet-end:[lambda.Java.DeleteFunction.complete]
Update DeleteFunction.java
javav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java
Update DeleteFunction.java
<ide><path>avav2/example_code/lambda/src/main/java/com/example/lambda/DeleteFunction.java <ide> // snippet-sourceauthor:[AWS-scmacdon] <ide> <ide> <del>// snippet-start:[lambda.Java.DeleteFunction.complete] <add>// snippet-start:[lambda.java2.DeleteFunction.complete] <ide> package com.example.lambda; <ide> <ide> // snippet-start:[lambda.java2.delete.import] <ide> Region region = Region.US_WEST_2; <ide> LambdaClient awsLambda = LambdaClient.builder().region(region).build(); <ide> <del> //Setup a DeleteFunctionRequest <add> //Setup an DeleteFunctionRequest <ide> DeleteFunctionRequest request = DeleteFunctionRequest.builder() <ide> .functionName(functionName) <ide> .build(); <ide> // snippet-end:[lambda.java2.delete.main] <ide> } <ide> } <del>// snippet-end:[lambda.Java.DeleteFunction.complete] <add>// snippet-end:[lambda.java2.DeleteFunction.complete]
JavaScript
apache-2.0
201a9d761aae3b12fafb7e683c1c5eeda5f427f8
0
cbeust/cedCube,cbeust/cedCube,cbeust/cedCube,cbeust/cedCube
/** * Created by cedricbeust on 2/19/17. */ var cubitSize = 90; TransparentCube = function(passedWidth, passedHeight, startString, nodeId) { this.width = passedWidth; this.height = passedHeight; this.isAnimated = false; var mapping = [ {x: -1, y: 1, z: 1, front: 0, top: 42, left: 29}, {x: 0, y: 1, z: 1, front: 1, top: 43}, {x: 1, y: 1, z: 1, front: 2, top: 44, right: 9}, {x: -1, y: 0, z: 1, front: 3, left: 32}, {x: 0, y: 0, z: 1, front: 4}, {x: 1, y: 0, z: 1, front: 5, right: 12}, {x: -1, y: -1, z: 1, front: 6, bottom: 45, left: 35}, {x: 0, y: -1, z: 1, front: 7, bottom: 46}, {x: 1, y: -1, z: 1, front: 8, bottom: 47, right: 15}, {x: -1, y: 1, z: 0, left: 28, top: 39}, {x: 0, y: 1, z: 0, top: 40}, {x: 1, y: 1, z: 0, right: 10, top: 41}, {x: -1, y: 0, z: 0, left: 31}, {x: 1, y: 0, z: 0, right: 13}, {x: -1, y: -1, z: 0, left: 34, bottom: 48}, {x: 0, y: -1, z: 0, bottom: 49}, {x: 1, y: -1, z: 0, right: 16, bottom: 50}, {x: -1, y: 1, z: -1, top: 36, left: 27, back: 20}, {x: 0, y: 1, z: -1, top: 37, back: 19}, {x: 1, y: 1, z: -1, top: 38, right: 11, back: 18}, {x: -1, y: 0, z: -1, left: 30, back: 23}, {x: 0, y: 0, z: -1, back: 22}, {x: 1, y: 0, z: -1, right: 14, back: 21}, {x: -1, y: -1, z: -1, left: 33, back: 26, bottom: 51}, {x: 0, y: -1, z: -1, back: 25, bottom: 51}, {x: 1, y: -1, z: -1, right: 17, back: 24, bottom: 52} ]; var colorMapping = { "g": "green", "b": "blue", "r": "red", "o": "orange", "w": "white", "y": "yellow", "X": "grey" }; var SIDES = ["front", "right", "back", "left", "top", "bottom"]; this.runCube = function() { this.init(); var cube = this.createCube(); this.scene.add(cube); this.animate(); }; function createPlane(x, y, z, color) { var geometry = new THREE.PlaneGeometry(cubitSize, cubitSize); var material = new THREE.MeshBasicMaterial({ color: color, side: THREE.DoubleSide }); var result = new THREE.Mesh(geometry, material); result.position.x = x; result.position.y = y; result.position.z = z; return result; } this.createCubit = function(config) { var group = new THREE.Object3D(); if (config.left) { var left = createPlane(-cubitSize / 2, 0, 0, config.left); left.rotation.y = Math.PI / 2; group.add(left); } if (config.right) { var right = createPlane(cubitSize / 2, 0, 0, config.right); right.rotation.y = Math.PI / 2; group.add(right); } if (config.back) { group.add(createPlane(0, 0, -cubitSize / 2, config.back)); } if (config.front) { group.add(createPlane(0, 0, cubitSize / 2, config.front)); } if (config.bottom) { var front = createPlane(0, -cubitSize / 2, 0, config.bottom); front.rotation.x = Math.PI / 2; group.add(front); } if (config.top) { var ttop = createPlane(0, cubitSize / 2, 0, config.top); ttop.rotation.x = Math.PI / 2; group.add(ttop); } return group; }; this.init = function() { this.scene = new THREE.Scene(); // camera this.camera = new THREE.PerspectiveCamera(45, this.width / this.height); // camera.position.set(100, -800, 400); // camera.rotation.x = 45 * ( Math.PI / 180 ); // camera.position.x = 200; this.camera.position.set(300, 250, 540); // this.camera.position.x = 300; // this.camera.position.y = 250; // this.camera.position.z = 540; this.camera.lookAt(new THREE.Vector3(0, 0, 0)); this.scene.add(this.camera); this.renderer = new THREE.WebGLRenderer({ antialias: true }); // The X axis is red. The Y axis is green. The Z axis is blue. // this.scene.add(new THREE.AxisHelper(500)); this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement); this.renderer.setSize(this.width, this.height); document.getElementById(nodeId).appendChild(this.renderer.domElement); }; this.createCube = function() { var result = new THREE.Object3D(); for (var i = 0; i < mapping.length; i++) { var m = mapping[i]; var config = {}; for (var j = 0; j < SIDES.length; j++) { if (m[SIDES[j]] != null) { var colorIndex = m[SIDES[j]]; var colorChar = startString.charAt(colorIndex); config[SIDES[j]] = colorMapping[colorChar]; } } console.log("M: " + m); var cubit = this.createCubit(config); cubit.position.x += 100 * m.x; cubit.position.y += 100 * m.y; cubit.position.z += 100 * m.z; result.add(cubit); } return result; }; this.animate = function() { this.controls.update(); this.renderer.render(this.scene, this.camera); }; // function render() { // // mesh.rotation.x += 0.01; // // mesh.rotation.y += 0.02; // // // group.rotation.x -= 0.05; // // group.rotation.y -= 0.05; // // camera.rotation.x += 0.2; // this.controls.update(); // // } // this.init(); }; new TransparentCube("....bbrb....rrr.rrXXXggggggXXXooXoob.........wwXwwwwww");
js/TransparentCube.js
/** * Created by cedricbeust on 2/19/17. */ var cubitSize = 90; TransparentCube = function(passedWidth, passedHeight, startString, nodeId) { this.width = passedWidth; this.height = passedHeight; this.isAnimated = false; var mapping = [ {x: -1, y: 1, z: 1, front: 0, top: 42, left: 29}, {x: 0, y: 1, z: 1, front: 1, top: 43}, {x: 1, y: 1, z: 1, front: 2, top: 44, right: 9}, {x: -1, y: 0, z: 1, front: 3, left: 32}, {x: 0, y: 0, z: 1, front: 4}, {x: 1, y: 0, z: 1, front: 5, right: 12}, {x: -1, y: -1, z: 1, front: 6, bottom: 45, left: 35}, {x: 0, y: -1, z: 1, front: 7, bottom: 46}, {x: 1, y: -1, z: 1, front: 8, bottom: 47, right: 15}, {x: -1, y: 1, z: 0, left: 28, top: 39}, {x: 0, y: 1, z: 0, top: 40}, {x: 1, y: 1, z: 0, right: 10, top: 41}, {x: -1, y: 0, z: 0, left: 31}, {x: 1, y: 0, z: 0, right: 13}, {x: -1, y: -1, z: 0, left: 34, bottom: 48}, {x: 0, y: -1, z: 0, bottom: 49}, {x: 1, y: -1, z: 0, right: 16, bottom: 50}, {x: -1, y: 1, z: -1, top: 36, left: 27, back: 20}, {x: 0, y: 1, z: -1, top: 37, back: 19}, {x: 1, y: 1, z: -1, top: 38, right: 11, back: 18}, {x: -1, y: 0, z: -1, left: 30, back: 23}, {x: 0, y: 0, z: -1, back: 22}, {x: 1, y: 0, z: -1, right: 14, back: 21}, {x: -1, y: -1, z: -1, left: 33, back: 26, bottom: 51}, {x: 0, y: -1, z: -1, back: 25, bottom: 51}, {x: 1, y: -1, z: -1, right: 17, back: 24, bottom: 52} ]; var colorMapping = { "g": "green", "b": "blue", "r": "red", "o": "orange", "w": "white", "y": "yellow", "X": "grey" }; var SIDES = ["front", "right", "back", "left", "top", "bottom"]; this.runCube = function() { this.init(); var cube = this.createCube(); this.scene.add(cube); this.animate(); }; function createPlane(x, y, z, color) { var geometry = new THREE.PlaneGeometry(cubitSize, cubitSize); var material = new THREE.MeshBasicMaterial({ color: color, side: THREE.DoubleSide }); var result = new THREE.Mesh(geometry, material); result.position.x = x; result.position.y = y; result.position.z = z; return result; } this.createCubit = function(config) { var group = new THREE.Object3D(); if (config.left) { var left = createPlane(-cubitSize / 2, 0, 0, config.left); left.rotation.y = Math.PI / 2; group.add(left); } if (config.right) { var right = createPlane(cubitSize / 2, 0, 0, config.right); right.rotation.y = Math.PI / 2; group.add(right); } if (config.back) { group.add(createPlane(0, 0, -cubitSize / 2, config.back)); } if (config.front) { group.add(createPlane(0, 0, cubitSize / 2, config.front)); } if (config.bottom) { var front = createPlane(0, -cubitSize / 2, 0, config.bottom); front.rotation.x = Math.PI / 2; group.add(front); } if (config.top) { var ttop = createPlane(0, cubitSize / 2, 0, config.top); ttop.rotation.x = Math.PI / 2; group.add(ttop); } return group; }; this.init = function() { this.renderer = new THREE.WebGLRenderer(); this.scene = new THREE.Scene(); // camera this.camera = new THREE.PerspectiveCamera(45, this.width / this.height); // camera.position.set(100, -800, 400); // camera.rotation.x = 45 * ( Math.PI / 180 ); // camera.position.x = 200; this.camera.position.set(300, 250, 540); // this.camera.position.x = 300; // this.camera.position.y = 250; // this.camera.position.z = 540; this.camera.lookAt(new THREE.Vector3(0, 0, 0)); this.scene.add(this.camera); // The X axis is red. The Y axis is green. The Z axis is blue. // this.scene.add(new THREE.AxisHelper(500)); this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement); this.renderer.setSize(this.width, this.height); document.getElementById(nodeId).appendChild(this.renderer.domElement); }; this.createCube = function() { var result = new THREE.Object3D(); for (var i = 0; i < mapping.length; i++) { var m = mapping[i]; var config = {}; for (var j = 0; j < SIDES.length; j++) { if (m[SIDES[j]] != null) { var colorIndex = m[SIDES[j]]; var colorChar = startString.charAt(colorIndex); config[SIDES[j]] = colorMapping[colorChar]; } } console.log("M: " + m); var cubit = this.createCubit(config); cubit.position.x += 100 * m.x; cubit.position.y += 100 * m.y; cubit.position.z += 100 * m.z; result.add(cubit); } return result; }; this.animate = function() { this.controls.update(); this.renderer.render(this.scene, this.camera); }; // function render() { // // mesh.rotation.x += 0.01; // // mesh.rotation.y += 0.02; // // // group.rotation.x -= 0.05; // // group.rotation.y -= 0.05; // // camera.rotation.x += 0.2; // this.controls.update(); // // } // this.init(); }; new TransparentCube("....bbrb....rrr.rrXXXggggggXXXooXoob.........wwXwwwwww");
Turn on antialias.
js/TransparentCube.js
Turn on antialias.
<ide><path>s/TransparentCube.js <ide> }; <ide> <ide> this.init = function() { <del> this.renderer = new THREE.WebGLRenderer(); <ide> this.scene = new THREE.Scene(); <ide> <ide> // camera <ide> // this.camera.position.z = 540; <ide> this.camera.lookAt(new THREE.Vector3(0, 0, 0)); <ide> this.scene.add(this.camera); <add> <add> this.renderer = new THREE.WebGLRenderer({ antialias: true }); <ide> <ide> // The X axis is red. The Y axis is green. The Z axis is blue. <ide> // this.scene.add(new THREE.AxisHelper(500));
Java
bsd-3-clause
bc740f3f97544db1bf16816658c8d0b143b94c17
0
tcoxon/metazelda,Ryan1729/metazelda
package net.bytten.metazelda; public class Room { public Condition precond; public final Coords coords; protected Symbol item; protected Edge[] edges; // index with Direction.{N,E,S,W} public Room(Coords coords, Symbol item, Condition precond) { this.coords = coords; this.item = item; this.edges = new Edge[Direction.NUM_DIRS]; this.precond = precond; // all edges initially null } public Room(int x, int y, Symbol item, Condition precond) { this(new Coords(x,y), item, precond); } public Symbol getItem() { return item; } public void setItem(Symbol item) { this.item = item; } public Edge[] getEdges() { return edges; } public Edge getEdge(int d) { return edges[d]; } public boolean isStart() { return item != null && item.isStart(); } public boolean isGoal() { return item != null && item.isGoal(); } public Condition getPrecond() { return precond; } }
src/net/bytten/metazelda/Room.java
package net.bytten.metazelda; import java.util.Random; public class Room { public Condition precond; public final Coords coords; protected Symbol item; protected Edge[] edges; // index with Direction.{N,E,S,W} public Room(Coords coords, Symbol item, Condition precond) { this.coords = coords; this.item = item; this.edges = new Edge[Direction.NUM_DIRS]; this.precond = precond; // all edges initially null } public Room(int x, int y, Symbol item, Condition precond) { this(new Coords(x,y), item, precond); } public Symbol getItem() { return item; } public void setItem(Symbol item) { this.item = item; } public Edge[] getEdges() { return edges; } public Edge getEdge(int d) { return edges[d]; } public boolean isStart() { return item != null && item.isStart(); } public boolean isGoal() { return item != null && item.isGoal(); } public Integer getRandomFreeEdgeDirection(Random rand) { // Return a random direction for which there is no outgoing edge in the room int d = rand.nextInt(Direction.NUM_DIRS), tries = 0; while (edges[d] != null && tries < Direction.NUM_DIRS){ d = (d+1) % Direction.NUM_DIRS; ++tries; } if (edges[d] == null) return d; return null; } public Condition getPrecond() { return precond; } }
Remove unused method on Room.
src/net/bytten/metazelda/Room.java
Remove unused method on Room.
<ide><path>rc/net/bytten/metazelda/Room.java <ide> package net.bytten.metazelda; <del> <del>import java.util.Random; <ide> <ide> public class Room { <ide> <ide> return item != null && item.isGoal(); <ide> } <ide> <del> public Integer getRandomFreeEdgeDirection(Random rand) { <del> // Return a random direction for which there is no outgoing edge in the room <del> int d = rand.nextInt(Direction.NUM_DIRS), <del> tries = 0; <del> while (edges[d] != null && tries < Direction.NUM_DIRS){ <del> d = (d+1) % Direction.NUM_DIRS; <del> ++tries; <del> } <del> if (edges[d] == null) <del> return d; <del> return null; <del> } <del> <ide> public Condition getPrecond() { <ide> return precond; <ide> }
Java
agpl-3.0
837dfd5917a6e3d0f40cf2cc938c5437e8b55077
0
roidelapluie/Gadgetbridge,rosenpin/Gadgetbridge,roidelapluie/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,ivanovlev/Gadgetbridge,rosenpin/Gadgetbridge,ivanovlev/Gadgetbridge,rosenpin/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,roidelapluie/Gadgetbridge,ivanovlev/Gadgetbridge
package nodomain.freeyourgadget.gadgetbridge.activities.appmanager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.widget.LinearLayoutManager; import android.view.HapticFeedbackConstants; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.PopupMenu; import com.woxthebox.draglistview.DragListView; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.activities.ExternalPebbleJSActivity; import nodomain.freeyourgadget.gadgetbridge.adapter.GBDeviceAppAdapter; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.impl.GBDeviceApp; import nodomain.freeyourgadget.gadgetbridge.model.DeviceService; import nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol; import nodomain.freeyourgadget.gadgetbridge.util.FileUtils; import nodomain.freeyourgadget.gadgetbridge.util.PebbleUtils; public abstract class AbstractAppManagerFragment extends Fragment { public static final String ACTION_REFRESH_APPLIST = "nodomain.freeyourgadget.gadgetbridge.appmanager.action.refresh_applist"; private static final Logger LOG = LoggerFactory.getLogger(AbstractAppManagerFragment.class); protected abstract void refreshList(); protected abstract String getSortFilename(); protected abstract boolean isCacheManager(); protected abstract boolean filterApp(GBDeviceApp gbDeviceApp); protected void onChangedAppOrder() { List<UUID> uuidList = new ArrayList<>(); for (GBDeviceApp gbDeviceApp : mGBDeviceAppAdapter.getItemList()) { uuidList.add(gbDeviceApp.getUUID()); } AppManagerActivity.rewriteAppOrderFile(getSortFilename(), uuidList); } private void refreshListFromPebble(Intent intent) { appList.clear(); int appCount = intent.getIntExtra("app_count", 0); for (Integer i = 0; i < appCount; i++) { String appName = intent.getStringExtra("app_name" + i.toString()); String appCreator = intent.getStringExtra("app_creator" + i.toString()); UUID uuid = UUID.fromString(intent.getStringExtra("app_uuid" + i.toString())); GBDeviceApp.Type appType = GBDeviceApp.Type.values()[intent.getIntExtra("app_type" + i.toString(), 0)]; GBDeviceApp app = new GBDeviceApp(uuid, appName, appCreator, "", appType); app.setOnDevice(true); if (filterApp(app)) { appList.add(app); } } } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_REFRESH_APPLIST)) { if (intent.hasExtra("app_count")) { LOG.info("got app info from pebble"); if (!isCacheManager()) { LOG.info("will refresh list based on data from pebble"); refreshListFromPebble(intent); } } else if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) >= 3 || isCacheManager()) { refreshList(); } mGBDeviceAppAdapter.notifyDataSetChanged(); } } }; private DragListView appListView; protected final List<GBDeviceApp> appList = new ArrayList<>(); private GBDeviceAppAdapter mGBDeviceAppAdapter; protected GBDevice mGBDevice = null; protected List<GBDeviceApp> getSystemApps() { List<GBDeviceApp> systemApps = new ArrayList<>(); //systemApps.add(new GBDeviceApp(UUID.fromString("4dab81a6-d2fc-458a-992c-7a1f3b96a970"), "Sports (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); //systemApps.add(new GBDeviceApp(UUID.fromString("cf1e816a-9db0-4511-bbb8-f60c48ca8fac"), "Golf (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("1f03293d-47af-4f28-b960-f2b02a6dd757"), "Music (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("b2cae818-10f8-46df-ad2b-98ad2254a3c1"), "Notifications (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("67a32d95-ef69-46d4-a0b9-854cc62f97f9"), "Alarms (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("18e443ce-38fd-47c8-84d5-6d0c775fbe55"), "Watchfaces (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); if (mGBDevice != null && !"aplite".equals(PebbleUtils.getPlatformName(mGBDevice.getModel()))) { systemApps.add(new GBDeviceApp(UUID.fromString("0863fc6a-66c5-4f62-ab8a-82ed00a98b5d"), "Send Text (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(PebbleProtocol.UUID_PEBBLE_HEALTH, "Health (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); } return systemApps; } protected List<GBDeviceApp> getSystemWatchfaces() { List<GBDeviceApp> systemWatchfaces = new ArrayList<>(); systemWatchfaces.add(new GBDeviceApp(UUID.fromString("8f3c8686-31a1-4f5f-91f5-01600c9bdc59"), "Tic Toc (System)", "Pebble Inc.", "", GBDeviceApp.Type.WATCHFACE_SYSTEM)); return systemWatchfaces; } protected List<GBDeviceApp> getCachedApps(List<UUID> uuids) { List<GBDeviceApp> cachedAppList = new ArrayList<>(); File cachePath; try { cachePath = new File(FileUtils.getExternalFilesDir().getPath() + "/pbw-cache"); } catch (IOException e) { LOG.warn("could not get external dir while reading pbw cache."); return cachedAppList; } File[] files; if (uuids == null) { files = cachePath.listFiles(); } else { files = new File[uuids.size()]; int index = 0; for (UUID uuid : uuids) { files[index++] = new File(uuid.toString() + ".pbw"); } } if (files != null) { for (File file : files) { if (file.getName().endsWith(".pbw")) { String baseName = file.getName().substring(0, file.getName().length() - 4); //metadata File jsonFile = new File(cachePath, baseName + ".json"); //configuration File configFile = new File(cachePath, baseName + "_config.js"); try { String jsonstring = FileUtils.getStringFromFile(jsonFile); JSONObject json = new JSONObject(jsonstring); cachedAppList.add(new GBDeviceApp(json, configFile.exists())); } catch (Exception e) { LOG.info("could not read json file for " + baseName); //FIXME: this is really ugly, if we do not find system uuids in pbw cache add them manually. Also duplicated code switch (baseName) { case "8f3c8686-31a1-4f5f-91f5-01600c9bdc59": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Tic Toc (System)", "Pebble Inc.", "", GBDeviceApp.Type.WATCHFACE_SYSTEM)); break; case "1f03293d-47af-4f28-b960-f2b02a6dd757": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Music (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "b2cae818-10f8-46df-ad2b-98ad2254a3c1": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Notifications (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "67a32d95-ef69-46d4-a0b9-854cc62f97f9": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Alarms (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "18e443ce-38fd-47c8-84d5-6d0c775fbe55": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Watchfaces (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "0863fc6a-66c5-4f62-ab8a-82ed00a98b5d": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Send Text (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; } /* else if (baseName.equals("4dab81a6-d2fc-458a-992c-7a1f3b96a970")) { cachedAppList.add(new GBDeviceApp(UUID.fromString("4dab81a6-d2fc-458a-992c-7a1f3b96a970"), "Sports (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); } else if (baseName.equals("cf1e816a-9db0-4511-bbb8-f60c48ca8fac")) { cachedAppList.add(new GBDeviceApp(UUID.fromString("cf1e816a-9db0-4511-bbb8-f60c48ca8fac"), "Golf (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); } */ if (mGBDevice != null && !"aplite".equals(PebbleUtils.getPlatformName(mGBDevice.getModel()))) { if (baseName.equals(PebbleProtocol.UUID_PEBBLE_HEALTH.toString())) { cachedAppList.add(new GBDeviceApp(PebbleProtocol.UUID_PEBBLE_HEALTH, "Health (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); continue; } } if (uuids == null) { cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), baseName, "N/A", "", GBDeviceApp.Type.UNKNOWN)); } } } } } return cachedAppList; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mGBDevice = ((AppManagerActivity) getActivity()).getGBDevice(); if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) < 3 && !isCacheManager()) { appListView.setDragEnabled(false); } IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_REFRESH_APPLIST); LocalBroadcastManager.getInstance(getContext()).registerReceiver(mReceiver, filter); if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) < 3) { GBApplication.deviceService().onAppInfoReq(); if (isCacheManager()) { refreshList(); } } else { refreshList(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_appmanager, container, false); appListView = (DragListView) (rootView.findViewById(R.id.appListView)); appListView.setLayoutManager(new LinearLayoutManager(getActivity())); mGBDeviceAppAdapter = new GBDeviceAppAdapter(appList, R.layout.item_with_details, R.id.item_image, this.getContext(), this); appListView.setAdapter(mGBDeviceAppAdapter, false); appListView.setCanDragHorizontally(false); appListView.setDragListListener(new DragListView.DragListListener() { @Override public void onItemDragStarted(int position) { } @Override public void onItemDragging(int itemPosition, float x, float y) { } @Override public void onItemDragEnded(int fromPosition, int toPosition) { onChangedAppOrder(); } }); return rootView; } protected void sendOrderToDevice(String concatFilename) { ArrayList<UUID> uuids = new ArrayList<>(); for (GBDeviceApp gbDeviceApp : mGBDeviceAppAdapter.getItemList()) { uuids.add(gbDeviceApp.getUUID()); } if (concatFilename != null) { ArrayList<UUID> concatUuids = AppManagerActivity.getUuidsFromFile(concatFilename); uuids.addAll(concatUuids); } GBApplication.deviceService().onAppReorder(uuids.toArray(new UUID[uuids.size()])); } public boolean openPopupMenu(View view, int position) { PopupMenu popupMenu = new PopupMenu(getContext(), view); popupMenu.getMenuInflater().inflate(R.menu.appmanager_context, popupMenu.getMenu()); Menu menu = popupMenu.getMenu(); final GBDeviceApp selectedApp = appList.get(position); if (!selectedApp.isInCache()) { menu.removeItem(R.id.appmanager_app_reinstall); menu.removeItem(R.id.appmanager_app_delete_cache); } if (!PebbleProtocol.UUID_PEBBLE_HEALTH.equals(selectedApp.getUUID())) { menu.removeItem(R.id.appmanager_health_activate); menu.removeItem(R.id.appmanager_health_deactivate); } if (selectedApp.getType() == GBDeviceApp.Type.APP_SYSTEM || selectedApp.getType() == GBDeviceApp.Type.WATCHFACE_SYSTEM) { menu.removeItem(R.id.appmanager_app_delete); } if (!selectedApp.isConfigurable()) { menu.removeItem(R.id.appmanager_app_configure); } switch (selectedApp.getType()) { case WATCHFACE: case APP_GENERIC: case APP_ACTIVITYTRACKER: break; default: menu.removeItem(R.id.appmanager_app_openinstore); } //menu.setHeaderTitle(selectedApp.getName()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { return onContextItemSelected(item, selectedApp); } } ); view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); popupMenu.show(); return true; } public boolean onContextItemSelected(MenuItem item, GBDeviceApp selectedApp) { switch (item.getItemId()) { case R.id.appmanager_app_delete_cache: String baseName; try { baseName = FileUtils.getExternalFilesDir().getPath() + "/pbw-cache/" + selectedApp.getUUID(); } catch (IOException e) { LOG.warn("could not get external dir while trying to access pbw cache."); return true; } String[] suffixToDelete = new String[]{".pbw", ".json", "_config.js", "_preset.json"}; for (String suffix : suffixToDelete) { File fileToDelete = new File(baseName + suffix); if (!fileToDelete.delete()) { LOG.warn("could not delete file from pbw cache: " + fileToDelete.toString()); } else { LOG.info("deleted file: " + fileToDelete.toString()); } } AppManagerActivity.deleteFromAppOrderFile("pbwcacheorder.txt", selectedApp.getUUID()); // FIXME: only if successful // fall through case R.id.appmanager_app_delete: if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) >= 3) { AppManagerActivity.deleteFromAppOrderFile(mGBDevice.getAddress() + ".watchapps", selectedApp.getUUID()); // FIXME: only if successful AppManagerActivity.deleteFromAppOrderFile(mGBDevice.getAddress() + ".watchfaces", selectedApp.getUUID()); // FIXME: only if successful Intent refreshIntent = new Intent(AbstractAppManagerFragment.ACTION_REFRESH_APPLIST); LocalBroadcastManager.getInstance(getContext()).sendBroadcast(refreshIntent); } GBApplication.deviceService().onAppDelete(selectedApp.getUUID()); return true; case R.id.appmanager_app_reinstall: File cachePath; try { cachePath = new File(FileUtils.getExternalFilesDir().getPath() + "/pbw-cache/" + selectedApp.getUUID() + ".pbw"); } catch (IOException e) { LOG.warn("could not get external dir while trying to access pbw cache."); return true; } GBApplication.deviceService().onInstallApp(Uri.fromFile(cachePath)); return true; case R.id.appmanager_health_activate: GBApplication.deviceService().onInstallApp(Uri.parse("fake://health")); return true; case R.id.appmanager_health_deactivate: GBApplication.deviceService().onAppDelete(selectedApp.getUUID()); return true; case R.id.appmanager_app_configure: GBApplication.deviceService().onAppStart(selectedApp.getUUID(), true); Intent startIntent = new Intent(getContext().getApplicationContext(), ExternalPebbleJSActivity.class); startIntent.putExtra(DeviceService.EXTRA_APP_UUID, selectedApp.getUUID()); startIntent.putExtra(GBDevice.EXTRA_DEVICE, mGBDevice); startActivity(startIntent); return true; case R.id.appmanager_app_openinstore: String url = "https://apps.getpebble.com/en_US/search/" + ((selectedApp.getType() == GBDeviceApp.Type.WATCHFACE) ? "watchfaces" : "watchapps") + "/1?query=" + selectedApp.getName() + "&dev_settings=true"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); return true; default: return super.onContextItemSelected(item); } } @Override public void onDestroy() { LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mReceiver); super.onDestroy(); } }
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/activities/appmanager/AbstractAppManagerFragment.java
package nodomain.freeyourgadget.gadgetbridge.activities.appmanager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.widget.LinearLayoutManager; import android.view.HapticFeedbackConstants; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.PopupMenu; import com.woxthebox.draglistview.DragListView; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.activities.ExternalPebbleJSActivity; import nodomain.freeyourgadget.gadgetbridge.adapter.GBDeviceAppAdapter; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.impl.GBDeviceApp; import nodomain.freeyourgadget.gadgetbridge.model.DeviceService; import nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol; import nodomain.freeyourgadget.gadgetbridge.util.FileUtils; import nodomain.freeyourgadget.gadgetbridge.util.PebbleUtils; public abstract class AbstractAppManagerFragment extends Fragment { public static final String ACTION_REFRESH_APPLIST = "nodomain.freeyourgadget.gadgetbridge.appmanager.action.refresh_applist"; private static final Logger LOG = LoggerFactory.getLogger(AbstractAppManagerFragment.class); protected abstract void refreshList(); protected abstract String getSortFilename(); protected abstract boolean isCacheManager(); protected abstract boolean filterApp(GBDeviceApp gbDeviceApp); protected void onChangedAppOrder() { List<UUID> uuidList = new ArrayList<>(); for (GBDeviceApp gbDeviceApp : mGBDeviceAppAdapter.getItemList()) { uuidList.add(gbDeviceApp.getUUID()); } AppManagerActivity.rewriteAppOrderFile(getSortFilename(), uuidList); } private void refreshListFromPebble(Intent intent) { appList.clear(); int appCount = intent.getIntExtra("app_count", 0); for (Integer i = 0; i < appCount; i++) { String appName = intent.getStringExtra("app_name" + i.toString()); String appCreator = intent.getStringExtra("app_creator" + i.toString()); UUID uuid = UUID.fromString(intent.getStringExtra("app_uuid" + i.toString())); GBDeviceApp.Type appType = GBDeviceApp.Type.values()[intent.getIntExtra("app_type" + i.toString(), 0)]; GBDeviceApp app = new GBDeviceApp(uuid, appName, appCreator, "", appType); app.setOnDevice(true); if (filterApp(app)) { appList.add(app); } } } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_REFRESH_APPLIST)) { if (intent.hasExtra("app_count")) { LOG.info("got app info from pebble"); if (!isCacheManager()) { LOG.info("will refresh list based on data from pebble"); refreshListFromPebble(intent); } } else if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) >= 3 || isCacheManager()) { refreshList(); } mGBDeviceAppAdapter.notifyDataSetChanged(); } } }; private DragListView appListView; protected final List<GBDeviceApp> appList = new ArrayList<>(); private GBDeviceAppAdapter mGBDeviceAppAdapter; protected GBDevice mGBDevice = null; protected List<GBDeviceApp> getSystemApps() { List<GBDeviceApp> systemApps = new ArrayList<>(); //systemApps.add(new GBDeviceApp(UUID.fromString("4dab81a6-d2fc-458a-992c-7a1f3b96a970"), "Sports (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); //systemApps.add(new GBDeviceApp(UUID.fromString("cf1e816a-9db0-4511-bbb8-f60c48ca8fac"), "Golf (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("1f03293d-47af-4f28-b960-f2b02a6dd757"), "Music (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("b2cae818-10f8-46df-ad2b-98ad2254a3c1"), "Notifications (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("67a32d95-ef69-46d4-a0b9-854cc62f97f9"), "Alarms (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(UUID.fromString("18e443ce-38fd-47c8-84d5-6d0c775fbe55"), "Watchfaces (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); if (mGBDevice != null && !"aplite".equals(PebbleUtils.getPlatformName(mGBDevice.getModel()))) { systemApps.add(new GBDeviceApp(UUID.fromString("0863fc6a-66c5-4f62-ab8a-82ed00a98b5d"), "Send Text (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); systemApps.add(new GBDeviceApp(PebbleProtocol.UUID_PEBBLE_HEALTH, "Health (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); } return systemApps; } protected List<GBDeviceApp> getSystemWatchfaces() { List<GBDeviceApp> systemWatchfaces = new ArrayList<>(); systemWatchfaces.add(new GBDeviceApp(UUID.fromString("8f3c8686-31a1-4f5f-91f5-01600c9bdc59"), "Tic Toc (System)", "Pebble Inc.", "", GBDeviceApp.Type.WATCHFACE_SYSTEM)); return systemWatchfaces; } protected List<GBDeviceApp> getCachedApps(List<UUID> uuids) { List<GBDeviceApp> cachedAppList = new ArrayList<>(); File cachePath; try { cachePath = new File(FileUtils.getExternalFilesDir().getPath() + "/pbw-cache"); } catch (IOException e) { LOG.warn("could not get external dir while reading pbw cache."); return cachedAppList; } File[] files; if (uuids == null) { files = cachePath.listFiles(); } else { files = new File[uuids.size()]; int index = 0; for (UUID uuid : uuids) { files[index++] = new File(uuid.toString() + ".pbw"); } } if (files != null) { for (File file : files) { if (file.getName().endsWith(".pbw")) { String baseName = file.getName().substring(0, file.getName().length() - 4); //metadata File jsonFile = new File(cachePath, baseName + ".json"); //configuration File configFile = new File(cachePath, baseName + "_config.js"); try { String jsonstring = FileUtils.getStringFromFile(jsonFile); JSONObject json = new JSONObject(jsonstring); cachedAppList.add(new GBDeviceApp(json, configFile.exists())); } catch (Exception e) { LOG.info("could not read json file for " + baseName); //FIXME: this is really ugly, if we do not find system uuids in pbw cache add them manually. Also duplicated code switch (baseName) { case "8f3c8686-31a1-4f5f-91f5-01600c9bdc59": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Tic Toc (System)", "Pebble Inc.", "", GBDeviceApp.Type.WATCHFACE_SYSTEM)); break; case "1f03293d-47af-4f28-b960-f2b02a6dd757": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Music (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "b2cae818-10f8-46df-ad2b-98ad2254a3c1": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Notifications (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "67a32d95-ef69-46d4-a0b9-854cc62f97f9": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Alarms (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "18e443ce-38fd-47c8-84d5-6d0c775fbe55": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Watchfaces (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; case "0863fc6a-66c5-4f62-ab8a-82ed00a98b5d": cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), "Send Text (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); break; } /* else if (baseName.equals("4dab81a6-d2fc-458a-992c-7a1f3b96a970")) { cachedAppList.add(new GBDeviceApp(UUID.fromString("4dab81a6-d2fc-458a-992c-7a1f3b96a970"), "Sports (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); } else if (baseName.equals("cf1e816a-9db0-4511-bbb8-f60c48ca8fac")) { cachedAppList.add(new GBDeviceApp(UUID.fromString("cf1e816a-9db0-4511-bbb8-f60c48ca8fac"), "Golf (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); } */ if (mGBDevice != null && !"aplite".equals(PebbleUtils.getPlatformName(mGBDevice.getModel()))) { if (baseName.equals(PebbleProtocol.UUID_PEBBLE_HEALTH.toString())) { cachedAppList.add(new GBDeviceApp(PebbleProtocol.UUID_PEBBLE_HEALTH, "Health (System)", "Pebble Inc.", "", GBDeviceApp.Type.APP_SYSTEM)); continue; } } if (uuids == null) { cachedAppList.add(new GBDeviceApp(UUID.fromString(baseName), baseName, "N/A", "", GBDeviceApp.Type.UNKNOWN)); } } } } } return cachedAppList; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mGBDevice = ((AppManagerActivity) getActivity()).getGBDevice(); if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) < 3 && !isCacheManager()) { appListView.setDragEnabled(false); } IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_REFRESH_APPLIST); LocalBroadcastManager.getInstance(getContext()).registerReceiver(mReceiver, filter); if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) < 3) { GBApplication.deviceService().onAppInfoReq(); if (isCacheManager()) { refreshList(); } } else { refreshList(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_appmanager, container, false); appListView = (DragListView) (rootView.findViewById(R.id.appListView)); appListView.setLayoutManager(new LinearLayoutManager(getActivity())); mGBDeviceAppAdapter = new GBDeviceAppAdapter(appList, R.layout.item_with_details, R.id.item_image, this.getContext(), this); appListView.setAdapter(mGBDeviceAppAdapter, false); appListView.setCanDragHorizontally(false); appListView.setDragListListener(new DragListView.DragListListener() { @Override public void onItemDragStarted(int position) { } @Override public void onItemDragging(int itemPosition, float x, float y) { } @Override public void onItemDragEnded(int fromPosition, int toPosition) { onChangedAppOrder(); } }); return rootView; } protected void sendOrderToDevice(String concatFilename) { ArrayList<UUID> uuids = new ArrayList<>(); for (GBDeviceApp gbDeviceApp : mGBDeviceAppAdapter.getItemList()) { uuids.add(gbDeviceApp.getUUID()); } if (concatFilename != null) { ArrayList<UUID> concatUuids = AppManagerActivity.getUuidsFromFile(concatFilename); uuids.addAll(concatUuids); } GBApplication.deviceService().onAppReorder(uuids.toArray(new UUID[uuids.size()])); } public boolean openPopupMenu(View view, int position) { PopupMenu popupMenu = new PopupMenu(getContext(), view); popupMenu.getMenuInflater().inflate(R.menu.appmanager_context, popupMenu.getMenu()); Menu menu = popupMenu.getMenu(); final GBDeviceApp selectedApp = appList.get(position); if (!selectedApp.isInCache()) { menu.removeItem(R.id.appmanager_app_reinstall); menu.removeItem(R.id.appmanager_app_delete_cache); } if (!PebbleProtocol.UUID_PEBBLE_HEALTH.equals(selectedApp.getUUID())) { menu.removeItem(R.id.appmanager_health_activate); menu.removeItem(R.id.appmanager_health_deactivate); } if (selectedApp.getType() == GBDeviceApp.Type.APP_SYSTEM || selectedApp.getType() == GBDeviceApp.Type.WATCHFACE_SYSTEM) { menu.removeItem(R.id.appmanager_app_delete); } if (!selectedApp.isConfigurable()) { menu.removeItem(R.id.appmanager_app_configure); } switch (selectedApp.getType()) { case WATCHFACE: case APP_GENERIC: case APP_ACTIVITYTRACKER: break; default: menu.removeItem(R.id.appmanager_app_openinstore); } //menu.setHeaderTitle(selectedApp.getName()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { return onContextItemSelected(item, selectedApp); } } ); view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); popupMenu.show(); return true; } public boolean onContextItemSelected(MenuItem item, GBDeviceApp selectedApp) { switch (item.getItemId()) { case R.id.appmanager_health_deactivate: case R.id.appmanager_app_delete_cache: String baseName; try { baseName = FileUtils.getExternalFilesDir().getPath() + "/pbw-cache/" + selectedApp.getUUID(); } catch (IOException e) { LOG.warn("could not get external dir while trying to access pbw cache."); return true; } String[] suffixToDelete = new String[]{".pbw", ".json", "_config.js", "_preset.json"}; for (String suffix : suffixToDelete) { File fileToDelete = new File(baseName + suffix); if (!fileToDelete.delete()) { LOG.warn("could not delete file from pbw cache: " + fileToDelete.toString()); } else { LOG.info("deleted file: " + fileToDelete.toString()); } } AppManagerActivity.deleteFromAppOrderFile("pbwcacheorder.txt", selectedApp.getUUID()); // FIXME: only if successful // fall through case R.id.appmanager_app_delete: if (PebbleUtils.getFwMajor(mGBDevice.getFirmwareVersion()) >= 3) { AppManagerActivity.deleteFromAppOrderFile(mGBDevice.getAddress() + ".watchapps", selectedApp.getUUID()); // FIXME: only if successful AppManagerActivity.deleteFromAppOrderFile(mGBDevice.getAddress() + ".watchfaces", selectedApp.getUUID()); // FIXME: only if successful Intent refreshIntent = new Intent(AbstractAppManagerFragment.ACTION_REFRESH_APPLIST); LocalBroadcastManager.getInstance(getContext()).sendBroadcast(refreshIntent); } GBApplication.deviceService().onAppDelete(selectedApp.getUUID()); return true; case R.id.appmanager_app_reinstall: File cachePath; try { cachePath = new File(FileUtils.getExternalFilesDir().getPath() + "/pbw-cache/" + selectedApp.getUUID() + ".pbw"); } catch (IOException e) { LOG.warn("could not get external dir while trying to access pbw cache."); return true; } GBApplication.deviceService().onInstallApp(Uri.fromFile(cachePath)); return true; case R.id.appmanager_health_activate: GBApplication.deviceService().onInstallApp(Uri.parse("fake://health")); return true; case R.id.appmanager_app_configure: GBApplication.deviceService().onAppStart(selectedApp.getUUID(), true); Intent startIntent = new Intent(getContext().getApplicationContext(), ExternalPebbleJSActivity.class); startIntent.putExtra(DeviceService.EXTRA_APP_UUID, selectedApp.getUUID()); startIntent.putExtra(GBDevice.EXTRA_DEVICE, mGBDevice); startActivity(startIntent); return true; case R.id.appmanager_app_openinstore: String url = "https://apps.getpebble.com/en_US/search/" + ((selectedApp.getType() == GBDeviceApp.Type.WATCHFACE) ? "watchfaces" : "watchapps") + "/1?query=" + selectedApp.getName() + "&dev_settings=true"; Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); return true; default: return super.onContextItemSelected(item); } } @Override public void onDestroy() { LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mReceiver); super.onDestroy(); } }
Pebble: fix Pebble Health vanishing when deactivating
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/activities/appmanager/AbstractAppManagerFragment.java
Pebble: fix Pebble Health vanishing when deactivating
<ide><path>pp/src/main/java/nodomain/freeyourgadget/gadgetbridge/activities/appmanager/AbstractAppManagerFragment.java <ide> <ide> public boolean onContextItemSelected(MenuItem item, GBDeviceApp selectedApp) { <ide> switch (item.getItemId()) { <del> case R.id.appmanager_health_deactivate: <ide> case R.id.appmanager_app_delete_cache: <ide> String baseName; <ide> try { <ide> case R.id.appmanager_health_activate: <ide> GBApplication.deviceService().onInstallApp(Uri.parse("fake://health")); <ide> return true; <add> case R.id.appmanager_health_deactivate: <add> GBApplication.deviceService().onAppDelete(selectedApp.getUUID()); <add> return true; <ide> case R.id.appmanager_app_configure: <ide> GBApplication.deviceService().onAppStart(selectedApp.getUUID(), true); <ide>
JavaScript
mit
43e84b7e0f80ec767e404e27fc4ebef5927afe94
0
arik-le/A-Home-For-Every-Child,arik-le/A-Home-For-Every-Child
var usersManagement = function() { const FAIL = -1; const ADDPAGE = 1; const EDITPAGE = 2; const OS_TYPE = 3; var clubhousesInfo = []; // key and name var page; var addPrevType; var AddSectionClubName; var EditSectionClubName; var clubIndex_Edit; var socialPrevCH_edit=[]; var userToEdit; //------------------------------------------------------------------------------------------------- var UserPage= { inputSection: '<div class="container">'+ '<div class="row main">'+ '<div class="panel-heading">'+ '<div class="panel-title text-center">'+ '<h2 id="allTitles" class="registerTitle">רישום משתמש</h2>'+ '</div>'+ '</div> '+ '<div class="main-login main-center">'+ '<form class="form-horizontal" method="post" action="#">'+ '<div class="form-group">'+ '<label for="name" class="col-sm-2 controlLabel" >:שם פרטי</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>'+ '<input type="text" class="form-control" name="name" id="UserPName" maxlength="20" placeholder="הכנס שם פרטי" dir="rtl" />'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="UserLastName" class="col-sm-2 controlLabel" id="formTxts">:שם משפחה</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>'+ '<input type="text" class="form-control" name="UserLastName" id="UserLName" maxlength="20" placeholder="הכנס שם משפחה" dir="rtl"/>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="username" class="col-sm-2 controlLabel">:שם משתמש</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>'+ '<input type="email" class="form-control" name="username" id="username" maxlength="20" placeholder="הכנס שם משתמש" dir="rtl"/>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="username" class="col-sm-2 controlLabel">:סוג משתמש</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-slideshare" aria-hidden="true"></i></span>'+ '<select type="text" class="form-control" id="userType">'+ '<option value = "0" class="ptUser">הורה</option>'+ '<option value = "1" class="tcUser">מורה</option>'+ '<option value = "2" class="GuUser">מדריך</option>'+ '<option value = "3" class="SWUser">עו"ס</option>'+ '<option value = "4" class="AdmUser">מנהל</option>'+ '</select>'+ '</div>'+ '</div>'+ '</div>'+ '<div id = "passwordSection">'+ '<div class="form-group">'+ '<label for="password" class="col-sm-2 controlLabel">:סיסמא</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>'+ '<input type="password" class="form-control" name="password" id="password" maxlength="10" placeholder="הכנס סיסמה"/>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="confirm" class="col-sm-2 controlLabel">:אימות סיסמא</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>'+ '<input type="password" class="form-control" name="confirm" id="confirm" maxlength="10" placeholder="אמת בשנית סיסמה"/>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '<div id="selectCHSection" class="form-group">'+ '<label for="clubHouseName" class="col-sm-2 controlLabel">:בחר מועדונית</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-home" aria-hidden="true"></i></span>'+ '<select type="text" id="clubhouse_select_Add" class="form-control clubHouseName" placeholder="בחר מועדונית מתוך הרשימה">'+ '</select>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group" id="buttons_area">'+ '</div>'+ '</form>'+ '</div>'+ '</div>' } //------------------------------------------------------------------------------------------------- var EditUserOp={ inputSection: '<div class="container">'+ '<label id="allTitles">:בחר מועדונית</label>'+ '</br>'+ '<div class="row">'+ '<div id = "clubBottunGroup" class="col-md-4 text-center">'+ '</div>'+ '</div>'+ '</div>'+ '<br>'+ '<label id="allTitles2">:בחר משתמש</label>'+ '</br></br>'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-user" aria-hidden="true"></i></span>'+ '<select type="text" id="usersInCH" class="form-control" >'+ '</select>'+ '</div>'+ '</br>'+ '<div class="col-md-4 text-center">'+ '<button type="button" id="openUserEditBtn" class="btn btn-warning btn3d">לחץ כאן לערוך</button>'+ '</div>'+ '</div>' } //------------------------------------------------------------------------------------------------- var EditUserButtons= { inputSection: '</br>'+ '<button id ="change-button" type="button" class="btn btn-primary btn-block btn-lg edit-button" >עריכה</button>'+ '<button id ="delete-button" type="button" class="btn-danger btn-danger btn-block btn-lg delete-button" >מחיקת משתמש</button>' } //------------------------------------------------------------------------------------------------- var addUserButton= { inputSection: '</br>'+ '<button type="button" class="btn btn-primary btn-lg btn-block register-button" data-toggle="modal" data-target="#myModal" id="addUser" >הרשמה</button>' } //------------------------------------------------------------------------------------------------- var swMultiselect = { inputSection: '<ul id = "swMultiSelect" class="list-group">'+ '</ul>' } //------------------------------------------------------------------------------------------------- ///////////////////////////////////////////////////////////////////// // ADD USER // ///////////////////////////////////////////////////////////////////// var addUser=function() { page = ADDPAGE; clubhousesInfo = []; loadClubhousesData(); $('.Nav').collapse('hide'); $("#body").html(UserPage.inputSection); $('#buttons_area').html(addUserButton.inputSection); $("#addUser").click(createUser); addPrevType=0; $('#userType').on('change',updateType); } //------------------------------------------------------------------------------------------------- var createUser=function() { var firstName=document.getElementById("UserPName").value; var lastName=document.getElementById("UserLName").value; var username=document.getElementById("username").value; var fPassword=document.getElementById("password").value; var sPassword=document.getElementById("confirm").value; var Uclubhouse; if( sPassword!=fPassword && fPassword != "" )//&& fPassword < 4) { alert(" הסיסמאות שהוזנו אינן תואמות"); return; } var res = inputsValidation({firstName:firstName,lastName:lastName,username:username,password:sPassword}); if (!res) return; // selecting the clubhouse var e; e=document.getElementById("userType"); var type = e.selectedIndex; if(type >= 0 && type < User.SOCIAL ) { if (page == ADDPAGE) e = document.getElementById("clubhouse_select_Add"); if(e.selectedIndex == -1)// when there are no clubhouses at DB { alert("אנא הזן מועדוניות לפני יצירת משתמשים במערכת"); return; } Uclubhouse= e.options[e.selectedIndex].text; var clubKey = getClubKeyByName(Uclubhouse); checkAndPush(username,fPassword,firstName,lastName,type,clubKey); } else if (type == User.SOCIAL) { var clubhousesSw=[]; var childs = $('#swMultiSelect')[0].childNodes; for (var i = 0; i < childs.length; i++) { var element = childs[i]; if (element.className == 'list-group-item active') { var temp = getClubKeyByName(childs[i].textContent); clubhousesSw.push(temp); } } if (clubhousesSw.length <= 0) { alert("אנא הזן מועדוניות לפני יצירת משתמשים במערכת"); return; } checkAndPush(username,fPassword,firstName,lastName,type,clubhousesSw); } else if (type == User.ADMIN) { checkAndPush(username,fPassword,firstName,lastName,type,clubhousesSw); } } var inputsValidation = function(args) { var usernameRegex = /^\w+(\-+(\w)*)*$/; // var namesRegex = /^[[(א-ת)]+$/|/^[(a-zA-Z)]]+$/; var spacesRegex = /\s/; if (args.firstName == "" || args.lastName == "" || args.username == "") { alert("אנא מלא את כל השדות הנדרשים"); return false; } if(!usernameRegex.test(args.username)) { alert("יש לבחור שם משתמש המורכב ממספרים ואותיות בלבד"); return false; } if( spacesRegex.test(args.firstName) == true) { alert("שם פרטי שהוזן אינו חוקי"); return false; } if( spacesRegex.test(args.lastName) == true) { alert("שם משפחה שהוזן אינו חוקי"); return false; } if(args.password.length<4 || args.password.length>10) { alert("נא להזין סיסמא באורך בין 4-10 תווים"); return false; } return true; } var checkAndPush = function(username,fPassword,firstName,lastName,type,clubKey) { //check if the username exist - if not push to DB var ref = firebase.database().ref("users"); ref.once("value") .then(function(data) // when value recieved { // in case the root is empty -> name is not exist if (data.val() == null) return false; var allUsers = data.val(); // get the whole tree of users var keys = Object.keys(allUsers); // get all keys // loop on the answer array to find user name. var temp = false; for(var i =0; i<keys.length;i++) { var k = keys[i]; var tempName = allUsers[k].username; if( tempName == username ) temp = true; } return temp; }).then(function(res) { if(res) // name is already exist in DB { alert("שם משתמש כבר קיים"); return; } // else - push user to DB var usersRef = firebase.database().ref('users'); var newUser; if(type == User.ADMIN) { newUser = User.create(username,fPassword,firstName,lastName,type,null); var key = usersRef.push(newUser); firebase.database().ref('users/' + key.key + '/userKey').set(key.key); addUser(); } else if(type == User.SOCIAL) { newUser = User.create(username,fPassword,firstName,lastName,type,clubKey); var key = usersRef.push(newUser); firebase.database().ref('users/' + key.key + '/userKey').set(key.key); for (var i = 0; i < clubKey.length; i++) { firebase.database().ref('clubhouse/'+clubKey[i]+'/usersList') .push({userkey:key.key,username:username,type:type}); } addUser(); } else { newUser = User.create(username,fPassword,firstName,lastName,type,clubKey); var key = usersRef.push(newUser); firebase.database().ref('users/' + key.key + '/userKey').set(key.key); firebase.database().ref('clubhouse/'+clubKey+'/usersList') .push({userkey:key.key,username:username,type:type}); addUser(); } alert("הוזן בהצלחה"); }); } ///////////////////////////////////////////////////////////////// // addPrevType holds the last value on selectbox var updateType = function(e) { var type = e.target.value; var input; if(addPrevType !=type && type == User.ADMIN) { // inject for admin $('#selectCHSection').html(""); } else if(addPrevType !=type && type == User.SOCIAL) { // inject for social worker input = swMultiselect.inputSection; $('#selectCHSection').html(input); for (var i = 0; i < clubhousesInfo.length; i++) { var id='swClubhouseSelect'+i; var line = '<li id="'+id+'" class="list-group-item">'+clubhousesInfo[i].name+'</li>' $('#swMultiSelect').append(line) $('#'+id).click(SwClubListener); } } else { // inject for regualar users , guide parent teacer input ='<label for="clubHouseName" class="col-sm-2 controlLabel">:בחר מועדונית</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-home" aria-hidden="true"></i></span>'+ '<select type="text" id="clubhouse_select_Add" class="form-control clubHouseName" placeholder="בחר מועדונית מתוך הרשימה">'+ '</select>'+ '</div>'+ '</div>'; $('#selectCHSection').html(input); for(var i =0; i<clubhousesInfo.length;i++) $('#clubhouse_select_Add').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>'); } addPrevType = type; } var addClubSelectValue = function() { var index = document.getElementById("clubhouse_select_Add").value; if (index > clubhousesInfo.length) return; if(AddSectionClubName == clubhousesInfo[index].name) return; AddSectionClubName = clubhousesInfo[index].name; return AddSectionClubName; } // sw multiselect listener var SwClubListener = function(e) { var targetClass = e.currentTarget.className; if(targetClass == 'list-group-item') e.currentTarget.className = 'list-group-item active'; if(targetClass == 'list-group-item active') e.currentTarget.className = 'list-group-item'; } ///////////////////////////////////////////////////////////////////// // EDIT USER // ///////////////////////////////////////////////////////////////////// // Edit user function var editUser=function() { page = EDITPAGE; $("#body").html(EditUserOp.inputSection); $('.Nav').collapse('hide'); clubhousesInfo = []; loadClubhousesData(); // attach listeners after loading clubhouses $('#openUserEditBtn').click(editUserListener); } //====================================================================================== // show user list from a selected clubhouse var showUsersPerCH = function(clubhouseSelected) { document.getElementById('usersInCH').innerHTML = ""; var tmpIndex = getClubKeyIndex(clubhouseSelected); if(tmpIndex == FAIL) { alert("לא נמצאה מועדונית "); return; } var ClubKey = clubhousesInfo[tmpIndex].key; var ref = firebase.database().ref("clubhouse/"+ClubKey+"/usersList"); ref.once("value") .then(function(data) // when value recieved { if (data.val() == null) { alert("לא נמצאו משתמשים להציג "); return; } var users = data.val(); // get the whole tree of clubhouses var keys = Object.keys(users); // get all keys for(var i =0; i<keys.length;i++) { var k = keys[i]; var uKey=users[k].userkey; var userRef= firebase.database().ref("users/"+uKey); userRef.ref.once("value").then(function(data) { var user=data.val(); $('#usersInCH').append('<option value="'+user.userKey+'">'+user.firstName+' '+user.lastName+'</option>'); }); } }); } var editUserListener= function() { var e = document.getElementById("usersInCH"); if(e.selectedIndex<0) { alert('לא נבחר שם משתמש'); return; } var userKey = e.options[e.selectedIndex].value; var user = loadUserDetails(userKey); }; // load user data when selected var loadUserDetails = function(userKey) { if(!userKey) { alert('key Error: '+userKey); return; } // get the user object firebase.database().ref("users/"+userKey).once("value") .then(function(data) { var user = data.val(); if(user) { userToEdit = user; injectEditPage(user); } }); } var injectEditPage = function (user) { $('#body').html(UserPage.inputSection); document.getElementById('allTitles').innerHTML ="עריכת/מחיקת משתמש"; $('#UserPName').val(user.firstName); $('#UserLName').val(user.lastName); $('#username').val(user.username); $('#userType').val(user.userType); document.getElementById("userType").disabled = true; //disable option for changing user-type $('#passwordSection').html(""); // prevent change the password if there is oath with email /*$('#password').val(user.password); $('#confirm').val(user.password);*/ // html inject for each user type// //===============================// if(user.userType == User.ADMIN) { $('#selectCHSection').html(""); } // multi select injection for SW if ( user.userType == User.SOCIAL) { socialPrevCH_edit=[]; // keep the indexes of the old clubhouses the social had $('#selectCHSection').html(swMultiselect.inputSection); for (var i = 0; i < clubhousesInfo.length; i++) { var id='swClubhouseSelect'+i; var line = '<li id="'+id+'" class="list-group-item">'+clubhousesInfo[i].name+'</li>' for (var j = 0; j < userToEdit.clubhouseKey.length; j++) { // to retrive the slected clubhouses if(userToEdit.clubhouseKey[j] == clubhousesInfo[i].key) { line = '<li id="'+id+'" class="list-group-item active">'+clubhousesInfo[i].name+'</li>'; socialPrevCH_edit.push(i); } } $('#swMultiSelect').append(line); $('#'+id).click(SwClubListener); } } if(user.userType >= User.PARENT && user.userType < User.SOCIAL) { // append element to select and choose the selected index on default. var tempIndex; for(var i =0; i<clubhousesInfo.length;i++) { if (clubhousesInfo[i].key == user.clubhouseKey) tempIndex = i; $('#clubhouse_select_Add').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>'); } $('#clubhouse_select_Add').val(tempIndex); $('#clubhouse_select_Add').on('change',function(e) // update selected index listener { clubIndex_Edit = e.currentTarget.selectedIndex; }); } $('#buttons_area').html(EditUserButtons.inputSection); $('#change-button').click(changeUserInfo); $('#delete-button').click(function(){ deleteUser(user.userType) }); } var changeUserInfo = function() { var obj={}; var firstName = $('#UserPName').val(); var lastName = $('#UserLName').val(); var Nusername = $('#username').val(); var password = $('#password').val(); var confirm = $('#confirm').val(); if (userToEdit.firstName != firstName) obj.firstName = firstName; if (userToEdit.lastName != lastName) obj.lastName = lastName; if (userToEdit.username != Nusername) obj.username = Nusername; if( userToEdit.userType >= User.PARENT && userToEdit.userType < User.SOCIAL) { // currClubIndex= $('#clubhouse_select_Add').val(); currClubKey = clubhousesInfo[clubIndex_Edit].key; if(userToEdit.clubhouseKey != currClubKey) // clubhouse changed { // update new clubhouse firebase.database().ref('clubhouse/'+currClubKey+'/usersList') .push({userkey:userToEdit.userKey,username:Nusername,type:userType}); // remove from old clubhouse removeUserFromClubOnly(userToEdit.clubhouseKey); obj.clubhouseKey = currClubKey; // update user object } } if ( userToEdit.userType == User.SOCIAL) { // get curr indexes var currIndexes=[]; var childs = $('#swMultiSelect')[0].childNodes; for (var i = 0; i < childs.length; i++) { var element = childs[i]; if (element.className == 'list-group-item active') { currIndexes.push(i); } } if(currIndexes.length<=0) { alert('אנא הזן מועדוניות '); return; } //......................................... // compare selection with previous values var max = Math.max(socialPrevCH_edit.length, currIndexes.length); console.log(socialPrevCH_edit); console.log(currIndexes); var keyRM; var keyADD; for (var i = 0 ; i < max ; i++) { if(socialPrevCH_edit[i]==currIndexes[i]) continue; // indexes are not equal - remove from old clubhouse if(i < socialPrevCH_edit.length) { keyRM = clubhousesInfo[socialPrevCH_edit[i]].key; removeUserFromClubOnly(keyRM); } // push new Clubhouse if (i < currIndexes.length ) { keyADD = clubhousesInfo[currIndexes[i]].key; firebase.database().ref('clubhouse/'+keyADD+'/userList').push({userkey:userToEdit.userKey,username:Nusername,type:userType}); } } // if equal var tempCHARr=[]; for(var i = 0 ; i <currIndexes.length ; i++) tempCHARr.push(clubhousesInfo[currIndexes[i]].key); obj.clubhouseKey = tempCHARr; } /*if (password != confirm) { alert('הסיסמאות אינן תואמות'); return; if (userToEdit.password != password) obj.password = password; }*/ // var e = document.getElementById("clubhouse_select_Add"); var userRef = firebase.database().ref('users/'); userRef.child(userToEdit.userKey).update(obj); alert("המידע עודכן בהצלחה"); editUser(); } var deleteUser = function(uType) { if(uType == OS_TYPE) //if the user is Social worker - then it delete him from several clubhouses deleteUserInCH(); else { var clubKey = clubhousesInfo[clubIndex_Edit].key; firebase.database().ref("clubhouse/"+clubKey+"/usersList").once("value") .then(function(data) { if (data.val() == null) { alert("לא נמצאו משתמשים להציג "); return; } var users = data.val(); // get the whole tree of clubhouses var keys = Object.keys(users); // get all keys for(var i =0; i<keys.length;i++) { var key = users[keys[i]].userkey; var k = keys[i]; if(userToEdit.userKey == users[keys[i]].userkey) { firebase.database().ref("clubhouse/"+clubKey+"/usersList").child(k).remove(); return "true"; } } return ("false") }).then(function(res) { if(res == "true") { firebase.database().ref("users/"+userToEdit.userKey).remove(); alert("המשתמש הוסר בהצלחה"); editUser(); } }); } } var deleteUserInCH = function() { firebase.database().ref("users/"+userToEdit.userKey+"/clubhouseKey").once("value") .then(function(data) { if (data.val() == null) { alert("לא נמצאו מועדוניות להציג "); return; } var clubs = data.val(); //all clubhouses that the user is in there var clubsKeys = Object.keys(clubs); //all keys of clubhouses for(var i =0;i<clubsKeys.length;i++) removeUserFromClubOnly(clubs[i]); //delete user from clubhouse userslist return "true"; }).then(function(res) { if(res == "true") { firebase.database().ref("users/"+userToEdit.userKey).remove(); alert("המשתמש הוסר בהצלחה"); editUser(); } }); } var removeUserFromClubOnly = function(clubKey) { firebase.database().ref("clubhouse/"+clubKey+"/usersList").once("value") .then(function(data) { if (data.val() == null) { alert("לא נמצאה מועדונית "); return; } var users = data.val(); // get the whole tree of clubhouses var keys = Object.keys(users); // get all keys for(var i =0; i<keys.length;i++) { var key = users[keys[i]].userkey; var k = keys[i]; if(userToEdit.userKey == users[keys[i]].userkey) { firebase.database().ref("clubhouse/"+clubKey+"/usersList").child(k).remove(); } } }); } // listener for clubhouse Buttons for user edit var EditClubselectValue = function(e) { EditSectionClubName = e.target.innerText; if(e.target.innerText == "") { alert("לא נבחר משתמש"); return; } clubIndex_Edit = getClubKeyIndex(e.target.innerText.trim()); showUsersPerCH(e.target.innerText); } ///////////////////////////////////////////////////////////////////// // LOAD DATA // ///////////////////////////////////////////////////////////////////// // Updates clubhousesInfo array var loadClubhousesData = function() { var ref = firebase.database().ref("clubhouse"); ref.once("value") .then(function(data) // when value recieved { if (data.val() == null) { alert("לא נמצאו מועדוניות להציג"); return; } allClubhousesObjects = data.val(); var allClubhouses = data.val(); // get the whole tree of clubhouses var keys = Object.keys(allClubhouses); // get all keys for(var i =0; i<keys.length;i++) { var tempName = allClubhouses[keys[i]].name; clubhousesInfo[i] = {key:keys[i],name:tempName} if (page == EDITPAGE) { var tempBtnID = 'btn'+i; var btnInput = '<a href="#" id="'+tempBtnID+'" class="btn btn-sq-lg btn-primary clubSquare">'+ '<i class="fa fa-home fa-2x"></i><br/>'+tempName+'</a>'; $('#clubBottunGroup').append(btnInput); $('#'+tempBtnID).click(EditClubselectValue); mainPage.paintButton(i,tempBtnID); } if (page == ADDPAGE) $('#clubhouse_select_Add').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>'); } }); } ///////////////////////////////////////////////////////////////////// // GENERAL METHODS // ///////////////////////////////////////////////////////////////////// var getTypeAsString = function(type) { if(type == User.PARENT) return "הורה"; if(type == User.TEACHER) return "מורה"; if(type == User.GUIDE) return "מדריך"; if(type == User.SOCIAL) return 'עו"ס'; if(type == User.ADMIN) return "מנהל"; else return""; } var getClubKeyIndex = function(clubName) { for (var i = 0; i < clubhousesInfo.length; i++) { if(clubName.trim() == clubhousesInfo[i].name) return i; } return FAIL; } var getClubKeyByName = function (clubName) { for (var i = 0; i < clubhousesInfo.length; i++) { if(clubName.trim() == clubhousesInfo[i].name) return clubhousesInfo[i].key; } return ""; } return{addUser:addUser,editUser:editUser}; }();
app/public/js/Management/usersManagement.js
var usersManagement = function() { const FAIL = -1; const ADDPAGE = 1; const EDITPAGE = 2; const OS_TYPE = 3; var clubhousesInfo = []; // key and name var page; var addPrevType; var AddSectionClubName; var EditSectionClubName; var clubIndex_Edit; var userToEdit; //------------------------------------------------------------------------------------------------- var UserPage= { inputSection: '<div class="container">'+ '<div class="row main">'+ '<div class="panel-heading">'+ '<div class="panel-title text-center">'+ '<h2 id="allTitles" class="registerTitle">רישום משתמש</h2>'+ '</div>'+ '</div> '+ '<div class="main-login main-center">'+ '<form class="form-horizontal" method="post" action="#">'+ '<div class="form-group">'+ '<label for="name" class="col-sm-2 controlLabel" >:שם פרטי</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>'+ '<input type="text" class="form-control" name="name" id="UserPName" maxlength="20" placeholder="הכנס שם פרטי" dir="rtl" />'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="UserLastName" class="col-sm-2 controlLabel" id="formTxts">:שם משפחה</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>'+ '<input type="text" class="form-control" name="UserLastName" id="UserLName" maxlength="20" placeholder="הכנס שם משפחה" dir="rtl"/>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="username" class="col-sm-2 controlLabel">:שם משתמש</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>'+ '<input type="email" class="form-control" name="username" id="username" maxlength="20" placeholder="הכנס שם משתמש" dir="rtl"/>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="username" class="col-sm-2 controlLabel">:סוג משתמש</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-slideshare" aria-hidden="true"></i></span>'+ '<select type="text" class="form-control" id="userType">'+ '<option value = "0" class="ptUser">הורה</option>'+ '<option value = "1" class="tcUser">מורה</option>'+ '<option value = "2" class="GuUser">מדריך</option>'+ '<option value = "3" class="SWUser">עו"ס</option>'+ '<option value = "4" class="AdmUser">מנהל</option>'+ '</select>'+ '</div>'+ '</div>'+ '</div>'+ '<div id = "passwordSection">'+ '<div class="form-group">'+ '<label for="password" class="col-sm-2 controlLabel">:סיסמא</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>'+ '<input type="password" class="form-control" name="password" id="password" maxlength="10" placeholder="הכנס סיסמה"/>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group">'+ '<label for="confirm" class="col-sm-2 controlLabel">:אימות סיסמא</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>'+ '<input type="password" class="form-control" name="confirm" id="confirm" maxlength="10" placeholder="אמת בשנית סיסמה"/>'+ '</div>'+ '</div>'+ '</div>'+ '</div>'+ '<div id="selectCHSection" class="form-group">'+ '<label for="clubHouseName" class="col-sm-2 controlLabel">:בחר מועדונית</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-home" aria-hidden="true"></i></span>'+ '<select type="text" id="clubhouse_select_Add" class="form-control clubHouseName" placeholder="בחר מועדונית מתוך הרשימה">'+ '</select>'+ '</div>'+ '</div>'+ '</div>'+ '<div class="form-group" id="buttons_area">'+ '</div>'+ '</form>'+ '</div>'+ '</div>' } //------------------------------------------------------------------------------------------------- var EditUserOp={ inputSection: '<div class="container">'+ '<label id="allTitles">:בחר מועדונית</label>'+ '</br>'+ '<div class="row">'+ '<div id = "clubBottunGroup" class="col-md-4 text-center">'+ '</div>'+ '</div>'+ '</div>'+ '<br>'+ '<label id="allTitles2">:בחר משתמש</label>'+ '</br></br>'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-user" aria-hidden="true"></i></span>'+ '<select type="text" id="usersInCH" class="form-control" >'+ '</select>'+ '</div>'+ '</br>'+ '<div class="col-md-4 text-center">'+ '<button type="button" id="openUserEditBtn" class="btn btn-warning btn3d">לחץ כאן לערוך</button>'+ '</div>'+ '</div>' } //------------------------------------------------------------------------------------------------- var EditUserButtons= { inputSection: '</br>'+ '<button id ="change-button" type="button" class="btn btn-primary btn-block btn-lg edit-button" >עריכה</button>'+ '<button id ="delete-button" type="button" class="btn-danger btn-danger btn-block btn-lg delete-button" >מחיקת משתמש</button>' } //------------------------------------------------------------------------------------------------- var addUserButton= { inputSection: '</br>'+ '<button type="button" class="btn btn-primary btn-lg btn-block register-button" data-toggle="modal" data-target="#myModal" id="addUser" >הרשמה</button>' } //------------------------------------------------------------------------------------------------- var swMultiselect = { inputSection: '<ul id = "swMultiSelect" class="list-group">'+ '</ul>' } //------------------------------------------------------------------------------------------------- ///////////////////////////////////////////////////////////////////// // ADD USER // ///////////////////////////////////////////////////////////////////// var addUser=function() { page = ADDPAGE; clubhousesInfo = []; loadClubhousesData(); $('.Nav').collapse('hide'); $("#body").html(UserPage.inputSection); $('#buttons_area').html(addUserButton.inputSection); $("#addUser").click(createUser); addPrevType=0; $('#userType').on('change',updateType); } //------------------------------------------------------------------------------------------------- var createUser=function() { var firstName=document.getElementById("UserPName").value; var lastName=document.getElementById("UserLName").value; var username=document.getElementById("username").value; var fPassword=document.getElementById("password").value; var sPassword=document.getElementById("confirm").value; var Uclubhouse; if( sPassword!=fPassword && fPassword != "" )//&& fPassword < 4) { alert(" הסיסמאות שהוזנו אינן תואמות"); return; } var res = inputsValidation({firstName:firstName,lastName:lastName,username:username,password:sPassword}); if (!res) return; // selecting the clubhouse var e; e=document.getElementById("userType"); var type = e.selectedIndex; if(type >= 0 && type < User.SOCIAL ) { if (page == ADDPAGE) e = document.getElementById("clubhouse_select_Add"); if(e.selectedIndex == -1)// when there are no clubhouses at DB { alert("אנא הזן מועדוניות לפני יצירת משתמשים במערכת"); return; } Uclubhouse= e.options[e.selectedIndex].text; var clubKey = getClubKeyByName(Uclubhouse); checkAndPush(username,fPassword,firstName,lastName,type,clubKey); } else if (type == User.SOCIAL) { var clubhousesSw=[]; var childs = $('#swMultiSelect')[0].childNodes; for (var i = 0; i < childs.length; i++) { var element = childs[i]; if (element.className == 'list-group-item active') { var temp = getClubKeyByName(childs[i].textContent); clubhousesSw.push(temp); } } if (clubhousesSw.length <= 0) { alert("אנא הזן מועדוניות לפני יצירת משתמשים במערכת"); return; } checkAndPush(username,fPassword,firstName,lastName,type,clubhousesSw); } else if (type == User.ADMIN) { checkAndPush(username,fPassword,firstName,lastName,type,clubhousesSw); } } var inputsValidation = function(args) { var usernameRegex = /^\w+(\-+(\w)*)*$/; // var namesRegex = /^[[(א-ת)]+$/|/^[(a-zA-Z)]]+$/; var spacesRegex = /\s/; if (args.firstName == "" || args.lastName == "" || args.username == "") { alert("אנא מלא את כל השדות הנדרשים"); return false; } if(!usernameRegex.test(args.username)) { alert("יש לבחור שם משתמש המורכב ממספרים ואותיות בלבד"); return false; } if( spacesRegex.test(args.firstName) == true) { alert("שם פרטי שהוזן אינו חוקי"); return false; } if( spacesRegex.test(args.lastName) == true) { alert("שם משפחה שהוזן אינו חוקי"); return false; } if(args.password.length<4 || args.password.length>10) { alert("נא להזין סיסמא באורך בין 4-10 תווים"); return false; } return true; } var checkAndPush = function(username,fPassword,firstName,lastName,type,clubKey) { //check if the username exist - if not push to DB var ref = firebase.database().ref("users"); ref.once("value") .then(function(data) // when value recieved { // in case the root is empty -> name is not exist if (data.val() == null) return false; var allUsers = data.val(); // get the whole tree of users var keys = Object.keys(allUsers); // get all keys // loop on the answer array to find user name. var temp = false; for(var i =0; i<keys.length;i++) { var k = keys[i]; var tempName = allUsers[k].username; if( tempName == username ) temp = true; } return temp; }).then(function(res) { if(res) // name is already exist in DB { alert("שם משתמש כבר קיים"); return; } // else - push user to DB var usersRef = firebase.database().ref('users'); var newUser; if(type == User.ADMIN) { newUser = User.create(username,fPassword,firstName,lastName,type,null); var key = usersRef.push(newUser); firebase.database().ref('users/' + key.key + '/userKey').set(key.key); addUser(); } else if(type == User.SOCIAL) { newUser = User.create(username,fPassword,firstName,lastName,type,clubKey); var key = usersRef.push(newUser); firebase.database().ref('users/' + key.key + '/userKey').set(key.key); for (var i = 0; i < clubKey.length; i++) { firebase.database().ref('clubhouse/'+clubKey[i]+'/usersList') .push({userkey:key.key,username:username,type:type}); } addUser(); } else { newUser = User.create(username,fPassword,firstName,lastName,type,clubKey); var key = usersRef.push(newUser); firebase.database().ref('users/' + key.key + '/userKey').set(key.key); firebase.database().ref('clubhouse/'+clubKey+'/usersList') .push({userkey:key.key,username:username,type:type}); addUser(); } alert("הוזן בהצלחה"); }); } ///////////////////////////////////////////////////////////////// // addPrevType holds the last value on selectbox var updateType = function(e) { var type = e.target.value; var input; if(addPrevType !=type && type == User.ADMIN) { // inject for admin $('#selectCHSection').html(""); } else if(addPrevType !=type && type == User.SOCIAL) { // inject for social worker input = swMultiselect.inputSection; $('#selectCHSection').html(input); for (var i = 0; i < clubhousesInfo.length; i++) { var id='swClubhouseSelect'+i; var line = '<li id="'+id+'" class="list-group-item">'+clubhousesInfo[i].name+'</li>' $('#swMultiSelect').append(line) $('#'+id).click(SwClubListener); } } else { // inject for regualar users , guide parent teacer input ='<label for="clubHouseName" class="col-sm-2 controlLabel">:בחר מועדונית</label>'+ '<div class="col-sm-10">'+ '<div class="input-group">'+ '<span class="input-group-addon"><i class="fa fa-home" aria-hidden="true"></i></span>'+ '<select type="text" id="clubhouse_select_Add" class="form-control clubHouseName" placeholder="בחר מועדונית מתוך הרשימה">'+ '</select>'+ '</div>'+ '</div>'; $('#selectCHSection').html(input); for(var i =0; i<clubhousesInfo.length;i++) $('#clubhouse_select_Add').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>'); } addPrevType = type; } var addClubSelectValue = function() { var index = document.getElementById("clubhouse_select_Add").value; if (index > clubhousesInfo.length) return; if(AddSectionClubName == clubhousesInfo[index].name) return; AddSectionClubName = clubhousesInfo[index].name; return AddSectionClubName; } // sw multiselect listener var SwClubListener = function(e) { var targetClass = e.currentTarget.className; if(targetClass == 'list-group-item') e.currentTarget.className = 'list-group-item active'; if(targetClass == 'list-group-item active') e.currentTarget.className = 'list-group-item'; } ///////////////////////////////////////////////////////////////////// // EDIT USER // ///////////////////////////////////////////////////////////////////// // Edit user function var editUser=function() { page = EDITPAGE; $("#body").html(EditUserOp.inputSection); $('.Nav').collapse('hide'); clubhousesInfo = []; loadClubhousesData(); // attach listeners after loading clubhouses $('#openUserEditBtn').click(editUserListener); } //====================================================================================== // show user list from a selected clubhouse var showUsersPerCH = function(clubhouseSelected) { document.getElementById('usersInCH').innerHTML = ""; var tmpIndex = getClubKeyIndex(clubhouseSelected); if(tmpIndex == FAIL) { alert("לא נמצאה מועדונית "); return; } var ClubKey = clubhousesInfo[tmpIndex].key; var ref = firebase.database().ref("clubhouse/"+ClubKey+"/usersList"); ref.once("value") .then(function(data) // when value recieved { if (data.val() == null) { alert("לא נמצאו משתמשים להציג "); return; } var users = data.val(); // get the whole tree of clubhouses var keys = Object.keys(users); // get all keys for(var i =0; i<keys.length;i++) { var k = keys[i]; var uKey=users[k].userkey; var userRef= firebase.database().ref("users/"+uKey); userRef.ref.once("value").then(function(data) { var user=data.val(); $('#usersInCH').append('<option value="'+user.userKey+'">'+user.firstName+' '+user.lastName+'</option>'); }); } }); } var editUserListener= function() { var e = document.getElementById("usersInCH"); if(e.selectedIndex<0) { alert('לא נבחר שם משתמש'); return; } var userKey = e.options[e.selectedIndex].value; var user = loadUserDetails(userKey); }; // load user data when selected var loadUserDetails = function(userKey) { if(!userKey) { alert('key Error: '+userKey); return; } // get the user object firebase.database().ref("users/"+userKey).once("value") .then(function(data) { var user = data.val(); if(user) { userToEdit = user; injectEditPage(user); } }); } var injectEditPage = function (user) { $('#body').html(UserPage.inputSection); document.getElementById('allTitles').innerHTML ="עריכת/מחיקת משתמש"; $('#UserPName').val(user.firstName); $('#UserLName').val(user.lastName); $('#username').val(user.username); $('#userType').val(user.userType); document.getElementById("userType").disabled = true; //disable option for changing user-type $('#passwordSection').html(""); // prevent change the password if there is oath with email /*$('#password').val(user.password); $('#confirm').val(user.password);*/ // html inject for each user type// //===============================// if(user.userType == User.ADMIN) { $('#selectCHSection').html(""); } // multi select injection for SW if ( user.userType == User.SOCIAL) { $('#selectCHSection').html(swMultiselect.inputSection) } // if( user.userType == User.SOCIAL) if(user.userType >= User.PARENT && user.userType < User.SOCIAL) { // append element to select and choose the selected index on default. var tempIndex; for(var i =0; i<clubhousesInfo.length;i++) { if (clubhousesInfo[i].key == user.clubhouseKey) tempIndex = i; $('#clubhouse_select_Add').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>'); } $('#clubhouse_select_Add').val(tempIndex); $('#clubhouse_select_Add').on('change',function(e) // update selected index listener { clubIndex_Edit = e.currentTarget.selectedIndex; }); } $('#buttons_area').html(EditUserButtons.inputSection); $('#change-button').click(changeUserInfo); $('#delete-button').click(function(){ deleteUser(user.userType) }); } var changeUserInfo = function() { var obj={}; var firstName = $('#UserPName').val(); var lastName = $('#UserLName').val(); var Nusername = $('#username').val(); var password = $('#password').val(); var confirm = $('#confirm').val(); if( userToEdit.userType >= User.PARENT && userToEdit.userType < User.SOCIAL) { // currClubIndex= $('#clubhouse_select_Add').val(); console.log(clubhousesInfo[clubIndex_Edit]); currClubKey = clubhousesInfo[clubIndex_Edit].key; if(userToEdit.clubhouseKey != currClubKey) // clubhouse changed { // update new clubhouse firebase.database().ref('clubhouse/'+currClubKey+'/usersList') .push({userkey:userToEdit.userKey,username:Nusername,type:userType}); // remove from old clubhouse removeUserFromClubOnly(userToEdit.clubhouseKey); obj.clubhouseKey = currClubKey; // update user object } } /*if (password != confirm) { alert('הסיסמאות אינן תואמות'); return; if (userToEdit.password != password) obj.password = password; }*/ if (userToEdit.firstName != firstName) obj.firstName = firstName; if (userToEdit.lastName != lastName) obj.lastName = lastName; if (userToEdit.username != Nusername) obj.username = Nusername; var e = document.getElementById("clubhouse_select_Add"); var userRef = firebase.database().ref('users/'); userRef.child(userToEdit.userKey).update(obj); alert("המידע עודכן בהצלחה"); editUser(); } var deleteUser = function(uType) { if(uType == OS_TYPE) //if the user is Social worker - then it delete him from several clubhouses deleteUserInCH(); else { var clubKey = clubhousesInfo[clubIndex_Edit].key; firebase.database().ref("clubhouse/"+clubKey+"/usersList").once("value") .then(function(data) { if (data.val() == null) { alert("לא נמצאו משתמשים להציג "); return; } var users = data.val(); // get the whole tree of clubhouses var keys = Object.keys(users); // get all keys for(var i =0; i<keys.length;i++) { var key = users[keys[i]].userkey; var k = keys[i]; if(userToEdit.userKey == users[keys[i]].userkey) { firebase.database().ref("clubhouse/"+clubKey+"/usersList").child(k).remove(); return "true"; } } return ("false") }).then(function(res) { if(res == "true") { firebase.database().ref("users/"+userToEdit.userKey).remove(); alert("המשתמש הוסר בהצלחה"); editUser(); } }); } } var deleteUserInCH = function() { firebase.database().ref("users/"+userToEdit.userKey+"/clubhouseKey").once("value") .then(function(data) { if (data.val() == null) { alert("לא נמצאו מועדוניות להציג "); return; } var clubs = data.val(); //all clubhouses that the user is in there var clubsKeys = Object.keys(clubs); //all keys of clubhouses for(var i =0;i<clubsKeys.length;i++) removeUserFromClubOnly(clubs[i]); //delete user from clubhouse userslist return "true"; }).then(function(res) { if(res == "true") { firebase.database().ref("users/"+userToEdit.userKey).remove(); alert("המשתמש הוסר בהצלחה"); editUser(); } }); } var removeUserFromClubOnly = function(clubKey) { firebase.database().ref("clubhouse/"+clubKey+"/usersList").once("value") .then(function(data) { if (data.val() == null) { alert("לא נמצאה מועדונית "); return; } var users = data.val(); // get the whole tree of clubhouses var keys = Object.keys(users); // get all keys for(var i =0; i<keys.length;i++) { var key = users[keys[i]].userkey; var k = keys[i]; if(userToEdit.userKey == users[keys[i]].userkey) { firebase.database().ref("clubhouse/"+clubKey+"/usersList").child(k).remove(); } } }); } // listener for clubhouse Buttons for user edit var EditClubselectValue = function(e) { EditSectionClubName = e.target.innerText; if(e.target.innerText == "") { alert("לא נבחר משתמש"); return; } clubIndex_Edit = getClubKeyIndex(e.target.innerText.trim()); showUsersPerCH(e.target.innerText); } ///////////////////////////////////////////////////////////////////// // LOAD DATA // ///////////////////////////////////////////////////////////////////// // Updates clubhousesInfo array var loadClubhousesData = function() { var ref = firebase.database().ref("clubhouse"); ref.once("value") .then(function(data) // when value recieved { if (data.val() == null) { alert("לא נמצאו מועדוניות להציג"); return; } allClubhousesObjects = data.val(); var allClubhouses = data.val(); // get the whole tree of clubhouses var keys = Object.keys(allClubhouses); // get all keys for(var i =0; i<keys.length;i++) { var tempName = allClubhouses[keys[i]].name; clubhousesInfo[i] = {key:keys[i],name:tempName} if (page == EDITPAGE) { var tempBtnID = 'btn'+i; var btnInput = '<a href="#" id="'+tempBtnID+'" class="btn btn-sq-lg btn-primary clubSquare">'+ '<i class="fa fa-home fa-2x"></i><br/>'+tempName+'</a>'; $('#clubBottunGroup').append(btnInput); $('#'+tempBtnID).click(EditClubselectValue); mainPage.paintButton(i,tempBtnID); } if (page == ADDPAGE) $('#clubhouse_select_Add').append('<option value="'+i+'">'+clubhousesInfo[i].name+'</option>'); } }); } ///////////////////////////////////////////////////////////////////// // GENERAL METHODS // ///////////////////////////////////////////////////////////////////// var getTypeAsString = function(type) { if(type == User.PARENT) return "הורה"; if(type == User.TEACHER) return "מורה"; if(type == User.GUIDE) return "מדריך"; if(type == User.SOCIAL) return 'עו"ס'; if(type == User.ADMIN) return "מנהל"; else return""; } var getClubKeyIndex = function(clubName) { for (var i = 0; i < clubhousesInfo.length; i++) { if(clubName.trim() == clubhousesInfo[i].name) return i; } return FAIL; } var getClubKeyByName = function (clubName) { for (var i = 0; i < clubhousesInfo.length; i++) { if(clubName.trim() == clubhousesInfo[i].name) return clubhousesInfo[i].key; } return ""; } return{addUser:addUser,editUser:editUser}; }();
social worker edit update - remain small bug after push
app/public/js/Management/usersManagement.js
social worker edit update - remain small bug after push
<ide><path>pp/public/js/Management/usersManagement.js <ide> var AddSectionClubName; <ide> var EditSectionClubName; <ide> var clubIndex_Edit; <add> var socialPrevCH_edit=[]; <ide> var userToEdit; <ide> //------------------------------------------------------------------------------------------------- <ide> var UserPage= <ide> // multi select injection for SW <ide> if ( user.userType == User.SOCIAL) <ide> { <del> $('#selectCHSection').html(swMultiselect.inputSection) <del> <del> } <del> <del> // if( user.userType == User.SOCIAL) <add> socialPrevCH_edit=[]; // keep the indexes of the old clubhouses the social had <add> $('#selectCHSection').html(swMultiselect.inputSection); <add> for (var i = 0; i < clubhousesInfo.length; i++) { <add> var id='swClubhouseSelect'+i; <add> var line = '<li id="'+id+'" class="list-group-item">'+clubhousesInfo[i].name+'</li>' <add> for (var j = 0; j < userToEdit.clubhouseKey.length; j++) { // to retrive the slected clubhouses <add> if(userToEdit.clubhouseKey[j] == clubhousesInfo[i].key) <add> { <add> line = '<li id="'+id+'" class="list-group-item active">'+clubhousesInfo[i].name+'</li>'; <add> socialPrevCH_edit.push(i); <add> } <add> } <add> <add> $('#swMultiSelect').append(line); <add> $('#'+id).click(SwClubListener); <add> } <add> <add> } <add> <ide> if(user.userType >= User.PARENT && user.userType < User.SOCIAL) <ide> { <ide> // append element to select and choose the selected index on default. <ide> var password = $('#password').val(); <ide> var confirm = $('#confirm').val(); <ide> <add> if (userToEdit.firstName != firstName) <add> obj.firstName = firstName; <add> if (userToEdit.lastName != lastName) <add> obj.lastName = lastName; <add> if (userToEdit.username != Nusername) <add> obj.username = Nusername; <ide> <ide> if( userToEdit.userType >= User.PARENT && userToEdit.userType < User.SOCIAL) <ide> { <ide> // currClubIndex= $('#clubhouse_select_Add').val(); <del> console.log(clubhousesInfo[clubIndex_Edit]); <ide> currClubKey = clubhousesInfo[clubIndex_Edit].key; <ide> if(userToEdit.clubhouseKey != currClubKey) // clubhouse changed <ide> { <ide> obj.clubhouseKey = currClubKey; // update user object <ide> } <ide> } <add> if ( userToEdit.userType == User.SOCIAL) <add> { <add> // get curr indexes <add> var currIndexes=[]; <add> var childs = $('#swMultiSelect')[0].childNodes; <add> for (var i = 0; i < childs.length; i++) <add> { <add> var element = childs[i]; <add> if (element.className == 'list-group-item active') <add> { <add> currIndexes.push(i); <add> } <add> } <add> if(currIndexes.length<=0) <add> { <add> alert('אנא הזן מועדוניות '); <add> return; <add> } <add> //......................................... <add> // compare selection with previous values <add> <add> var max = Math.max(socialPrevCH_edit.length, currIndexes.length); <add> console.log(socialPrevCH_edit); <add> console.log(currIndexes); <add> var keyRM; <add> var keyADD; <add> for (var i = 0 ; i < max ; i++) <add> { <add> if(socialPrevCH_edit[i]==currIndexes[i]) <add> continue; <add> <add> // indexes are not equal - remove from old clubhouse <add> if(i < socialPrevCH_edit.length) <add> { <add> keyRM = clubhousesInfo[socialPrevCH_edit[i]].key; <add> removeUserFromClubOnly(keyRM); <add> } <add> // push new Clubhouse <add> if (i < currIndexes.length ) <add> { <add> keyADD = clubhousesInfo[currIndexes[i]].key; <add> firebase.database().ref('clubhouse/'+keyADD+'/userList').push({userkey:userToEdit.userKey,username:Nusername,type:userType}); <add> } <add> <add> } <add> <add> // if equal <add> var tempCHARr=[]; <add> for(var i = 0 ; i <currIndexes.length ; i++) <add> tempCHARr.push(clubhousesInfo[currIndexes[i]].key); <add> obj.clubhouseKey = tempCHARr; <add> } <ide> <ide> <ide> /*if (password != confirm) <ide> if (userToEdit.password != password) <ide> obj.password = password; <ide> }*/ <del> if (userToEdit.firstName != firstName) <del> obj.firstName = firstName; <del> if (userToEdit.lastName != lastName) <del> obj.lastName = lastName; <del> if (userToEdit.username != Nusername) <del> obj.username = Nusername; <del> <del> <del> <del> var e = document.getElementById("clubhouse_select_Add"); <add> <add> <add> <add> // var e = document.getElementById("clubhouse_select_Add"); <ide> var userRef = firebase.database().ref('users/'); <ide> userRef.child(userToEdit.userKey).update(obj); <ide> alert("המידע עודכן בהצלחה");
JavaScript
isc
2d5c0320909d611be407ea5205c41481d425d6a3
0
qubz/qubz.github.io
// Constants var w = 600; var h = 600; var padding = 60; var radius = 15; // Global vars var data = []; // the datajoin object for d3 var tags; // Tag wieghts for sliders var users; // user data (index corresponds to that of points.json) var points; // points (index corresponds to the users from user_data.json) // For bug where text labels are only half their supposed x value // See http://stackoverflow.com/questions/7000190/detect-all-firefox-versions-in-js // for this solution. var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; // Load each style sheet var doc = document; // shortcut // Pull in the main css file var cssId = 'widgetCss'; if (!doc.getElementById(cssId)) { var head = doc.getElementsByTagName('head')[0]; var link = doc.createElement('link'); link.id = cssId; link.rel = 'stylesheet'; link.type = 'text/css'; // link.href = 'https://raw.github.com/qubz/YourView-Political-Alignment-Visualisation/master/styles/widget.css'; link.href = 'styles/widget.css'; link.media = 'all'; head.appendChild(link); } // Grab the theme css file var cssId = 'themeCss'; if (!doc.getElementById(cssId)) { var head = doc.getElementsByTagName('head')[0]; var link = doc.createElement('link'); link.id = cssId; link.rel = 'stylesheet'; link.type = 'text/css'; // link.href = 'https://raw.github.com/qubz/YourView-Political-Alignment-Visualisation/master/styles/absolution.css'; link.href = 'styles/absolution.css'; link.media = 'all'; head.appendChild(link); } // Load jQuery.js using only JS var jQueryUrl = '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js'; var jQueryUiUrl = '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js'; var d3Url = 'http://d3js.org/d3.v2.js'; function loadScript(url, callback) { // adding the script tag to the head as suggested before var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // then bind the event to the callback function // there are several events for cross browser compatibility script.onreadystatechange = callback; script.onload = callback; // fire the loading head.appendChild(script); } var jQueryLoadedCallback = function() { loadScript(jQueryUiUrl, jQueryUILoadedCallback); }; var jQueryUILoadedCallback = function() { loadScript(d3Url, d3LoadedCallback); }; var d3LoadedCallback = function() { // Everything is loaded, ready to run the rest of the code $(document).ready(function() { // jQuery stuff to build DOM from this script var widget = document.getElementById("yourview-visualization"); var map = $("<div id='map'></div>"); var controls = $("<div id='controls'></div>"); map.appendTo(widget); controls.appendTo(widget); // Initiealise the controls; the tabs. function initControls() { var tabs = $("<div id='tabs' class='container'></div>"); tabs.appendTo(controls); var ul = $("<ul></ul>"); ul.appendTo(tabs); var li = $("<li></li>"); li.appendTo(ul); var tab1Title = $("<a href='#tabs-1'>Areas</a>"); tab1Title.appendTo(li); var li = $("<li></li>"); li.appendTo(ul); var tab2Title = $("<a href='#tabs-2'>Entities</a>"); tab2Title.appendTo(li); var tab1 = $("<div id='tabs-1' class='panel'></div>"); tab1.appendTo(tabs); // Decribe the function of the tag weights to the user var sliderHeaderTitle = $("<p id='slider-header-title' ><--- Less --- IMPORTANT --- More ---></p>"); sliderHeaderTitle.appendTo(tab1); // Add each slider from tags and set its callback function // TODO: - A POST request with all tags sent to the server for fresh points var sliders = []; for (var i = 0; i < tags.length; i++) { sliders.push($("<p>" + tags[i].name + "</p><div id='slider" + i + "'></div>")); sliders[i].appendTo(tab1); $("#slider" + i).slider({ value: tags[i].weight, min: 0, max: 1, step: 0.2 }).on("slidestop", function(event, ui) { update(); }); } var tab2 = $("<div id='tabs-2' class='panel'></div>"); tab2.appendTo(tabs); var table = $("<table></table>"); table.appendTo(tab2); // Add each button from users and set its callback function // TODO: - This could probably be simplified // - Checked/clicked state (using Checkbox button?) // - Tranlate to links? var entities = []; for (var i = 0; i < users.length; i++) { var tr = $("<tr></tr>"); tr.appendTo(table); var td = $("<td></td>"); td.appendTo(tr); entities.push($("<button id='" + users[i].id + "' class='button'>" + users[i].username + "</button>").addClass("button_clicked")); entities[i].appendTo(td); $("#" + users[i].id).click(function() { var id = $(this).attr('id'); for (var j = 0; j < users.length; j++) { if (users[j].id == id) { users[j].primary = !users[j].primary; if (users[j].primary) $(this).addClass("button_clicked"); else $(this).removeClass("button_clicked"); toggleEnitiy(); } } }); } $(function() { $("#tabs").tabs(); }); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~d3 stuff~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var svg = d3.select("#map") .append("svg") .attr("width", w) .attr("height", h); // Retrieve user data from user_data.json // d3.json("http://staging.yourview.org.au/visualization/user_data.json?forum=1", function(json) { d3.json("json/user_data.json", function(json) { users = json.users; tags = json.tags; initControls(); initPlot(); }); function initPlot() { // d3.json("http://staging.yourview.org.au/visualization/points.json?forum=1", function(json) { d3.json("json/points.json", function(json) { points = scale(json); data = createData(); draw(); }); } function scale(points) { var xs = []; var ys = []; for (var i = 0; i < points.length; i++) { xs.push(points[i][0]); ys.push(points[i][1]); } var xMin = d3.min(xs); var xMax = d3.max(xs); var yMin = d3.min(ys); var yMax = d3.max(ys); if (xMin < yMin) var min = xMin; else var min = yMin; if (xMax > yMax) var max = xMax; else var max = yMax; var linearScale = d3.scale.linear() .domain([min, max]) .range([0 + padding, w - padding]); var scaledPoints = [] for (var i = 0; i < points.length; i++) { xs[i] = linearScale(xs[i]); ys[i] = linearScale(ys[i]); scaledPoints.push([xs[i], ys[i]]); } return scaledPoints; } function createData() { var dataset = []; // Merge users with points into an object for (var i = 0; i < users.length; i++) { dataset.push({ x: points[i][0], y: points[i][1], colour: users[i].colour, cred: users[i].cred, id: users[i].id, link: users[i].link, primary: users[i].primary, username: users[i].username }); } return dataset; } var previousIndex; function chooseRandDummyFile() { var array = []; path1 = "json/dummy_points1.json"; path2 = "json/dummy_points2.json"; path3 = "json/dummy_points3.json"; path4 = "json/dummy_points4.json"; path5 = "json/dummy_points5.json"; array.push(path1); array.push(path2); array.push(path3); array.push(path4); array.push(path5); // Make sure we choose an index different to the last one. while (true) { index = Math.floor((Math.random() * 5) + 1); if (previousIndex != index) break; } previousIndex = index; console.log(array[index - 1]); return array[index - 1]; } function sortPrimaryZBelow(a, b) { if (a.primary && !b.primary) return -1; else if (!a.primary && b.primary) return 1; else return 0; } function draw() { var g = svg.selectAll("g") .data(data) .enter() .append("g") .on("mouseover", function(d) { var sel = d3.select(this); sel.moveToFront(); console.log(d.username); }); g.append("circle") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .style("opacity", function(d) { return 0.8; }) .style("stroke", function(d) { return "dark" + d.colour; }) .style("stroke-width", 2) .style("fill", function(d) { return d.colour; }) .transition() .duration(700) .attr("r", function(d) { return radius; }); g.append("text") .attr("dx", function(d) { if (is_firefox) return d.x * 2; return d.x; }) .attr("dy", function(d) { return d.y + 35; }) .attr("font-family", "sans-serif") .attr("font-size", "13px") .style("text-anchor", "middle") .text(function(d) { return d.username; }); g.append("svg:title") .text(function(d) { return d.username; }); } function update() { d3.json(chooseRandDummyFile(), function(json) { points = scale(json); // update datapoints data = createData(); svg.selectAll("g") .data(data) .on("mouseover", function(d) { var sel = d3.select(this); sel.moveToFront(); console.log(d.username); }); // enter() and append() are omitted for a transision() svg.selectAll("circle") .data(data) .transition() .duration(1100) .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", function(d, i) { if (users[i].primary) return radius; else return radius - 5; }) .style("stroke", function(d, i) { if (users[i].primary) return "dark" + d.colour; else return "dimgray"; }) .style("stroke-width", 2) .style("fill", function(d, i) { if (users[i].primary) return d.colour; else return "dimgray"; }) svg.selectAll("text") .data(data) .transition() .duration(1100) .attr("dx", function(d) { if (is_firefox) return d.x * 2; return d.x; }) .attr("dy", function(d) { return d.y + 35; }) .attr("font-family", "sans-serif") .attr("font-size", "13px") .style("text-anchor", "middle") .text(function(d) { return d.username; }); }); } function toggleEnitiy() { // svg.selectAll('g') // .style("opacity", function(d, i) { // if (!visibility[i].isVisible) return 0.0; // else return 0.8; // }); svg.selectAll('text') .transition() .style("opacity", function(d, i) { if (users[i].primary) return 1.0; else return 0.0; }); svg.selectAll('circle') .transition() .duration(500) .attr("r", function(d, i) { if (users[i].primary) return radius; else return radius - 5; }) .style("stroke", function(d, i) { if (users[i].primary) return "dark" + d.colour; else return "dimgray"; }) .style("stroke-width", 2) .style("fill", function(d, i) { if (users[i].primary) return d.colour; return "dimgray"; }); svg.selectAll("g") .on("mouseover", function(d) { var sel = d3.select(this); sel.moveToFront(); console.log(d.username); }); } d3.selection.prototype.moveToFront = function() { return this.each(function() { this.parentNode.appendChild(this); }); }; }); }; loadScript(jQueryUrl, jQueryLoadedCallback);
scripts/visualisation_io.js
// Constants var w = 600; var h = 600; var padding = 60; var radius = 15; // Global vars var data = []; // the datajoin object for d3 var tags; // Tag wieghts for sliders var users; // user data (index corresponds to that of points.json) var points; // points (index corresponds to the users from user_data.json) // For bug where text labels are only half their supposed x value // See http://stackoverflow.com/questions/7000190/detect-all-firefox-versions-in-js // for this solution. var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; // Load each style sheet var doc = document; // shortcut // Pull in the main css file var cssId = 'widgetCss'; if (!doc.getElementById(cssId)) { var head = doc.getElementsByTagName('head')[0]; var link = doc.createElement('link'); link.id = cssId; link.rel = 'stylesheet'; link.type = 'text/css'; // link.href = 'https://raw.github.com/qubz/YourView-Political-Alignment-Visualisation/master/styles/widget.css'; link.href = 'styles/widget.css'; link.media = 'all'; head.appendChild(link); } // Grab the theme css file var cssId = 'themeCss'; if (!doc.getElementById(cssId)) { var head = doc.getElementsByTagName('head')[0]; var link = doc.createElement('link'); link.id = cssId; link.rel = 'stylesheet'; link.type = 'text/css'; // link.href = 'https://raw.github.com/qubz/YourView-Political-Alignment-Visualisation/master/styles/absolution.css'; link.href = 'styles/absolution.css'; link.media = 'all'; head.appendChild(link); } // Load jQuery.js using only JS var jQueryUrl = '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js'; var jQueryUiUrl = '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js'; var d3Url = 'http://d3js.org/d3.v2.js'; function loadScript(url, callback) { // adding the script tag to the head as suggested before var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // then bind the event to the callback function // there are several events for cross browser compatibility script.onreadystatechange = callback; script.onload = callback; // fire the loading head.appendChild(script); } var jQueryLoadedCallback = function() { loadScript(jQueryUiUrl, jQueryUILoadedCallback); }; var jQueryUILoadedCallback = function() { loadScript(d3Url, d3LoadedCallback); }; var d3LoadedCallback = function() { // Everything is loaded, ready to run the rest of the code $(document).ready(function() { // jQuery stuff to build DOM from this script var widget = document.getElementById("yourview-visualization"); var map = $("<div id='map'></div>"); var controls = $("<div id='controls'></div>"); map.appendTo(widget); controls.appendTo(widget); // Initiealise the controls; the tabs. function initControls() { var tabs = $("<div id='tabs' class='container'></div>"); tabs.appendTo(controls); var ul = $("<ul></ul>"); ul.appendTo(tabs); var li = $("<li></li>"); li.appendTo(ul); var tab1Title = $("<a href='#tabs-1'>Areas</a>"); tab1Title.appendTo(li); var li = $("<li></li>"); li.appendTo(ul); var tab2Title = $("<a href='#tabs-2'>Entities</a>"); tab2Title.appendTo(li); var tab1 = $("<div id='tabs-1' class='panel'></div>"); tab1.appendTo(tabs); // Decribe the function of the tag weights to the user var sliderHeaderTitle = $("<p id='slider-header-title' ><--- Less --- IMPORTANT --- More ---></p>"); sliderHeaderTitle.appendTo(tab1); // Add each slider from tags and set its callback function // TODO: - A POST request with all tags sent to the server for fresh points var sliders = []; for (var i = 0; i < tags.length; i++) { sliders.push($("<p>" + tags[i].name + "</p><div id='slider" + i + "'></div>")); sliders[i].appendTo(tab1); $("#slider" + i).slider({ value: tags[i].weight, min: 0, max: 1, step: 0.2 }).on("slidestop", function(event, ui) { update(); }); } var tab2 = $("<div id='tabs-2' class='panel'></div>"); tab2.appendTo(tabs); var table = $("<table></table>"); table.appendTo(tab2); // Add each button from users and set its callback function // TODO: - This could probably be simplified // - Checked/clicked state (using Checkbox button?) // - Tranlate to links? var entities = []; for (var i = 0; i < users.length; i++) { var tr = $("<tr></tr>"); tr.appendTo(table); var td = $("<td></td>"); td.appendTo(tr); entities.push($("<button id='" + users[i].id + "' class='button'>" + users[i].username + "</button>").addClass("button_clicked")); entities[i].appendTo(td); $("#" + users[i].id).click(function() { var id = $(this).attr('id'); for (var j = 0; j < users.length; j++) { if (users[j].id == id) { users[j].primary = !users[j].primary; if (users[j].primary) $(this).addClass("button_clicked"); else $(this).removeClass("button_clicked"); toggleEnitiy(); } } }); } $(function() { $("#tabs").tabs(); }); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~d3 stuff~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var svg = d3.select("#plot") .append("svg") .attr("width", w) .attr("height", h); // Retrieve user data from user_data.json // d3.json("http://staging.yourview.org.au/visualization/user_data.json?forum=1", function(json) { d3.json("json/user_data.json", function(json) { users = json.users; tags = json.tags; initControls(); initPlot(); }); function initPlot() { // d3.json("http://staging.yourview.org.au/visualization/points.json?forum=1", function(json) { d3.json("json/points.json", function(json) { points = scale(json); data = createData(); draw(); }); } function scale(points) { var xs = []; var ys = []; for (var i = 0; i < points.length; i++) { xs.push(points[i][0]); ys.push(points[i][1]); } var xMin = d3.min(xs); var xMax = d3.max(xs); var yMin = d3.min(ys); var yMax = d3.max(ys); if (xMin < yMin) var min = xMin; else var min = yMin; if (xMax > yMax) var max = xMax; else var max = yMax; var linearScale = d3.scale.linear() .domain([min, max]) .range([0 + padding, w - padding]); var scaledPoints = [] for (var i = 0; i < points.length; i++) { xs[i] = linearScale(xs[i]); ys[i] = linearScale(ys[i]); scaledPoints.push([xs[i], ys[i]]); } return scaledPoints; } function createData() { var dataset = []; // Merge users with points into an object for (var i = 0; i < users.length; i++) { dataset.push({ x: points[i][0], y: points[i][1], colour: users[i].colour, cred: users[i].cred, id: users[i].id, link: users[i].link, primary: users[i].primary, username: users[i].username }); } return dataset; } var previousIndex; function chooseRandDummyFile() { var array = []; path1 = "json/dummy_points1.json"; path2 = "json/dummy_points2.json"; path3 = "json/dummy_points3.json"; path4 = "json/dummy_points4.json"; path5 = "json/dummy_points5.json"; array.push(path1); array.push(path2); array.push(path3); array.push(path4); array.push(path5); // Make sure we choose an index different to the last one. while (true) { index = Math.floor((Math.random() * 5) + 1); if (previousIndex != index) break; } previousIndex = index; console.log(array[index - 1]); return array[index - 1]; } function sortPrimaryZBelow(a, b) { if (a.primary && !b.primary) return -1; else if (!a.primary && b.primary) return 1; else return 0; } function draw() { var g = svg.selectAll("g") .data(data) .enter() .append("g") .on("mouseover", function(d) { var sel = d3.select(this); sel.moveToFront(); console.log(d.username); }); g.append("circle") .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .style("opacity", function(d) { return 0.8; }) .style("stroke", function(d) { return "dark" + d.colour; }) .style("stroke-width", 2) .style("fill", function(d) { return d.colour; }) .transition() .duration(700) .attr("r", function(d) { return radius; }); g.append("text") .attr("dx", function(d) { if (is_firefox) return d.x * 2; return d.x; }) .attr("dy", function(d) { return d.y + 35; }) .attr("font-family", "sans-serif") .attr("font-size", "13px") .style("text-anchor", "middle") .text(function(d) { return d.username; }); g.append("svg:title") .text(function(d) { return d.username; }); } function update() { d3.json(chooseRandDummyFile(), function(json) { points = scale(json); // update datapoints data = createData(); svg.selectAll("g") .data(data) .on("mouseover", function(d) { var sel = d3.select(this); sel.moveToFront(); console.log(d.username); }); // enter() and append() are omitted for a transision() svg.selectAll("circle") .data(data) .transition() .duration(1100) .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }) .attr("r", function(d, i) { if (users[i].primary) return radius; else return radius - 5; }) .style("stroke", function(d, i) { if (users[i].primary) return "dark" + d.colour; else return "dimgray"; }) .style("stroke-width", 2) .style("fill", function(d, i) { if (users[i].primary) return d.colour; else return "dimgray"; }) svg.selectAll("text") .data(data) .transition() .duration(1100) .attr("dx", function(d) { if (is_firefox) return d.x * 2; return d.x; }) .attr("dy", function(d) { return d.y + 35; }) .attr("font-family", "sans-serif") .attr("font-size", "13px") .style("text-anchor", "middle") .text(function(d) { return d.username; }); }); } function toggleEnitiy() { // svg.selectAll('g') // .style("opacity", function(d, i) { // if (!visibility[i].isVisible) return 0.0; // else return 0.8; // }); svg.selectAll('text') .transition() .style("opacity", function(d, i) { if (users[i].primary) return 1.0; else return 0.0; }); svg.selectAll('circle') .transition() .duration(500) .attr("r", function(d, i) { if (users[i].primary) return radius; else return radius - 5; }) .style("stroke", function(d, i) { if (users[i].primary) return "dark" + d.colour; else return "dimgray"; }) .style("stroke-width", 2) .style("fill", function(d, i) { if (users[i].primary) return d.colour; return "dimgray"; }); svg.selectAll("g") .on("mouseover", function(d) { var sel = d3.select(this); sel.moveToFront(); console.log(d.username); }); } d3.selection.prototype.moveToFront = function() { return this.each(function() { this.parentNode.appendChild(this); }); }; }); }; loadScript(jQueryUrl, jQueryLoadedCallback);
Updated io script to new CSS
scripts/visualisation_io.js
Updated io script to new CSS
<ide><path>cripts/visualisation_io.js <ide> <ide> // ~~~~~~~~~~~~~~~~~~~~~~~~~~d3 stuff~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <ide> <del> var svg = d3.select("#plot") <add> var svg = d3.select("#map") <ide> .append("svg") <ide> .attr("width", w) <ide> .attr("height", h);
Java
apache-2.0
e54c4ca6e911418051d19f6100296e9a8bdb5f63
0
blademainer/intellij-community,allotria/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ernestp/consulo,petteyg/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,semonte/intellij-community,kool79/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,apixandru/intellij-community,holmes/intellij-community,apixandru/intellij-community,FHannes/intellij-community,kool79/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,da1z/intellij-community,youdonghai/intellij-community,izonder/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,slisson/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,asedunov/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,caot/intellij-community,xfournet/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,suncycheng/intellij-community,supersven/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,supersven/intellij-community,allotria/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,consulo/consulo,blademainer/intellij-community,ryano144/intellij-community,fnouama/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,asedunov/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,petteyg/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,allotria/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,da1z/intellij-community,Lekanich/intellij-community,izonder/intellij-community,allotria/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,signed/intellij-community,FHannes/intellij-community,semonte/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,FHannes/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,caot/intellij-community,kool79/intellij-community,adedayo/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,hurricup/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,hurricup/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,signed/intellij-community,izonder/intellij-community,semonte/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,vladmm/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,izonder/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,amith01994/intellij-community,amith01994/intellij-community,xfournet/intellij-community,xfournet/intellij-community,semonte/intellij-community,apixandru/intellij-community,ryano144/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,fitermay/intellij-community,diorcety/intellij-community,retomerz/intellij-community,samthor/intellij-community,kool79/intellij-community,tmpgit/intellij-community,semonte/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,apixandru/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,kdwink/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,caot/intellij-community,jagguli/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,FHannes/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,adedayo/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,Lekanich/intellij-community,consulo/consulo,vladmm/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,apixandru/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,kool79/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,blademainer/intellij-community,asedunov/intellij-community,semonte/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,consulo/consulo,holmes/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,supersven/intellij-community,dslomov/intellij-community,apixandru/intellij-community,kdwink/intellij-community,fitermay/intellij-community,ibinti/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,dslomov/intellij-community,dslomov/intellij-community,kool79/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,ernestp/consulo,vladmm/intellij-community,SerCeMan/intellij-community,ernestp/consulo,ahb0327/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,dslomov/intellij-community,signed/intellij-community,xfournet/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,supersven/intellij-community,hurricup/intellij-community,signed/intellij-community,Distrotech/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,caot/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,fitermay/intellij-community,clumsy/intellij-community,consulo/consulo,caot/intellij-community,fitermay/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,allotria/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,ernestp/consulo,akosyakov/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,izonder/intellij-community,da1z/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,hurricup/intellij-community,semonte/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,caot/intellij-community,clumsy/intellij-community,samthor/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,ryano144/intellij-community,da1z/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,slisson/intellij-community,clumsy/intellij-community,joewalnes/idea-community,holmes/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,petteyg/intellij-community,fnouama/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,signed/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,kool79/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,holmes/intellij-community,samthor/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,nicolargo/intellij-community,kool79/intellij-community,slisson/intellij-community,adedayo/intellij-community,da1z/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,ibinti/intellij-community,slisson/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ibinti/intellij-community,dslomov/intellij-community,joewalnes/idea-community,allotria/intellij-community,jagguli/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,izonder/intellij-community,supersven/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,samthor/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,jagguli/intellij-community,da1z/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,hurricup/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,amith01994/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,retomerz/intellij-community,izonder/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,dslomov/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,izonder/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,allotria/intellij-community,Lekanich/intellij-community,holmes/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,signed/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,amith01994/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,caot/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,allotria/intellij-community,samthor/intellij-community,retomerz/intellij-community,ryano144/intellij-community,hurricup/intellij-community,amith01994/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,consulo/consulo,semonte/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,joewalnes/idea-community,orekyuu/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,ryano144/intellij-community,clumsy/intellij-community,robovm/robovm-studio,caot/intellij-community,joewalnes/idea-community,apixandru/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,allotria/intellij-community,izonder/intellij-community,hurricup/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,adedayo/intellij-community,petteyg/intellij-community,fnouama/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,izonder/intellij-community,apixandru/intellij-community,ernestp/consulo,tmpgit/intellij-community,diorcety/intellij-community,consulo/consulo,slisson/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,apixandru/intellij-community,fnouama/intellij-community,petteyg/intellij-community,ibinti/intellij-community,semonte/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,adedayo/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,TangHao1987/intellij-community,slisson/intellij-community,slisson/intellij-community,amith01994/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.ui.configuration.libraryEditor; import com.intellij.ide.IconUtilEx; import com.intellij.ide.util.treeView.AbstractTreeStructure; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.impl.libraries.LibraryImpl; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryProperties; import com.intellij.openapi.roots.libraries.LibraryType; import com.intellij.openapi.roots.libraries.LibraryUtil; import com.intellij.openapi.roots.libraries.ui.AttachRootButtonDescriptor; import com.intellij.openapi.roots.libraries.ui.LibraryEditorComponent; import com.intellij.openapi.roots.libraries.ui.LibraryPropertiesEditor; import com.intellij.openapi.roots.libraries.ui.LibraryRootsComponentDescriptor; import com.intellij.openapi.roots.ui.configuration.ModuleEditor; import com.intellij.openapi.roots.ui.configuration.libraries.LibraryPresentationManager; import com.intellij.openapi.roots.ui.configuration.projectRoot.ModuleStructureConfigurable; import com.intellij.openapi.ui.VerticalFlowLayout; import com.intellij.openapi.ui.ex.MultiLineLabel; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.*; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.ex.http.HttpFileSystem; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ArrayUtil; import com.intellij.util.Icons; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.*; import java.util.List; /** * @author Eugene Zhuravlev * Date: Jan 11, 2004 */ public class LibraryRootsComponent implements Disposable, LibraryEditorComponent { static final UrlComparator ourUrlComparator = new UrlComparator(); private JPanel myPanel; private JButton myRemoveButton; private JPanel myTreePanel; private JButton myAttachMoreButton; private MultiLineLabel myPropertiesLabel; private JPanel myPropertiesPanel; private JPanel myAttachButtonsPanel; private LibraryPropertiesEditor myPropertiesEditor; private Tree myTree; private LibraryTableTreeBuilder myTreeBuilder; private static final Icon INVALID_ITEM_ICON = IconLoader.getIcon("/nodes/ppInvalid.png"); private static final Icon JAR_DIRECTORY_ICON = IconLoader.getIcon("/nodes/jarDirectory.png"); private final Collection<Runnable> myListeners = new ArrayList<Runnable>(); @Nullable private final Project myProject; private final Computable<LibraryEditor> myLibraryEditorComputable; private LibraryRootsComponentDescriptor myDescriptor; private Module myContextModule; public LibraryRootsComponent(@Nullable Project project, @NotNull LibraryEditor libraryEditor) { this(project, new Computable.PredefinedValueComputable<LibraryEditor>(libraryEditor)); } public LibraryRootsComponent(@Nullable Project project, @NotNull Computable<LibraryEditor> libraryEditorComputable) { myProject = project; myLibraryEditorComputable = libraryEditorComputable; final LibraryEditor editor = getLibraryEditor(); final LibraryType type = editor.getType(); if (type != null) { myDescriptor = type.createLibraryRootsComponentDescriptor(); //noinspection unchecked myPropertiesEditor = type.createPropertiesEditor(this); if (myPropertiesEditor != null) { myPropertiesPanel.add(myPropertiesEditor.createComponent(), BorderLayout.CENTER); } } if (myDescriptor == null) { myDescriptor = new DefaultLibraryRootsComponentDescriptor(); } init(new LibraryTreeStructure(this, myDescriptor)); updateProperties(); } @NotNull @Override public LibraryProperties getProperties() { return getLibraryEditor().getProperties(); } private void updateProperties() { StringBuilder text = new StringBuilder(); for (String description : LibraryPresentationManager.getInstance().getDescriptions(getLibraryEditor().getFiles(OrderRootType.CLASSES))) { if (text.length() > 0) { text.append("\n"); } text.append(description); } myPropertiesLabel.setText(text.toString()); } private void init(AbstractTreeStructure treeStructure) { myTree = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode())); myTree.setRootVisible(false); myTree.setShowsRootHandles(true); new MyTreeSpeedSearch(myTree); myTree.setCellRenderer(new LibraryTreeRenderer()); final MyTreeSelectionListener treeSelectionListener = new MyTreeSelectionListener(); myTree.getSelectionModel().addTreeSelectionListener(treeSelectionListener); myTreeBuilder = new LibraryTableTreeBuilder(myTree, (DefaultTreeModel)myTree.getModel(), treeStructure); myTreePanel.setLayout(new BorderLayout()); myTreePanel.add(ScrollPaneFactory.createScrollPane(myTree), BorderLayout.CENTER); final JPanel buttonsPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 5, true, false)); for (AttachRootButtonDescriptor descriptor : myDescriptor.createAttachButtons()) { JButton button = new JButton(descriptor.getButtonText()); button.addActionListener(new AttachItemAction(descriptor)); buttonsPanel.add(button); } myAttachButtonsPanel.add(buttonsPanel, BorderLayout.CENTER); myRemoveButton.addActionListener(new RemoveAction()); final LibraryTableAttachHandler[] handlers = LibraryTableAttachHandler.EP_NAME.getExtensions(); if (handlers.length == 0 || myProject == null || getLibraryEditor().getType() != null) { myAttachMoreButton.setVisible(false); } else { myAttachMoreButton.addActionListener(new AttachMoreAction(handlers)); if (handlers.length == 1) { myAttachMoreButton.setText(handlers[0].getLongName()); } } treeSelectionListener.updateButtons(); Disposer.register(this, myTreeBuilder); } public Tree getTree() { return myTree; } public JComponent getComponent() { return myPanel; } public void setContextModule(Module module) { myContextModule = module; } public LibraryEditor getLibraryEditor() { return myLibraryEditorComputable.compute(); } public boolean hasChanges() { if (myPropertiesEditor != null && myPropertiesEditor.isModified()) { return true; } return getLibraryEditor().hasChanges(); } private Object[] getSelectedElements() { if (myTreeBuilder == null || myTreeBuilder.isDisposed()) return ArrayUtil.EMPTY_OBJECT_ARRAY; final TreePath[] selectionPaths = myTreeBuilder.getTree().getSelectionPaths(); if (selectionPaths == null) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } List<Object> elements = new ArrayList<Object>(); for (TreePath selectionPath : selectionPaths) { final Object pathElement = getPathElement(selectionPath); if (pathElement != null) { elements.add(pathElement); } } return ArrayUtil.toObjectArray(elements); } @Nullable private static Object getPathElement(final TreePath selectionPath) { if (selectionPath == null) { return null; } final DefaultMutableTreeNode lastPathComponent = (DefaultMutableTreeNode)selectionPath.getLastPathComponent(); if (lastPathComponent == null) { return null; } final Object userObject = lastPathComponent.getUserObject(); if (!(userObject instanceof NodeDescriptor)) { return null; } final Object element = ((NodeDescriptor)userObject).getElement(); if (!(element instanceof LibraryTableTreeContentElement)) { return null; } return element; } public void renameLibrary(String newName) { final LibraryEditor libraryEditor = getLibraryEditor(); libraryEditor.setName(newName); librariesChanged(false); } public void dispose() { if (myPropertiesEditor != null) { myPropertiesEditor.disposeUIResources(); } myTreeBuilder = null; } public void resetProperties() { if (myPropertiesEditor != null) { myPropertiesEditor.reset(); } } public void applyProperties() { if (myPropertiesEditor != null && myPropertiesEditor.isModified()) { myPropertiesEditor.apply(); } } public void updateRootsTree() { if (myTreeBuilder != null) { myTreeBuilder.queueUpdate(); } } private class AttachItemAction implements ActionListener { private VirtualFile myLastChosen = null; private final AttachRootButtonDescriptor myDescriptor; protected AttachItemAction(AttachRootButtonDescriptor descriptor) { myDescriptor = descriptor; } public final void actionPerformed(ActionEvent e) { VirtualFile toSelect = getFileToSelect(); final VirtualFile[] files = myDescriptor.selectFiles(myPanel, toSelect, myContextModule, getLibraryEditor().getName()); if (files.length == 0) return; final VirtualFile[] attachedFiles = attachFiles(myDescriptor.scanForActualRoots(files, myPanel), myDescriptor.getRootType(), myDescriptor.addAsJarDirectories()); if (attachedFiles.length > 0) { myLastChosen = attachedFiles[0]; } fireLibrariesChanged(); myTree.requestFocus(); } @Nullable private VirtualFile getFileToSelect() { VirtualFile toSelect = myLastChosen; if (toSelect == null) { for (OrderRootType orderRootType : OrderRootType.getAllPersistentTypes()) { final VirtualFile[] existingRoots = getLibraryEditor().getFiles(orderRootType); if (existingRoots.length > 0) { VirtualFile existingRoot = existingRoots [0]; if (existingRoot.getFileSystem() instanceof JarFileSystem) { existingRoot = JarFileSystem.getInstance().getVirtualFileForJar(existingRoot); } if (existingRoot != null) { if (existingRoot.isDirectory()) { toSelect = existingRoot; } else { toSelect = existingRoot.getParent(); } } break; } } } if (toSelect == null) { final Project project = myProject; if (project != null) { //todo[nik] perhaps we shouldn't select project base dir if global library is edited toSelect = project.getBaseDir(); } } return toSelect; } } private VirtualFile[] attachFiles(final VirtualFile[] files, final OrderRootType rootType, final boolean isJarDirectories) { final VirtualFile[] filesToAttach = filterAlreadyAdded(files, rootType); if (filesToAttach.length > 0) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { final LibraryEditor libraryEditor = getLibraryEditor(); for (VirtualFile file : filesToAttach) { if (isJarDirectories) { libraryEditor.addJarDirectory(file, false); } else { libraryEditor.addRoot(file, rootType); } } } }); updateProperties(); myTreeBuilder.queueUpdate(); } return filesToAttach; } private VirtualFile[] filterAlreadyAdded(VirtualFile[] files, final OrderRootType rootType) { if (files == null || files.length == 0) { return VirtualFile.EMPTY_ARRAY; } final Set<VirtualFile> chosenFilesSet = new HashSet<VirtualFile>(Arrays.asList(files)); final Set<VirtualFile> alreadyAdded = new HashSet<VirtualFile>(); final VirtualFile[] libraryFiles = getLibraryEditor().getFiles(rootType); ContainerUtil.addAll(alreadyAdded, libraryFiles); chosenFilesSet.removeAll(alreadyAdded); return VfsUtil.toVirtualFileArray(chosenFilesSet); } private class RemoveAction implements ActionListener { public void actionPerformed(ActionEvent e) { final Object[] selectedElements = getSelectedElements(); if (selectedElements.length == 0) { return; } ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (Object selectedElement : selectedElements) { if (selectedElement instanceof ItemElement) { final ItemElement itemElement = (ItemElement)selectedElement; getLibraryEditor().removeRoot(itemElement.getUrl(), itemElement.getRootType()); } } } }); librariesChanged(true); } } protected void librariesChanged(boolean putFocusIntoTree) { updateProperties(); myTreeBuilder.queueUpdate(); if (putFocusIntoTree) { myTree.requestFocus(); } fireLibrariesChanged(); } private void fireLibrariesChanged() { Runnable[] runnables = myListeners.toArray(new Runnable[myListeners.size()]); for (Runnable listener : runnables) { listener.run(); } } public void addListener(Runnable listener) { myListeners.add(listener); } public void removeListener(Runnable listener) { myListeners.remove(listener); } private class MyTreeSelectionListener implements TreeSelectionListener { public void valueChanged(TreeSelectionEvent e) { updateButtons(); } public void updateButtons() { final Object[] selectedElements = getSelectedElements(); final Class<?> elementsClass = getElementsClass(selectedElements); myRemoveButton.setEnabled(elementsClass != null && !elementsClass.isAssignableFrom(OrderRootTypeElement.class)); } @Nullable private Class<?> getElementsClass(Object[] elements) { if (elements.length == 0) { return null; } Class<?> cls = null; for (Object element : elements) { if (cls == null) { cls = element.getClass(); } else { if (!cls.equals(element.getClass())) { return null; } } } return cls; } } static Icon getIconForUrl(final String url, final boolean isValid, final boolean isJarDirectory) { final Icon icon; if (isValid) { VirtualFile presentableFile; if (isJarFileRoot(url)) { presentableFile = LocalFileSystem.getInstance().findFileByPath(getPresentablePath(url)); } else { presentableFile = VirtualFileManager.getInstance().findFileByUrl(url); } if (presentableFile != null && presentableFile.isValid()) { if (presentableFile.getFileSystem() instanceof HttpFileSystem) { icon = Icons.WEB_ICON; } else { if (presentableFile.isDirectory()) { if (isJarDirectory) { icon = JAR_DIRECTORY_ICON; } else { icon = Icons.DIRECTORY_CLOSED_ICON; } } else { icon = IconUtilEx.getIcon(presentableFile, 0, null); } } } else { icon = INVALID_ITEM_ICON; } } else { icon = INVALID_ITEM_ICON; } return icon; } static String getPresentablePath(final String url) { String presentablePath = VirtualFileManager.extractPath(url); if (isJarFileRoot(url)) { presentablePath = presentablePath.substring(0, presentablePath.length() - JarFileSystem.JAR_SEPARATOR.length()); } return presentablePath; } private static boolean isJarFileRoot(final String url) { return VirtualFileManager.extractPath(url).endsWith(JarFileSystem.JAR_SEPARATOR); } private static class MyTreeSpeedSearch extends TreeSpeedSearch { public MyTreeSpeedSearch(final Tree tree) { super(tree); } public boolean isMatchingElement(Object element, String pattern) { Object userObject = ((DefaultMutableTreeNode)((TreePath)element).getLastPathComponent()).getUserObject(); if (userObject instanceof ItemElementDescriptor) { String str = getElementText(element); if (str == null) { return false; } if (!hasCapitals(pattern)) { // be case-sensitive only if user types capitals str = str.toLowerCase(); } if (pattern.contains(File.separator)) { return compare(str,pattern); } final StringTokenizer tokenizer = new StringTokenizer(str, File.separator); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); if (compare(token,pattern)) { return true; } } return false; } else { return super.isMatchingElement(element, pattern); } } private static boolean hasCapitals(String str) { for (int idx = 0; idx < str.length(); idx++) { if (Character.isUpperCase(str.charAt(idx))) { return true; } } return false; } } private class AttachMoreAction implements ActionListener { private final LibraryTableAttachHandler[] myHandlers; public AttachMoreAction(LibraryTableAttachHandler[] handlers) { myHandlers = handlers; } public void actionPerformed(ActionEvent e) { final LibraryEditor libraryEditor = getLibraryEditor(); final Ref<Library.ModifiableModel> modelRef = Ref.create(null); final NullableComputable<Library.ModifiableModel> computable; if (libraryEditor instanceof ExistingLibraryEditor) { final ExistingLibraryEditor existingLibraryEditor = (ExistingLibraryEditor)libraryEditor; //todo[nik, greg] actually we cannot reliable find target library if the editor is closed so jars are downloaded under the modal progress dialog now computable = new NullableComputable<Library.ModifiableModel>() { public Library.ModifiableModel compute() { if (myTreeBuilder == null) { // The following lines were born in severe pain & suffering, please respect final Library library = existingLibraryEditor.getLibrary(); final InvocationHandler invocationHandler = Proxy.isProxyClass(library.getClass())? Proxy.getInvocationHandler(library) : null; final Library realLibrary = invocationHandler instanceof ModuleEditor.ProxyDelegateAccessor? (Library)((ModuleEditor.ProxyDelegateAccessor)invocationHandler) .getDelegate() : library; final Module module = realLibrary instanceof LibraryImpl && ((LibraryImpl)realLibrary).isDisposed()? ((LibraryImpl)realLibrary).getModule() : null; if (module != null && module.isDisposed()) return null; // no way final Library targetLibrary = module != null? LibraryUtil.findLibrary(module, realLibrary.getName()) : realLibrary; final Library.ModifiableModel model = targetLibrary.getModifiableModel(); modelRef.set(model); return model; } else { return existingLibraryEditor.getModel(); } } }; } else { computable = null; } final Runnable successRunnable = new Runnable() { public void run() { if (modelRef.get() != null) { modelRef.get().commit(); } ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (myTreeBuilder != null) myTreeBuilder.queueUpdate(); if (myProject != null && libraryEditor instanceof ExistingLibraryEditor) { ModuleStructureConfigurable.getInstance(myProject).fireItemsChangeListener(((ExistingLibraryEditor)libraryEditor).getLibrary()); } } }); } }; final Runnable rejectRunnable = new Runnable() { public void run() { if (modelRef.get() != null) { Disposer.dispose(modelRef.get()); } } }; if (myHandlers.length == 1) { myHandlers[0].performAttach(myProject, libraryEditor, computable).doWhenDone(successRunnable).doWhenRejected(rejectRunnable); } else { final ListPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<LibraryTableAttachHandler>(null, myHandlers) { @NotNull public String getTextFor(final LibraryTableAttachHandler handler) { return handler.getShortName(); } public Icon getIconFor(final LibraryTableAttachHandler handler) { return handler.getIcon(); } public PopupStep onChosen(final LibraryTableAttachHandler handler, final boolean finalChoice) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { handler.performAttach(myProject, libraryEditor, computable).doWhenProcessed(successRunnable).doWhenRejected(rejectRunnable); } }); return PopupStep.FINAL_CHOICE; } }); popup.showUnderneathOf(myAttachMoreButton); } } } }
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/LibraryRootsComponent.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.ui.configuration.libraryEditor; import com.intellij.ide.IconUtilEx; import com.intellij.ide.util.treeView.AbstractTreeStructure; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.impl.libraries.LibraryImpl; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryProperties; import com.intellij.openapi.roots.libraries.LibraryType; import com.intellij.openapi.roots.libraries.LibraryUtil; import com.intellij.openapi.roots.libraries.ui.AttachRootButtonDescriptor; import com.intellij.openapi.roots.libraries.ui.LibraryEditorComponent; import com.intellij.openapi.roots.libraries.ui.LibraryPropertiesEditor; import com.intellij.openapi.roots.libraries.ui.LibraryRootsComponentDescriptor; import com.intellij.openapi.roots.ui.configuration.ModuleEditor; import com.intellij.openapi.roots.ui.configuration.libraries.LibraryPresentationManager; import com.intellij.openapi.roots.ui.configuration.projectRoot.ModuleStructureConfigurable; import com.intellij.openapi.ui.VerticalFlowLayout; import com.intellij.openapi.ui.ex.MultiLineLabel; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.ListPopup; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.*; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.ex.http.HttpFileSystem; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ArrayUtil; import com.intellij.util.Icons; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.*; import java.util.List; /** * @author Eugene Zhuravlev * Date: Jan 11, 2004 */ public class LibraryRootsComponent implements Disposable, LibraryEditorComponent { static final UrlComparator ourUrlComparator = new UrlComparator(); private JPanel myPanel; private JButton myRemoveButton; private JPanel myTreePanel; private JButton myAttachMoreButton; private MultiLineLabel myPropertiesLabel; private JPanel myPropertiesPanel; private JPanel myAttachButtonsPanel; private LibraryPropertiesEditor myPropertiesEditor; private Tree myTree; private LibraryTableTreeBuilder myTreeBuilder; private static final Icon INVALID_ITEM_ICON = IconLoader.getIcon("/nodes/ppInvalid.png"); private static final Icon JAR_DIRECTORY_ICON = IconLoader.getIcon("/nodes/jarDirectory.png"); private final Collection<Runnable> myListeners = new ArrayList<Runnable>(); @Nullable private final Project myProject; private final Computable<LibraryEditor> myLibraryEditorComputable; private LibraryRootsComponentDescriptor myDescriptor; private Module myContextModule; public LibraryRootsComponent(@Nullable Project project, @NotNull LibraryEditor libraryEditor) { this(project, new Computable.PredefinedValueComputable<LibraryEditor>(libraryEditor)); } public LibraryRootsComponent(@Nullable Project project, @NotNull Computable<LibraryEditor> libraryEditorComputable) { myProject = project; myLibraryEditorComputable = libraryEditorComputable; final LibraryEditor editor = getLibraryEditor(); final LibraryType type = editor.getType(); if (type != null) { myDescriptor = type.createLibraryRootsComponentDescriptor(); //noinspection unchecked myPropertiesEditor = type.createPropertiesEditor(this); if (myPropertiesEditor != null) { myPropertiesPanel.add(myPropertiesEditor.createComponent(), BorderLayout.CENTER); } } if (myDescriptor == null) { myDescriptor = new DefaultLibraryRootsComponentDescriptor(); } init(new LibraryTreeStructure(this, myDescriptor)); updateProperties(); } @NotNull @Override public LibraryProperties getProperties() { return getLibraryEditor().getProperties(); } private void updateProperties() { StringBuilder text = new StringBuilder(); for (String description : LibraryPresentationManager.getInstance().getDescriptions(getLibraryEditor().getFiles(OrderRootType.CLASSES))) { if (text.length() > 0) { text.append("\n"); } text.append(description); } myPropertiesLabel.setText(text.toString()); } private void init(AbstractTreeStructure treeStructure) { myTree = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode())); myTree.setRootVisible(false); myTree.setShowsRootHandles(true); new MyTreeSpeedSearch(myTree); myTree.setCellRenderer(new LibraryTreeRenderer()); final MyTreeSelectionListener treeSelectionListener = new MyTreeSelectionListener(); myTree.getSelectionModel().addTreeSelectionListener(treeSelectionListener); myTreeBuilder = new LibraryTableTreeBuilder(myTree, (DefaultTreeModel)myTree.getModel(), treeStructure); myTreePanel.setLayout(new BorderLayout()); myTreePanel.add(ScrollPaneFactory.createScrollPane(myTree), BorderLayout.CENTER); final JPanel buttonsPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 5, true, false)); for (AttachRootButtonDescriptor descriptor : myDescriptor.createAttachButtons()) { JButton button = new JButton(descriptor.getButtonText()); button.addActionListener(new AttachItemAction(descriptor)); buttonsPanel.add(button); } myAttachButtonsPanel.add(buttonsPanel, BorderLayout.CENTER); myRemoveButton.addActionListener(new RemoveAction()); final LibraryTableAttachHandler[] handlers = LibraryTableAttachHandler.EP_NAME.getExtensions(); if (handlers.length == 0 || myProject == null || myDescriptor != null) { myAttachMoreButton.setVisible(false); } else { myAttachMoreButton.addActionListener(new AttachMoreAction(handlers)); if (handlers.length == 1) { myAttachMoreButton.setText(handlers[0].getLongName()); } } treeSelectionListener.updateButtons(); Disposer.register(this, myTreeBuilder); } public Tree getTree() { return myTree; } public JComponent getComponent() { return myPanel; } public void setContextModule(Module module) { myContextModule = module; } public LibraryEditor getLibraryEditor() { return myLibraryEditorComputable.compute(); } public boolean hasChanges() { if (myPropertiesEditor != null && myPropertiesEditor.isModified()) { return true; } return getLibraryEditor().hasChanges(); } private Object[] getSelectedElements() { if (myTreeBuilder == null || myTreeBuilder.isDisposed()) return ArrayUtil.EMPTY_OBJECT_ARRAY; final TreePath[] selectionPaths = myTreeBuilder.getTree().getSelectionPaths(); if (selectionPaths == null) { return ArrayUtil.EMPTY_OBJECT_ARRAY; } List<Object> elements = new ArrayList<Object>(); for (TreePath selectionPath : selectionPaths) { final Object pathElement = getPathElement(selectionPath); if (pathElement != null) { elements.add(pathElement); } } return ArrayUtil.toObjectArray(elements); } @Nullable private static Object getPathElement(final TreePath selectionPath) { if (selectionPath == null) { return null; } final DefaultMutableTreeNode lastPathComponent = (DefaultMutableTreeNode)selectionPath.getLastPathComponent(); if (lastPathComponent == null) { return null; } final Object userObject = lastPathComponent.getUserObject(); if (!(userObject instanceof NodeDescriptor)) { return null; } final Object element = ((NodeDescriptor)userObject).getElement(); if (!(element instanceof LibraryTableTreeContentElement)) { return null; } return element; } public void renameLibrary(String newName) { final LibraryEditor libraryEditor = getLibraryEditor(); libraryEditor.setName(newName); librariesChanged(false); } public void dispose() { if (myPropertiesEditor != null) { myPropertiesEditor.disposeUIResources(); } myTreeBuilder = null; } public void resetProperties() { if (myPropertiesEditor != null) { myPropertiesEditor.reset(); } } public void applyProperties() { if (myPropertiesEditor != null && myPropertiesEditor.isModified()) { myPropertiesEditor.apply(); } } public void updateRootsTree() { if (myTreeBuilder != null) { myTreeBuilder.queueUpdate(); } } private class AttachItemAction implements ActionListener { private VirtualFile myLastChosen = null; private final AttachRootButtonDescriptor myDescriptor; protected AttachItemAction(AttachRootButtonDescriptor descriptor) { myDescriptor = descriptor; } public final void actionPerformed(ActionEvent e) { VirtualFile toSelect = getFileToSelect(); final VirtualFile[] files = myDescriptor.selectFiles(myPanel, toSelect, myContextModule, getLibraryEditor().getName()); if (files.length == 0) return; final VirtualFile[] attachedFiles = attachFiles(myDescriptor.scanForActualRoots(files, myPanel), myDescriptor.getRootType(), myDescriptor.addAsJarDirectories()); if (attachedFiles.length > 0) { myLastChosen = attachedFiles[0]; } fireLibrariesChanged(); myTree.requestFocus(); } @Nullable private VirtualFile getFileToSelect() { VirtualFile toSelect = myLastChosen; if (toSelect == null) { for (OrderRootType orderRootType : OrderRootType.getAllPersistentTypes()) { final VirtualFile[] existingRoots = getLibraryEditor().getFiles(orderRootType); if (existingRoots.length > 0) { VirtualFile existingRoot = existingRoots [0]; if (existingRoot.getFileSystem() instanceof JarFileSystem) { existingRoot = JarFileSystem.getInstance().getVirtualFileForJar(existingRoot); } if (existingRoot != null) { if (existingRoot.isDirectory()) { toSelect = existingRoot; } else { toSelect = existingRoot.getParent(); } } break; } } } if (toSelect == null) { final Project project = myProject; if (project != null) { //todo[nik] perhaps we shouldn't select project base dir if global library is edited toSelect = project.getBaseDir(); } } return toSelect; } } private VirtualFile[] attachFiles(final VirtualFile[] files, final OrderRootType rootType, final boolean isJarDirectories) { final VirtualFile[] filesToAttach = filterAlreadyAdded(files, rootType); if (filesToAttach.length > 0) { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { final LibraryEditor libraryEditor = getLibraryEditor(); for (VirtualFile file : filesToAttach) { if (isJarDirectories) { libraryEditor.addJarDirectory(file, false); } else { libraryEditor.addRoot(file, rootType); } } } }); updateProperties(); myTreeBuilder.queueUpdate(); } return filesToAttach; } private VirtualFile[] filterAlreadyAdded(VirtualFile[] files, final OrderRootType rootType) { if (files == null || files.length == 0) { return VirtualFile.EMPTY_ARRAY; } final Set<VirtualFile> chosenFilesSet = new HashSet<VirtualFile>(Arrays.asList(files)); final Set<VirtualFile> alreadyAdded = new HashSet<VirtualFile>(); final VirtualFile[] libraryFiles = getLibraryEditor().getFiles(rootType); ContainerUtil.addAll(alreadyAdded, libraryFiles); chosenFilesSet.removeAll(alreadyAdded); return VfsUtil.toVirtualFileArray(chosenFilesSet); } private class RemoveAction implements ActionListener { public void actionPerformed(ActionEvent e) { final Object[] selectedElements = getSelectedElements(); if (selectedElements.length == 0) { return; } ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { for (Object selectedElement : selectedElements) { if (selectedElement instanceof ItemElement) { final ItemElement itemElement = (ItemElement)selectedElement; getLibraryEditor().removeRoot(itemElement.getUrl(), itemElement.getRootType()); } } } }); librariesChanged(true); } } protected void librariesChanged(boolean putFocusIntoTree) { updateProperties(); myTreeBuilder.queueUpdate(); if (putFocusIntoTree) { myTree.requestFocus(); } fireLibrariesChanged(); } private void fireLibrariesChanged() { Runnable[] runnables = myListeners.toArray(new Runnable[myListeners.size()]); for (Runnable listener : runnables) { listener.run(); } } public void addListener(Runnable listener) { myListeners.add(listener); } public void removeListener(Runnable listener) { myListeners.remove(listener); } private class MyTreeSelectionListener implements TreeSelectionListener { public void valueChanged(TreeSelectionEvent e) { updateButtons(); } public void updateButtons() { final Object[] selectedElements = getSelectedElements(); final Class<?> elementsClass = getElementsClass(selectedElements); myRemoveButton.setEnabled(elementsClass != null && !elementsClass.isAssignableFrom(OrderRootTypeElement.class)); } @Nullable private Class<?> getElementsClass(Object[] elements) { if (elements.length == 0) { return null; } Class<?> cls = null; for (Object element : elements) { if (cls == null) { cls = element.getClass(); } else { if (!cls.equals(element.getClass())) { return null; } } } return cls; } } static Icon getIconForUrl(final String url, final boolean isValid, final boolean isJarDirectory) { final Icon icon; if (isValid) { VirtualFile presentableFile; if (isJarFileRoot(url)) { presentableFile = LocalFileSystem.getInstance().findFileByPath(getPresentablePath(url)); } else { presentableFile = VirtualFileManager.getInstance().findFileByUrl(url); } if (presentableFile != null && presentableFile.isValid()) { if (presentableFile.getFileSystem() instanceof HttpFileSystem) { icon = Icons.WEB_ICON; } else { if (presentableFile.isDirectory()) { if (isJarDirectory) { icon = JAR_DIRECTORY_ICON; } else { icon = Icons.DIRECTORY_CLOSED_ICON; } } else { icon = IconUtilEx.getIcon(presentableFile, 0, null); } } } else { icon = INVALID_ITEM_ICON; } } else { icon = INVALID_ITEM_ICON; } return icon; } static String getPresentablePath(final String url) { String presentablePath = VirtualFileManager.extractPath(url); if (isJarFileRoot(url)) { presentablePath = presentablePath.substring(0, presentablePath.length() - JarFileSystem.JAR_SEPARATOR.length()); } return presentablePath; } private static boolean isJarFileRoot(final String url) { return VirtualFileManager.extractPath(url).endsWith(JarFileSystem.JAR_SEPARATOR); } private static class MyTreeSpeedSearch extends TreeSpeedSearch { public MyTreeSpeedSearch(final Tree tree) { super(tree); } public boolean isMatchingElement(Object element, String pattern) { Object userObject = ((DefaultMutableTreeNode)((TreePath)element).getLastPathComponent()).getUserObject(); if (userObject instanceof ItemElementDescriptor) { String str = getElementText(element); if (str == null) { return false; } if (!hasCapitals(pattern)) { // be case-sensitive only if user types capitals str = str.toLowerCase(); } if (pattern.contains(File.separator)) { return compare(str,pattern); } final StringTokenizer tokenizer = new StringTokenizer(str, File.separator); while (tokenizer.hasMoreTokens()) { final String token = tokenizer.nextToken(); if (compare(token,pattern)) { return true; } } return false; } else { return super.isMatchingElement(element, pattern); } } private static boolean hasCapitals(String str) { for (int idx = 0; idx < str.length(); idx++) { if (Character.isUpperCase(str.charAt(idx))) { return true; } } return false; } } private class AttachMoreAction implements ActionListener { private final LibraryTableAttachHandler[] myHandlers; public AttachMoreAction(LibraryTableAttachHandler[] handlers) { myHandlers = handlers; } public void actionPerformed(ActionEvent e) { final LibraryEditor libraryEditor = getLibraryEditor(); final Ref<Library.ModifiableModel> modelRef = Ref.create(null); final NullableComputable<Library.ModifiableModel> computable; if (libraryEditor instanceof ExistingLibraryEditor) { final ExistingLibraryEditor existingLibraryEditor = (ExistingLibraryEditor)libraryEditor; //todo[nik, greg] actually we cannot reliable find target library if the editor is closed so jars are downloaded under the modal progress dialog now computable = new NullableComputable<Library.ModifiableModel>() { public Library.ModifiableModel compute() { if (myTreeBuilder == null) { // The following lines were born in severe pain & suffering, please respect final Library library = existingLibraryEditor.getLibrary(); final InvocationHandler invocationHandler = Proxy.isProxyClass(library.getClass())? Proxy.getInvocationHandler(library) : null; final Library realLibrary = invocationHandler instanceof ModuleEditor.ProxyDelegateAccessor? (Library)((ModuleEditor.ProxyDelegateAccessor)invocationHandler) .getDelegate() : library; final Module module = realLibrary instanceof LibraryImpl && ((LibraryImpl)realLibrary).isDisposed()? ((LibraryImpl)realLibrary).getModule() : null; if (module != null && module.isDisposed()) return null; // no way final Library targetLibrary = module != null? LibraryUtil.findLibrary(module, realLibrary.getName()) : realLibrary; final Library.ModifiableModel model = targetLibrary.getModifiableModel(); modelRef.set(model); return model; } else { return existingLibraryEditor.getModel(); } } }; } else { computable = null; } final Runnable successRunnable = new Runnable() { public void run() { if (modelRef.get() != null) { modelRef.get().commit(); } ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (myTreeBuilder != null) myTreeBuilder.queueUpdate(); if (myProject != null && libraryEditor instanceof ExistingLibraryEditor) { ModuleStructureConfigurable.getInstance(myProject).fireItemsChangeListener(((ExistingLibraryEditor)libraryEditor).getLibrary()); } } }); } }; final Runnable rejectRunnable = new Runnable() { public void run() { if (modelRef.get() != null) { Disposer.dispose(modelRef.get()); } } }; if (myHandlers.length == 1) { myHandlers[0].performAttach(myProject, libraryEditor, computable).doWhenDone(successRunnable).doWhenRejected(rejectRunnable); } else { final ListPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<LibraryTableAttachHandler>(null, myHandlers) { @NotNull public String getTextFor(final LibraryTableAttachHandler handler) { return handler.getShortName(); } public Icon getIconFor(final LibraryTableAttachHandler handler) { return handler.getIcon(); } public PopupStep onChosen(final LibraryTableAttachHandler handler, final boolean finalChoice) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { handler.performAttach(myProject, libraryEditor, computable).doWhenProcessed(successRunnable).doWhenRejected(rejectRunnable); } }); return PopupStep.FINAL_CHOICE; } }); popup.showUnderneathOf(myAttachMoreButton); } } } }
'attach from repository' button restored
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/LibraryRootsComponent.java
'attach from repository' button restored
<ide><path>ava/idea-ui/src/com/intellij/openapi/roots/ui/configuration/libraryEditor/LibraryRootsComponent.java <ide> <ide> myRemoveButton.addActionListener(new RemoveAction()); <ide> final LibraryTableAttachHandler[] handlers = LibraryTableAttachHandler.EP_NAME.getExtensions(); <del> if (handlers.length == 0 || myProject == null || myDescriptor != null) { <add> if (handlers.length == 0 || myProject == null || getLibraryEditor().getType() != null) { <ide> myAttachMoreButton.setVisible(false); <ide> } <ide> else {
Java
mit
d0b5fa8d0779244c9903fcf12033ce92df941ad4
0
json-iterator/java
package com.jsoniter; import com.jsoniter.any.Any; import com.jsoniter.spi.JsonException; import com.jsoniter.spi.Slice; import java.io.IOException; class IterImplForStreaming { public static final int readObjectFieldAsHash(JsonIterator iter) throws IOException { if (nextToken(iter) != '"') { throw iter.reportError("readObjectFieldAsHash", "expect \""); } long hash = 0x811c9dc5; for (; ; ) { byte c = 0; int i = iter.head; for (; i < iter.tail; i++) { c = iter.buf[i]; if (c == '"') { break; } hash ^= c; hash *= 0x1000193; } if (c == '"') { iter.head = i + 1; if (nextToken(iter) != ':') { throw iter.reportError("readObjectFieldAsHash", "expect :"); } return (int) hash; } if (!loadMore(iter)) { throw iter.reportError("readObjectFieldAsHash", "unmatched quote"); } } } public static final Slice readObjectFieldAsSlice(JsonIterator iter) throws IOException { Slice field = readSlice(iter); boolean notCopied = field != null; if (CodegenAccess.skipWhitespacesWithoutLoadMore(iter)) { if (notCopied) { int len = field.tail() - field.head(); byte[] newBuf = new byte[len]; System.arraycopy(field.data(), field.head(), newBuf, 0, len); field.reset(newBuf, 0, newBuf.length); } if (!loadMore(iter)) { throw iter.reportError("readObjectFieldAsSlice", "expect : after object field"); } } if (iter.buf[iter.head] != ':') { throw iter.reportError("readObjectFieldAsSlice", "expect : after object field"); } iter.head++; return field; } final static void skipArray(JsonIterator iter) throws IOException { int level = 1; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { switch (iter.buf[i]) { case '"': // If inside string, skip it iter.head = i + 1; skipString(iter); i = iter.head - 1; // it will be i++ soon break; case '[': // If open symbol, increase level level++; break; case ']': // If close symbol, increase level level--; // If we have returned to the original level, we're done if (level == 0) { iter.head = i + 1; return; } break; } } if (!loadMore(iter)) { return; } } } final static void skipObject(JsonIterator iter) throws IOException { int level = 1; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { switch (iter.buf[i]) { case '"': // If inside string, skip it iter.head = i + 1; skipString(iter); i = iter.head - 1; // it will be i++ soon break; case '{': // If open symbol, increase level level++; break; case '}': // If close symbol, increase level level--; // If we have returned to the original level, we're done if (level == 0) { iter.head = i + 1; return; } break; } } if (!loadMore(iter)) { return; } } } final static void skipString(JsonIterator iter) throws IOException { for (; ; ) { int end = IterImplSkip.findStringEnd(iter); if (end == -1) { int j = iter.tail - 1; boolean escaped = true; // can not just look the last byte is \ // because it could be \\ or \\\ for (; ; ) { // walk backward until head if (j < iter.head || iter.buf[j] != '\\') { // even number of backslashes // either end of buffer, or " found escaped = false; break; } j--; if (j < iter.head || iter.buf[j] != '\\') { // odd number of backslashes // it is \" or \\\" break; } j--; } if (!loadMore(iter)) { throw iter.reportError("skipString", "incomplete string"); } if (escaped) { iter.head = 1; // skip the first char as last char is \ } } else { iter.head = end; return; } } } final static void skipUntilBreak(JsonIterator iter) throws IOException { // true, false, null, number for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { byte c = iter.buf[i]; if (IterImplSkip.breaks[c]) { iter.head = i; return; } } if (!loadMore(iter)) { iter.head = iter.tail; return; } } } final static boolean skipNumber(JsonIterator iter) throws IOException { // true, false, null, number boolean dotFound = false; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { byte c = iter.buf[i]; if (c == '.' || c == 'e' || c == 'E') { dotFound = true; continue; } if (IterImplSkip.breaks[c]) { iter.head = i; return dotFound; } } if (!loadMore(iter)) { iter.head = iter.tail; return dotFound; } } } // read the bytes between " " final static Slice readSlice(JsonIterator iter) throws IOException { if (IterImpl.nextToken(iter) != '"') { throw iter.reportError("readSlice", "expect \" for string"); } int end = IterImplString.findSliceEnd(iter); if (end != -1) { // reuse current buffer iter.reusableSlice.reset(iter.buf, iter.head, end - 1); iter.head = end; return iter.reusableSlice; } // TODO: avoid small memory allocation byte[] part1 = new byte[iter.tail - iter.head]; System.arraycopy(iter.buf, iter.head, part1, 0, part1.length); for (; ; ) { if (!loadMore(iter)) { throw iter.reportError("readSlice", "unmatched quote"); } end = IterImplString.findSliceEnd(iter); if (end == -1) { byte[] part2 = new byte[part1.length + iter.buf.length]; System.arraycopy(part1, 0, part2, 0, part1.length); System.arraycopy(iter.buf, 0, part2, part1.length, iter.buf.length); part1 = part2; } else { byte[] part2 = new byte[part1.length + end - 1]; System.arraycopy(part1, 0, part2, 0, part1.length); System.arraycopy(iter.buf, 0, part2, part1.length, end - 1); iter.head = end; iter.reusableSlice.reset(part2, 0, part2.length); return iter.reusableSlice; } } } final static byte nextToken(JsonIterator iter) throws IOException { for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { byte c = iter.buf[i]; switch (c) { case ' ': case '\n': case '\t': case '\r': continue; default: iter.head = i + 1; return c; } } if (!loadMore(iter)) { return 0; } } } public final static boolean loadMore(JsonIterator iter) throws IOException { if (iter.in == null) { return false; } if (iter.skipStartedAt != -1) { return keepSkippedBytesThenRead(iter); } int n = iter.in.read(iter.buf); if (n < 1) { if (n == -1) { return false; } else { throw iter.reportError("loadMore", "read from input stream returned " + n); } } else { iter.head = 0; iter.tail = n; } return true; } private static boolean keepSkippedBytesThenRead(JsonIterator iter) throws IOException { int offset = iter.tail - iter.skipStartedAt; byte[] srcBuffer = iter.buf; // Double the size of internal buffer // TODO: Fix NegativeArraySizeException that happens if source stream doesnt return as much // of output as was requested i.e. when n < iter.buf.length - offset. Anyhow doubling the buffer // size seems to be pretty dangerous idea and should be either disabled or solved safely. if (iter.skipStartedAt == 0 || iter.skipStartedAt < iter.tail / 2) { iter.buf = new byte[iter.buf.length * 2]; } System.arraycopy(srcBuffer, iter.skipStartedAt, iter.buf, 0, offset); int n = iter.in.read(iter.buf, offset, iter.buf.length - offset); iter.skipStartedAt = 0; if (n < 1) { if (n == -1) { return false; } else { throw iter.reportError("loadMore", "read from input stream returned " + n); } } else { iter.head = offset; iter.tail = offset + n; } return true; } final static byte readByte(JsonIterator iter) throws IOException { if (iter.head == iter.tail) { if (!loadMore(iter)) { throw iter.reportError("readByte", "no more to read"); } } return iter.buf[iter.head++]; } public static Any readAny(JsonIterator iter) throws IOException { // TODO: avoid small memory allocation iter.skipStartedAt = iter.head; byte c = nextToken(iter); switch (c) { case '"': skipString(iter); byte[] copied = copySkippedBytes(iter); return Any.lazyString(copied, 0, copied.length); case 't': skipFixedBytes(iter, 3); iter.skipStartedAt = -1; return Any.wrap(true); case 'f': skipFixedBytes(iter, 4); iter.skipStartedAt = -1; return Any.wrap(false); case 'n': skipFixedBytes(iter, 3); iter.skipStartedAt = -1; return Any.wrap((Object) null); case '[': skipArray(iter); copied = copySkippedBytes(iter); return Any.lazyArray(copied, 0, copied.length); case '{': skipObject(iter); copied = copySkippedBytes(iter); return Any.lazyObject(copied, 0, copied.length); default: if (skipNumber(iter)) { copied = copySkippedBytes(iter); return Any.lazyDouble(copied, 0, copied.length); } else { copied = copySkippedBytes(iter); return Any.lazyLong(copied, 0, copied.length); } } } private static byte[] copySkippedBytes(JsonIterator iter) { int start = iter.skipStartedAt; iter.skipStartedAt = -1; int end = iter.head; byte[] bytes = new byte[end - start]; System.arraycopy(iter.buf, start, bytes, 0, bytes.length); return bytes; } public static void skipFixedBytes(JsonIterator iter, int n) throws IOException { iter.head += n; if (iter.head >= iter.tail) { int more = iter.head - iter.tail; if (!loadMore(iter)) { if (more == 0) { iter.head = iter.tail; return; } throw iter.reportError("skipFixedBytes", "unexpected end"); } iter.head += more; } } public static int updateStringCopyBound(final JsonIterator iter, final int bound) { if (bound > iter.tail - iter.head) { return iter.tail - iter.head; } else { return bound; } } public final static int readStringSlowPath(JsonIterator iter, int j) throws IOException { boolean isExpectingLowSurrogate = false; for (;;) { int bc = readByte(iter); if (bc == '"') { return j; } if (bc == '\\') { bc = readByte(iter); switch (bc) { case 'b': bc = '\b'; break; case 't': bc = '\t'; break; case 'n': bc = '\n'; break; case 'f': bc = '\f'; break; case 'r': bc = '\r'; break; case '"': case '/': case '\\': break; case 'u': bc = (IterImplString.translateHex(readByte(iter)) << 12) + (IterImplString.translateHex(readByte(iter)) << 8) + (IterImplString.translateHex(readByte(iter)) << 4) + IterImplString.translateHex(readByte(iter)); if (Character.isHighSurrogate((char) bc)) { if (isExpectingLowSurrogate) { throw new JsonException("invalid surrogate"); } else { isExpectingLowSurrogate = true; } } else if (Character.isLowSurrogate((char) bc)) { if (isExpectingLowSurrogate) { isExpectingLowSurrogate = false; } else { throw new JsonException("invalid surrogate"); } } else { if (isExpectingLowSurrogate) { throw new JsonException("invalid surrogate"); } } break; default: throw iter.reportError("readStringSlowPath", "invalid escape character: " + bc); } } else if ((bc & 0x80) != 0) { final int u2 = readByte(iter); if ((bc & 0xE0) == 0xC0) { bc = ((bc & 0x1F) << 6) + (u2 & 0x3F); } else { final int u3 = readByte(iter); if ((bc & 0xF0) == 0xE0) { bc = ((bc & 0x0F) << 12) + ((u2 & 0x3F) << 6) + (u3 & 0x3F); } else { final int u4 = readByte(iter); if ((bc & 0xF8) == 0xF0) { bc = ((bc & 0x07) << 18) + ((u2 & 0x3F) << 12) + ((u3 & 0x3F) << 6) + (u4 & 0x3F); } else { throw iter.reportError("readStringSlowPath", "invalid unicode character"); } if (bc >= 0x10000) { // check if valid unicode if (bc >= 0x110000) throw iter.reportError("readStringSlowPath", "invalid unicode character"); // split surrogates final int sup = bc - 0x10000; if (iter.reusableChars.length == j) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } iter.reusableChars[j++] = (char) ((sup >>> 10) + 0xd800); if (iter.reusableChars.length == j) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } iter.reusableChars[j++] = (char) ((sup & 0x3ff) + 0xdc00); continue; } } } } if (iter.reusableChars.length == j) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } iter.reusableChars[j++] = (char) bc; } } static long readLongSlowPath(final JsonIterator iter, long value) throws IOException { value = -value; // add negatives to avoid redundant checks for Long.MIN_VALUE on each iteration long multmin = -922337203685477580L; // limit / 10 for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { int ind = IterImplNumber.intDigits[iter.buf[i]]; if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { iter.head = i; return value; } if (value < multmin) { throw iter.reportError("readLongSlowPath", "value is too large for long"); } value = (value << 3) + (value << 1) - ind; if (value >= 0) { throw iter.reportError("readLongSlowPath", "value is too large for long"); } } if (!IterImpl.loadMore(iter)) { iter.head = iter.tail; return value; } } } static int readIntSlowPath(final JsonIterator iter, int value) throws IOException { value = -value; // add negatives to avoid redundant checks for Integer.MIN_VALUE on each iteration int multmin = -214748364; // limit / 10 for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { int ind = IterImplNumber.intDigits[iter.buf[i]]; if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { iter.head = i; return value; } if (value < multmin) { throw iter.reportError("readIntSlowPath", "value is too large for int"); } value = (value << 3) + (value << 1) - ind; if (value >= 0) { throw iter.reportError("readIntSlowPath", "value is too large for int"); } } if (!IterImpl.loadMore(iter)) { iter.head = iter.tail; return value; } } } public static final double readDoubleSlowPath(final JsonIterator iter) throws IOException { try { numberChars numberChars = readNumber(iter); if (numberChars.charsLength == 0 && iter.whatIsNext() == ValueType.STRING) { String possibleInf = iter.readString(); if ("infinity".equals(possibleInf)) { return Double.POSITIVE_INFINITY; } if ("-infinity".equals(possibleInf)) { return Double.NEGATIVE_INFINITY; } throw iter.reportError("readDoubleSlowPath", "expect number but found string: " + possibleInf); } return Double.valueOf(new String(numberChars.chars, 0, numberChars.charsLength)); } catch (NumberFormatException e) { throw iter.reportError("readDoubleSlowPath", e.toString()); } } static class numberChars { char[] chars; int charsLength; boolean dotFound; } public static final numberChars readNumber(final JsonIterator iter) throws IOException { int j = 0; boolean dotFound = false; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { if (j == iter.reusableChars.length) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } byte c = iter.buf[i]; switch (c) { case '.': case 'e': case 'E': dotFound = true; // fallthrough case '-': case '+': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': iter.reusableChars[j++] = (char) c; break; default: iter.head = i; numberChars numberChars = new numberChars(); numberChars.chars = iter.reusableChars; numberChars.charsLength = j; numberChars.dotFound = dotFound; return numberChars; } } if (!IterImpl.loadMore(iter)) { iter.head = iter.tail; numberChars numberChars = new numberChars(); numberChars.chars = iter.reusableChars; numberChars.charsLength = j; numberChars.dotFound = dotFound; return numberChars; } } } static final double readDouble(final JsonIterator iter) throws IOException { return readDoubleSlowPath(iter); } static final long readLong(final JsonIterator iter, final byte c) throws IOException { long ind = IterImplNumber.intDigits[c]; if (ind == 0) { assertNotLeadingZero(iter); return 0; } if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { throw iter.reportError("readLong", "expect 0~9"); } return IterImplForStreaming.readLongSlowPath(iter, ind); } static final int readInt(final JsonIterator iter, final byte c) throws IOException { int ind = IterImplNumber.intDigits[c]; if (ind == 0) { assertNotLeadingZero(iter); return 0; } if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { throw iter.reportError("readInt", "expect 0~9"); } return IterImplForStreaming.readIntSlowPath(iter, ind); } static void assertNotLeadingZero(JsonIterator iter) throws IOException { try { byte nextByte = IterImpl.readByte(iter); iter.unreadByte(); int ind2 = IterImplNumber.intDigits[nextByte]; if (ind2 == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { return; } throw iter.reportError("assertNotLeadingZero", "leading zero is invalid"); } catch (ArrayIndexOutOfBoundsException e) { iter.head = iter.tail; return; } } }
src/main/java/com/jsoniter/IterImplForStreaming.java
package com.jsoniter; import com.jsoniter.any.Any; import com.jsoniter.spi.JsonException; import com.jsoniter.spi.Slice; import java.io.IOException; class IterImplForStreaming { public static final int readObjectFieldAsHash(JsonIterator iter) throws IOException { if (nextToken(iter) != '"') { throw iter.reportError("readObjectFieldAsHash", "expect \""); } long hash = 0x811c9dc5; for (; ; ) { byte c = 0; int i = iter.head; for (; i < iter.tail; i++) { c = iter.buf[i]; if (c == '"') { break; } hash ^= c; hash *= 0x1000193; } if (c == '"') { iter.head = i + 1; if (nextToken(iter) != ':') { throw iter.reportError("readObjectFieldAsHash", "expect :"); } return (int) hash; } if (!loadMore(iter)) { throw iter.reportError("readObjectFieldAsHash", "unmatched quote"); } } } public static final Slice readObjectFieldAsSlice(JsonIterator iter) throws IOException { Slice field = readSlice(iter); boolean notCopied = field != null; if (CodegenAccess.skipWhitespacesWithoutLoadMore(iter)) { if (notCopied) { int len = field.tail() - field.head(); byte[] newBuf = new byte[len]; System.arraycopy(field.data(), field.head(), newBuf, 0, len); field.reset(newBuf, 0, newBuf.length); } if (!loadMore(iter)) { throw iter.reportError("readObjectFieldAsSlice", "expect : after object field"); } } if (iter.buf[iter.head] != ':') { throw iter.reportError("readObjectFieldAsSlice", "expect : after object field"); } iter.head++; return field; } final static void skipArray(JsonIterator iter) throws IOException { int level = 1; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { switch (iter.buf[i]) { case '"': // If inside string, skip it iter.head = i + 1; skipString(iter); i = iter.head - 1; // it will be i++ soon break; case '[': // If open symbol, increase level level++; break; case ']': // If close symbol, increase level level--; // If we have returned to the original level, we're done if (level == 0) { iter.head = i + 1; return; } break; } } if (!loadMore(iter)) { return; } } } final static void skipObject(JsonIterator iter) throws IOException { int level = 1; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { switch (iter.buf[i]) { case '"': // If inside string, skip it iter.head = i + 1; skipString(iter); i = iter.head - 1; // it will be i++ soon break; case '{': // If open symbol, increase level level++; break; case '}': // If close symbol, increase level level--; // If we have returned to the original level, we're done if (level == 0) { iter.head = i + 1; return; } break; } } if (!loadMore(iter)) { return; } } } final static void skipString(JsonIterator iter) throws IOException { for (; ; ) { int end = IterImplSkip.findStringEnd(iter); if (end == -1) { int j = iter.tail - 1; boolean escaped = true; // can not just look the last byte is \ // because it could be \\ or \\\ for (; ; ) { // walk backward until head if (j < iter.head || iter.buf[j] != '\\') { // even number of backslashes // either end of buffer, or " found escaped = false; break; } j--; if (j < iter.head || iter.buf[j] != '\\') { // odd number of backslashes // it is \" or \\\" break; } j--; } if (!loadMore(iter)) { throw iter.reportError("skipString", "incomplete string"); } if (escaped) { iter.head = 1; // skip the first char as last char is \ } } else { iter.head = end; return; } } } final static void skipUntilBreak(JsonIterator iter) throws IOException { // true, false, null, number for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { byte c = iter.buf[i]; if (IterImplSkip.breaks[c]) { iter.head = i; return; } } if (!loadMore(iter)) { iter.head = iter.tail; return; } } } final static boolean skipNumber(JsonIterator iter) throws IOException { // true, false, null, number boolean dotFound = false; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { byte c = iter.buf[i]; if (c == '.' || c == 'e' || c == 'E') { dotFound = true; continue; } if (IterImplSkip.breaks[c]) { iter.head = i; return dotFound; } } if (!loadMore(iter)) { iter.head = iter.tail; return dotFound; } } } // read the bytes between " " final static Slice readSlice(JsonIterator iter) throws IOException { if (IterImpl.nextToken(iter) != '"') { throw iter.reportError("readSlice", "expect \" for string"); } int end = IterImplString.findSliceEnd(iter); if (end != -1) { // reuse current buffer iter.reusableSlice.reset(iter.buf, iter.head, end - 1); iter.head = end; return iter.reusableSlice; } // TODO: avoid small memory allocation byte[] part1 = new byte[iter.tail - iter.head]; System.arraycopy(iter.buf, iter.head, part1, 0, part1.length); for (; ; ) { if (!loadMore(iter)) { throw iter.reportError("readSlice", "unmatched quote"); } end = IterImplString.findSliceEnd(iter); if (end == -1) { byte[] part2 = new byte[part1.length + iter.buf.length]; System.arraycopy(part1, 0, part2, 0, part1.length); System.arraycopy(iter.buf, 0, part2, part1.length, iter.buf.length); part1 = part2; } else { byte[] part2 = new byte[part1.length + end - 1]; System.arraycopy(part1, 0, part2, 0, part1.length); System.arraycopy(iter.buf, 0, part2, part1.length, end - 1); iter.head = end; iter.reusableSlice.reset(part2, 0, part2.length); return iter.reusableSlice; } } } final static byte nextToken(JsonIterator iter) throws IOException { for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { byte c = iter.buf[i]; switch (c) { case ' ': case '\n': case '\t': case '\r': continue; default: iter.head = i + 1; return c; } } if (!loadMore(iter)) { return 0; } } } public final static boolean loadMore(JsonIterator iter) throws IOException { if (iter.in == null) { return false; } if (iter.skipStartedAt != -1) { return keepSkippedBytesThenRead(iter); } int n = iter.in.read(iter.buf); if (n < 1) { if (n == -1) { return false; } else { throw iter.reportError("loadMore", "read from input stream returned " + n); } } else { iter.head = 0; iter.tail = n; } return true; } private static boolean keepSkippedBytesThenRead(JsonIterator iter) throws IOException { int n; int offset; if (iter.skipStartedAt == 0 || iter.skipStartedAt < iter.tail / 2) { byte[] newBuf = new byte[iter.buf.length * 2]; offset = iter.tail - iter.skipStartedAt; System.arraycopy(iter.buf, iter.skipStartedAt, newBuf, 0, offset); iter.buf = newBuf; n = iter.in.read(iter.buf, offset, iter.buf.length - offset); } else { offset = iter.tail - iter.skipStartedAt; System.arraycopy(iter.buf, iter.skipStartedAt, iter.buf, 0, offset); n = iter.in.read(iter.buf, offset, iter.buf.length - offset); } iter.skipStartedAt = 0; if (n < 1) { if (n == -1) { return false; } else { throw iter.reportError("loadMore", "read from input stream returned " + n); } } else { iter.head = offset; iter.tail = offset + n; } return true; } final static byte readByte(JsonIterator iter) throws IOException { if (iter.head == iter.tail) { if (!loadMore(iter)) { throw iter.reportError("readByte", "no more to read"); } } return iter.buf[iter.head++]; } public static Any readAny(JsonIterator iter) throws IOException { // TODO: avoid small memory allocation iter.skipStartedAt = iter.head; byte c = nextToken(iter); switch (c) { case '"': skipString(iter); byte[] copied = copySkippedBytes(iter); return Any.lazyString(copied, 0, copied.length); case 't': skipFixedBytes(iter, 3); iter.skipStartedAt = -1; return Any.wrap(true); case 'f': skipFixedBytes(iter, 4); iter.skipStartedAt = -1; return Any.wrap(false); case 'n': skipFixedBytes(iter, 3); iter.skipStartedAt = -1; return Any.wrap((Object) null); case '[': skipArray(iter); copied = copySkippedBytes(iter); return Any.lazyArray(copied, 0, copied.length); case '{': skipObject(iter); copied = copySkippedBytes(iter); return Any.lazyObject(copied, 0, copied.length); default: if (skipNumber(iter)) { copied = copySkippedBytes(iter); return Any.lazyDouble(copied, 0, copied.length); } else { copied = copySkippedBytes(iter); return Any.lazyLong(copied, 0, copied.length); } } } private static byte[] copySkippedBytes(JsonIterator iter) { int start = iter.skipStartedAt; iter.skipStartedAt = -1; int end = iter.head; byte[] bytes = new byte[end - start]; System.arraycopy(iter.buf, start, bytes, 0, bytes.length); return bytes; } public static void skipFixedBytes(JsonIterator iter, int n) throws IOException { iter.head += n; if (iter.head >= iter.tail) { int more = iter.head - iter.tail; if (!loadMore(iter)) { if (more == 0) { iter.head = iter.tail; return; } throw iter.reportError("skipFixedBytes", "unexpected end"); } iter.head += more; } } public static int updateStringCopyBound(final JsonIterator iter, final int bound) { if (bound > iter.tail - iter.head) { return iter.tail - iter.head; } else { return bound; } } public final static int readStringSlowPath(JsonIterator iter, int j) throws IOException { boolean isExpectingLowSurrogate = false; for (;;) { int bc = readByte(iter); if (bc == '"') { return j; } if (bc == '\\') { bc = readByte(iter); switch (bc) { case 'b': bc = '\b'; break; case 't': bc = '\t'; break; case 'n': bc = '\n'; break; case 'f': bc = '\f'; break; case 'r': bc = '\r'; break; case '"': case '/': case '\\': break; case 'u': bc = (IterImplString.translateHex(readByte(iter)) << 12) + (IterImplString.translateHex(readByte(iter)) << 8) + (IterImplString.translateHex(readByte(iter)) << 4) + IterImplString.translateHex(readByte(iter)); if (Character.isHighSurrogate((char) bc)) { if (isExpectingLowSurrogate) { throw new JsonException("invalid surrogate"); } else { isExpectingLowSurrogate = true; } } else if (Character.isLowSurrogate((char) bc)) { if (isExpectingLowSurrogate) { isExpectingLowSurrogate = false; } else { throw new JsonException("invalid surrogate"); } } else { if (isExpectingLowSurrogate) { throw new JsonException("invalid surrogate"); } } break; default: throw iter.reportError("readStringSlowPath", "invalid escape character: " + bc); } } else if ((bc & 0x80) != 0) { final int u2 = readByte(iter); if ((bc & 0xE0) == 0xC0) { bc = ((bc & 0x1F) << 6) + (u2 & 0x3F); } else { final int u3 = readByte(iter); if ((bc & 0xF0) == 0xE0) { bc = ((bc & 0x0F) << 12) + ((u2 & 0x3F) << 6) + (u3 & 0x3F); } else { final int u4 = readByte(iter); if ((bc & 0xF8) == 0xF0) { bc = ((bc & 0x07) << 18) + ((u2 & 0x3F) << 12) + ((u3 & 0x3F) << 6) + (u4 & 0x3F); } else { throw iter.reportError("readStringSlowPath", "invalid unicode character"); } if (bc >= 0x10000) { // check if valid unicode if (bc >= 0x110000) throw iter.reportError("readStringSlowPath", "invalid unicode character"); // split surrogates final int sup = bc - 0x10000; if (iter.reusableChars.length == j) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } iter.reusableChars[j++] = (char) ((sup >>> 10) + 0xd800); if (iter.reusableChars.length == j) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } iter.reusableChars[j++] = (char) ((sup & 0x3ff) + 0xdc00); continue; } } } } if (iter.reusableChars.length == j) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } iter.reusableChars[j++] = (char) bc; } } static long readLongSlowPath(final JsonIterator iter, long value) throws IOException { value = -value; // add negatives to avoid redundant checks for Long.MIN_VALUE on each iteration long multmin = -922337203685477580L; // limit / 10 for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { int ind = IterImplNumber.intDigits[iter.buf[i]]; if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { iter.head = i; return value; } if (value < multmin) { throw iter.reportError("readLongSlowPath", "value is too large for long"); } value = (value << 3) + (value << 1) - ind; if (value >= 0) { throw iter.reportError("readLongSlowPath", "value is too large for long"); } } if (!IterImpl.loadMore(iter)) { iter.head = iter.tail; return value; } } } static int readIntSlowPath(final JsonIterator iter, int value) throws IOException { value = -value; // add negatives to avoid redundant checks for Integer.MIN_VALUE on each iteration int multmin = -214748364; // limit / 10 for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { int ind = IterImplNumber.intDigits[iter.buf[i]]; if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { iter.head = i; return value; } if (value < multmin) { throw iter.reportError("readIntSlowPath", "value is too large for int"); } value = (value << 3) + (value << 1) - ind; if (value >= 0) { throw iter.reportError("readIntSlowPath", "value is too large for int"); } } if (!IterImpl.loadMore(iter)) { iter.head = iter.tail; return value; } } } public static final double readDoubleSlowPath(final JsonIterator iter) throws IOException { try { numberChars numberChars = readNumber(iter); if (numberChars.charsLength == 0 && iter.whatIsNext() == ValueType.STRING) { String possibleInf = iter.readString(); if ("infinity".equals(possibleInf)) { return Double.POSITIVE_INFINITY; } if ("-infinity".equals(possibleInf)) { return Double.NEGATIVE_INFINITY; } throw iter.reportError("readDoubleSlowPath", "expect number but found string: " + possibleInf); } return Double.valueOf(new String(numberChars.chars, 0, numberChars.charsLength)); } catch (NumberFormatException e) { throw iter.reportError("readDoubleSlowPath", e.toString()); } } static class numberChars { char[] chars; int charsLength; boolean dotFound; } public static final numberChars readNumber(final JsonIterator iter) throws IOException { int j = 0; boolean dotFound = false; for (; ; ) { for (int i = iter.head; i < iter.tail; i++) { if (j == iter.reusableChars.length) { char[] newBuf = new char[iter.reusableChars.length * 2]; System.arraycopy(iter.reusableChars, 0, newBuf, 0, iter.reusableChars.length); iter.reusableChars = newBuf; } byte c = iter.buf[i]; switch (c) { case '.': case 'e': case 'E': dotFound = true; // fallthrough case '-': case '+': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': iter.reusableChars[j++] = (char) c; break; default: iter.head = i; numberChars numberChars = new numberChars(); numberChars.chars = iter.reusableChars; numberChars.charsLength = j; numberChars.dotFound = dotFound; return numberChars; } } if (!IterImpl.loadMore(iter)) { iter.head = iter.tail; numberChars numberChars = new numberChars(); numberChars.chars = iter.reusableChars; numberChars.charsLength = j; numberChars.dotFound = dotFound; return numberChars; } } } static final double readDouble(final JsonIterator iter) throws IOException { return readDoubleSlowPath(iter); } static final long readLong(final JsonIterator iter, final byte c) throws IOException { long ind = IterImplNumber.intDigits[c]; if (ind == 0) { assertNotLeadingZero(iter); return 0; } if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { throw iter.reportError("readLong", "expect 0~9"); } return IterImplForStreaming.readLongSlowPath(iter, ind); } static final int readInt(final JsonIterator iter, final byte c) throws IOException { int ind = IterImplNumber.intDigits[c]; if (ind == 0) { assertNotLeadingZero(iter); return 0; } if (ind == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { throw iter.reportError("readInt", "expect 0~9"); } return IterImplForStreaming.readIntSlowPath(iter, ind); } static void assertNotLeadingZero(JsonIterator iter) throws IOException { try { byte nextByte = IterImpl.readByte(iter); iter.unreadByte(); int ind2 = IterImplNumber.intDigits[nextByte]; if (ind2 == IterImplNumber.INVALID_CHAR_FOR_NUMBER) { return; } throw iter.reportError("assertNotLeadingZero", "leading zero is invalid"); } catch (ArrayIndexOutOfBoundsException e) { iter.head = iter.tail; return; } } }
Rewrote part of keepSkippedBytesThenRead function to get rid of duplicity and while keeping exactly same semantics.
src/main/java/com/jsoniter/IterImplForStreaming.java
Rewrote part of keepSkippedBytesThenRead function to get rid of duplicity and while keeping exactly same semantics.
<ide><path>rc/main/java/com/jsoniter/IterImplForStreaming.java <ide> } <ide> <ide> private static boolean keepSkippedBytesThenRead(JsonIterator iter) throws IOException { <del> int n; <del> int offset; <add> int offset = iter.tail - iter.skipStartedAt; <add> byte[] srcBuffer = iter.buf; <add> // Double the size of internal buffer <add> // TODO: Fix NegativeArraySizeException that happens if source stream doesnt return as much <add> // of output as was requested i.e. when n < iter.buf.length - offset. Anyhow doubling the buffer <add> // size seems to be pretty dangerous idea and should be either disabled or solved safely. <ide> if (iter.skipStartedAt == 0 || iter.skipStartedAt < iter.tail / 2) { <del> byte[] newBuf = new byte[iter.buf.length * 2]; <del> offset = iter.tail - iter.skipStartedAt; <del> System.arraycopy(iter.buf, iter.skipStartedAt, newBuf, 0, offset); <del> iter.buf = newBuf; <del> n = iter.in.read(iter.buf, offset, iter.buf.length - offset); <del> } else { <del> offset = iter.tail - iter.skipStartedAt; <del> System.arraycopy(iter.buf, iter.skipStartedAt, iter.buf, 0, offset); <del> n = iter.in.read(iter.buf, offset, iter.buf.length - offset); <del> } <add> iter.buf = new byte[iter.buf.length * 2]; <add> } <add> System.arraycopy(srcBuffer, iter.skipStartedAt, iter.buf, 0, offset); <add> int n = iter.in.read(iter.buf, offset, iter.buf.length - offset); <ide> iter.skipStartedAt = 0; <ide> if (n < 1) { <ide> if (n == -1) {
Java
apache-2.0
dc246d2c4f9923d45f1e747cb95cdef2cc43b4a6
0
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
package info.u_team.u_team_core.util; import java.util.Random; import net.minecraft.util.math.Vec3d; public class MathUtil { public static final Random RANDOM = new Random(); public static Vec3d rotateVectorAroundYCC(Vec3d vec, double angle) { return rotateVectorCC(vec, new Vec3d(0, 1, 0), angle); } public static Vec3d rotateVectorCC(Vec3d vec, Vec3d axis, double angle) { final double x = vec.getX(); final double y = vec.getY(); final double z = vec.getZ(); final double u = axis.getX(); final double v = axis.getY(); final double w = axis.getZ(); final double rotationX = u * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + x * Math.cos(angle) + (-w * y + v * z) * Math.sin(angle); final double rotationY = v * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + y * Math.cos(angle) + (w * x - u * z) * Math.sin(angle); final double rotationZ = w * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + z * Math.cos(angle) + (-v * x + u * y) * Math.sin(angle); return new Vec3d(rotationX, rotationY, rotationZ); } public static int getRandomNumberInRange(int min, int max) { return getRandomNumberInRange(RANDOM, min, max); } public static int getRandomNumberInRange(Random random, int min, int max) { return random.nextInt(max - min + 1) + min; } public static float getRandomNumberInRange(float min, float max) { return getRandomNumberInRange(RANDOM, min, max); } public static float getRandomNumberInRange(Random random, float min, float max) { return random.nextFloat() * (max - min) + min; } public static double getRandomNumberInRange(double min, double max) { return getRandomNumberInRange(RANDOM, min, max); } public static double getRandomNumberInRange(Random random, double min, double max) { return random.nextDouble() * (max - min) + min; } /// public static int randomNumberInRange(int min, int max) { return randomNumberInRange(RANDOM, min, max); } public static int randomNumberInRange(Random random, int min, int max) { return random.nextInt(max - min + 1) + min; } public static float randomNumberInRange(float min, float max) { return randomNumberInRange(RANDOM, min, max); } public static float randomNumberInRange(Random random, float min, float max) { return random.nextFloat() * (max - min) + min; } public static double randomNumberInRange(double min, double max) { return randomNumberInRange(RANDOM, min, max); } public static double randomNumberInRange(Random random, double min, double max) { return random.nextDouble() * (max - min) + min; } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static int valueInRange(int min, int max, int value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static long valueInRange(long min, long max, long value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static float valueInRange(float min, float max, float value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static double valueInRange(double min, double max, double value) { return Math.min(max, Math.max(min, value)); } }
src/main/java/info/u_team/u_team_core/util/MathUtil.java
package info.u_team.u_team_core.util; import java.util.Random; import net.minecraft.util.math.Vec3d; public class MathUtil { public static final Random RANDOM = new Random(); public static Vec3d rotateVectorAroundYCC(Vec3d vec, double angle) { return rotateVectorCC(vec, new Vec3d(0, 1, 0), angle); } public static Vec3d rotateVectorCC(Vec3d vec, Vec3d axis, double angle) { final double x = vec.getX(); final double y = vec.getY(); final double z = vec.getZ(); final double u = axis.getX(); final double v = axis.getY(); final double w = axis.getZ(); final double rotationX = u * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + x * Math.cos(angle) + (-w * y + v * z) * Math.sin(angle); final double rotationY = v * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + y * Math.cos(angle) + (w * x - u * z) * Math.sin(angle); final double rotationZ = w * (u * x + v * y + w * z) * (1 - Math.cos(angle)) + z * Math.cos(angle) + (-v * x + u * y) * Math.sin(angle); return new Vec3d(rotationX, rotationY, rotationZ); } public static int getRandomNumberInRange(int min, int max) { return getRandomNumberInRange(RANDOM, min, max); } public static int getRandomNumberInRange(Random random, int min, int max) { return random.nextInt(max - min + 1) + min; } public static float getRandomNumberInRange(float min, float max) { return getRandomNumberInRange(RANDOM, min, max); } public static float getRandomNumberInRange(Random random, float min, float max) { return random.nextFloat() * (max - min) + min; } public static double getRandomNumberInRange(double min, double max) { return getRandomNumberInRange(RANDOM, min, max); } public static double getRandomNumberInRange(Random random, double min, double max) { return random.nextDouble() * (max - min) + min; } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static int valueInRange(int min, int max, int value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static long valueInRange(long min, long max, long value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static float valueInRange(float min, float max, float value) { return Math.min(max, Math.max(min, value)); } /** * Returns a value between min and max * * @param min Minimal value (inclusive) * @param max Maximal value (inclusive) * @param value Value that should be in range * @return Return a value between min and max */ public static double valueInRange(double min, double max, double value) { return Math.min(max, Math.max(min, value)); } }
Change method name of the randomNumerInRange and remove get
src/main/java/info/u_team/u_team_core/util/MathUtil.java
Change method name of the randomNumerInRange and remove get
<ide><path>rc/main/java/info/u_team/u_team_core/util/MathUtil.java <ide> return random.nextDouble() * (max - min) + min; <ide> } <ide> <add> /// <add> public static int randomNumberInRange(int min, int max) { <add> return randomNumberInRange(RANDOM, min, max); <add> } <add> <add> public static int randomNumberInRange(Random random, int min, int max) { <add> return random.nextInt(max - min + 1) + min; <add> } <add> <add> public static float randomNumberInRange(float min, float max) { <add> return randomNumberInRange(RANDOM, min, max); <add> } <add> <add> public static float randomNumberInRange(Random random, float min, float max) { <add> return random.nextFloat() * (max - min) + min; <add> } <add> <add> public static double randomNumberInRange(double min, double max) { <add> return randomNumberInRange(RANDOM, min, max); <add> } <add> <add> public static double randomNumberInRange(Random random, double min, double max) { <add> return random.nextDouble() * (max - min) + min; <add> } <add> <ide> /** <ide> * Returns a value between min and max <ide> *
Java
mit
b5a74e69c9661f55afc219b7cd4704663919bf6a
0
spartan55/teste3Travis
public class Bubble implements SortElements { @Override public void sortItems(Integer[] elementos) { Integer aux; for (Integer i = 0; i < elementos.length - 1; i++) { for (Integer j = 0; j < elementos.length - 1; j++) { if (elementos[j].compareTo(elementos[j + 1]) == MAIOR) { aux = elementos[j]; elementos[j] = elementos[j + 1]; elementos[j + 1] = aux; } } } } }
src/cc/engeld/Bubble.java
package cc.engeld; public class Bubble implements SortElements { @Override public void sortItems(Integer[] elementos) { Integer aux; for (Integer i = 0; i < elementos.length - 1; i++) { for (Integer j = 0; j < elementos.length - 1; j++) { if (elementos[j].compareTo(elementos[j + 1]) == MAIOR) { aux = elementos[j]; elementos[j] = elementos[j + 1]; elementos[j + 1] = aux; } } } } }
Update Bubble.java
src/cc/engeld/Bubble.java
Update Bubble.java
<ide><path>rc/cc/engeld/Bubble.java <del>package cc.engeld; <del> <ide> public class Bubble implements SortElements { <ide> <ide> @Override
Java
apache-2.0
c86116ff3f1f94a61dbc56b66a4603d840df8fb4
0
takahashikzn/indolently,takahashikzn/indolently
// Copyright 2014 takahashikzn // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package jp.root42.indolently; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; /** * common method definition for {@link Sset} / {@link Slist}. * It's name comes from "Sugared collection". * * @param <T> value type * @param <SELF> self type * @author takahashikzn * @see Slist * @see Sset */ public interface Scol<T, SELF extends Scol<T, SELF>> extends Collection<T>, Freezable<SELF>, Identical<SELF> { /** * add value then return this instance. * * @param value value to add * @return {@code this} instance */ @Destructive default SELF push(final T value) { this.add(value); return this.identity(); } /** * add all values then return this instance. * * @param values values to add * @return {@code this} instance */ @Destructive default SELF pushAll(final Iterable<? extends T> values) { for (final T val : values) { this.add(val); } return this.identity(); } /** * add value then return this instance only if value exists. * otherwise, do nothing. * * @param value nullable value to add * @return {@code this} instance */ @Destructive default SELF push(final Optional<? extends T> value) { return Indolently.empty(value) ? this.identity() : this.push(value.get()); } /** * add all values then return this instance only if values exists. * otherwise, do nothing. * * @param values nullable values to add * @return {@code this} instance */ @Destructive default SELF pushAll(final Optional<? extends Iterable<? extends T>> values) { return Indolently.empty(values) ? this.identity() : this.pushAll(values.get()); } /** * remove values then return this instance. * * @param values values to remove * @return {@code this} instance * @see #removeAll(Collection) */ @Destructive default SELF delete(final Iterable<? extends T> values) { // optimization final Collection<? extends T> vals = (values instanceof Collection) ? (Collection<? extends T>) values : Indolently.list(values); this.removeAll(vals); return this.identity(); } /** * get first value. * * @return first value * @throws NoSuchElementException if empty */ default T first() { return this.iterator().next(); } /** * get last value. * * @return first value * @throws NoSuchElementException if empty */ default T last() { for (final Iterator<T> i = this.iterator(); i.hasNext();) { if (!i.hasNext()) { return i.next(); } } throw new NoSuchElementException(); } /** * get rest of this collection. * * @return collection values except for first value. * if this instance is empty, i.e. {@code col.isEmpty()} returns true, return empty collection. */ SELF tail(); /** * internal iterator. * * @param f function * @return {@code this} instance */ default SELF each(final Consumer<? super T> f) { return this.each((idx, val) -> f.accept(val)); } /** * internal iterator. * * @param f function. first argument is loop index. * @return {@code this} instance */ default SELF each(final BiConsumer<Integer, ? super T> f) { int i = 0; for (final T val : this) { f.accept(i++, val); } return this.identity(); } /** * Test whether at least one value satisfy condition. * * @param f condition * @return test result */ default boolean some(final Predicate<? super T> f) { return !this.filter(f).isEmpty(); } /** * Test whether all values satisfy condition. * * @param f condition * @return test result */ default boolean every(final Predicate<? super T> f) { return this.filter(f).size() == this.size(); } /** * Filter operation: returns values which satisfying condition. * This operation is constructive. * * @param f condition * @return new filtered collection */ default SELF filter(final Predicate<? super T> f) { return this.filter((idx, val) -> f.test(val)); } /** * Filter operation: returns values which satisfying condition. * This operation is constructive. * * @param f condition. first argument is loop index. * @return new filtered collection */ SELF filter(BiPredicate<Integer, ? super T> f); /** * Reduce operation. * * @param f function * @return result value * @throws NoSuchElementException this collection is empty * @see #mapred(Function, BiFunction) */ default Optional<T> reduce(final BiFunction<? super T, ? super T, ? extends T> f) { return this.mapred(Function.identity(), f); } /** * Reduce operation. * * @param initial initial value * @param f function * @return result value * @see #mapred(Object, BiFunction) */ default Optional<T> reduce(final T initial, final BiFunction<? super T, ? super T, ? extends T> f) { return this.mapred(Optional.ofNullable(initial), f); } /** * Reduce operation. * * @param initial initial value * @param f function * @return result value * @see #mapred(Optional, BiFunction) */ default Optional<T> reduce(final Optional<? extends T> initial, final BiFunction<? super T, ? super T, ? extends T> f) { return this.mapred(initial, f); } /** * Map then Reduce operation. * * @param <M> mapping target type * @param fm mapper function * @param fr reducer function * @return result value * @throws NoSuchElementException this collection is empty */ default <M> Optional<M> mapred(final Function<? super T, ? extends M> fm, final BiFunction<? super M, ? super M, ? extends M> fr) { return this.tail().mapred( // fm.apply(this.first()), // (rem, val) -> fr.apply(rem, fm.apply(val))); } /** * Map then Reduce operation. * * @param <M> mapping target type * @param initial initial value * @param f function * @return result value */ default <M> Optional<M> mapred(final M initial, final BiFunction<? super M, ? super T, ? extends M> f) { return this.mapred(Optional.ofNullable(initial), f); } /** * Map then Reduce operation. * * @param <M> mapping target type * @param initial initial value * @param f function * @return result value */ default <M> Optional<M> mapred(final Optional<? extends M> initial, final BiFunction<? super M, ? super T, ? extends M> f) { M rem = Indolently.empty(initial) ? null : initial.get(); for (final T val : this) { rem = f.apply(rem, val); } return Optional.ofNullable(rem); } }
src/main/java/jp/root42/indolently/Scol.java
// Copyright 2014 takahashikzn // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package jp.root42.indolently; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; /** * common method definition for {@link Sset} / {@link Slist}. * It's name comes from "Sugared collection". * * @param <T> value type * @param <SELF> self type * @author takahashikzn * @see Slist * @see Sset */ public interface Scol<T, SELF extends Scol<T, SELF>> extends Collection<T>, Freezable<SELF>, Identical<SELF> { /** * add value then return this instance. * * @param value value to add * @return {@code this} instance */ @Destructive default SELF push(final T value) { this.add(value); return this.identity(); } /** * add all values then return this instance. * * @param values values to add * @return {@code this} instance */ @Destructive default SELF pushAll(final Iterable<? extends T> values) { for (final T val : values) { this.add(val); } return this.identity(); } /** * add value then return this instance only if value exists. * otherwise, do nothing. * * @param value nullable value to add * @return {@code this} instance */ @Destructive default SELF push(final Optional<? extends T> value) { return Indolently.empty(value) ? this.identity() : this.push(value.get()); } /** * add all values then return this instance only if values exists. * otherwise, do nothing. * * @param values nullable values to add * @return {@code this} instance */ @Destructive default SELF pushAll(final Optional<? extends Iterable<? extends T>> values) { return Indolently.empty(values) ? this.identity() : this.pushAll(values.get()); } /** * remove values then return this instance. * * @param values values to remove * @return {@code this} instance * @see #removeAll(Collection) */ @Destructive default SELF delete(final Iterable<? extends T> values) { // optimization final Collection<? extends T> vals = (values instanceof Collection) ? (Collection<? extends T>) values : Indolently.list(values); this.removeAll(vals); return this.identity(); } /** * get first value. * * @return first value * @throws NoSuchElementException if empty */ default T first() { return this.iterator().next(); } /** * get last value. * * @return first value * @throws NoSuchElementException if empty */ default T last() { for (final Iterator<T> i = this.iterator(); i.hasNext();) { if (!i.hasNext()) { return i.next(); } } throw new NoSuchElementException(); } /** * get rest of this collection. * * @return collection values except for first value. * if this instance is empty, i.e. {@code col.isEmpty()} returns true, return empty collection. */ SELF tail(); /** * internal iterator. * * @param f function * @return {@code this} instance */ default SELF each(final Consumer<? super T> f) { return this.each((idx, val) -> f.accept(val)); } /** * internal iterator. * * @param f function. first argument is loop index. * @return {@code this} instance */ default SELF each(final BiConsumer<Integer, ? super T> f) { int i = 0; for (final T val : this) { f.accept(i++, val); } return this.identity(); } /** * Test whether at least one value satisfy condition. * * @param f condition * @return test result */ default boolean some(final Predicate<? super T> f) { return !this.filter(f).isEmpty(); } /** * Test whether all values satisfy condition. * * @param f condition * @return test result */ default boolean every(final Predicate<? super T> f) { return this.filter(f).size() == this.size(); } /** * Filter operation: returns values which satisfying condition. * This operation is constructive. * * @param f condition * @return new filtered collection */ default SELF filter(final Predicate<? super T> f) { return this.filter((idx, val) -> f.test(val)); } /** * Filter operation: returns values which satisfying condition. * This operation is constructive. * * @param f condition. first argument is loop index. * @return new filtered collection */ SELF filter(BiPredicate<Integer, ? super T> f); /** * Reduce operation. * * @param f function * @return result value * @throws NoSuchElementException the collection size is less than two */ default Optional<T> reduce(final BiFunction<? super T, ? super T, ? extends T> f) { return this.mapred(Function.identity(), f); } /** * Reduce operation. * * @param initial initial value * @param f function * @return result value */ default Optional<T> reduce(final T initial, final BiFunction<? super T, ? super T, ? extends T> f) { return this.mapred(Optional.ofNullable(initial), f); } /** * Reduce operation. * * @param initial initial value * @param f function * @return result value */ default Optional<T> reduce(final Optional<? extends T> initial, final BiFunction<? super T, ? super T, ? extends T> f) { return this.mapred(initial, f); } /** * Map then Reduce operation. * * @param <M> mapping target type * @param fm mapper function * @param fr reducer function * @return result value * @throws NoSuchElementException this collection is empty */ default <M> Optional<M> mapred(final Function<? super T, ? extends M> fm, final BiFunction<? super M, ? super M, ? extends M> fr) { return this.tail().mapred( // fm.apply(this.first()), // (rem, val) -> fr.apply(rem, fm.apply(val))); } /** * Map then Reduce operation. * * @param <M> mapping target type * @param initial initial value * @param f function * @return result value */ default <M> Optional<M> mapred(final M initial, final BiFunction<? super M, ? super T, ? extends M> f) { return this.mapred(Optional.ofNullable(initial), f); } /** * Map then Reduce operation. * * @param <M> mapping target type * @param initial initial value * @param f function * @return result value */ default <M> Optional<M> mapred(final Optional<? extends M> initial, final BiFunction<? super M, ? super T, ? extends M> f) { M rem = Indolently.empty(initial) ? null : initial.get(); for (final T val : this) { rem = f.apply(rem, val); } return Optional.ofNullable(rem); } }
javadoc
src/main/java/jp/root42/indolently/Scol.java
javadoc
<ide><path>rc/main/java/jp/root42/indolently/Scol.java <ide> * <ide> * @param f function <ide> * @return result value <del> * @throws NoSuchElementException the collection size is less than two <add> * @throws NoSuchElementException this collection is empty <add> * @see #mapred(Function, BiFunction) <ide> */ <ide> default Optional<T> reduce(final BiFunction<? super T, ? super T, ? extends T> f) { <ide> return this.mapred(Function.identity(), f); <ide> * @param initial initial value <ide> * @param f function <ide> * @return result value <add> * @see #mapred(Object, BiFunction) <ide> */ <ide> default Optional<T> reduce(final T initial, final BiFunction<? super T, ? super T, ? extends T> f) { <ide> return this.mapred(Optional.ofNullable(initial), f); <ide> * @param initial initial value <ide> * @param f function <ide> * @return result value <add> * @see #mapred(Optional, BiFunction) <ide> */ <ide> default Optional<T> reduce(final Optional<? extends T> initial, <ide> final BiFunction<? super T, ? super T, ? extends T> f) {
Java
agpl-3.0
310bb378e933de6d299da0325b6e6dc4d16a24d9
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
11a249a4-2e62-11e5-9284-b827eb9e62be
hello.java
119c90b8-2e62-11e5-9284-b827eb9e62be
11a249a4-2e62-11e5-9284-b827eb9e62be
hello.java
11a249a4-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>119c90b8-2e62-11e5-9284-b827eb9e62be <add>11a249a4-2e62-11e5-9284-b827eb9e62be
Java
unlicense
error: pathspec 'src/model/ChaveAcesso.java' did not match any file(s) known to git
1a96dd497ab4f15c5a5706a56dcbf19b76d743c9
1
crisstanza/Replacer,crisstanza/Replacer,crisstanza/Replacer
package model; public final class ChaveAcesso { }
src/model/ChaveAcesso.java
One more model.
src/model/ChaveAcesso.java
One more model.
<ide><path>rc/model/ChaveAcesso.java <add>package model; <add> <add>public final class ChaveAcesso { <add> <add>}
Java
mit
974f68d85f492a70fdb6224fd057cee6b3d07778
0
uiucGSLIS/ir-tools,uiucGSLIS/ir-tools
package edu.gslis.textrepresentation; import java.util.ArrayList; import java.util.List; import java.util.Map; import lemurproject.indri.DocumentVector; import lemurproject.indri.ParsedDocument; import lemurproject.indri.QueryEnvironment; import edu.gslis.utils.Stopper; /** * Basic class for handling interactions with an indri index pertaining to an individual document * * @author Miles Efron * */ public class IndriDocument { private QueryEnvironment env; /** * constructor for the case where we know the index */ public IndriDocument(QueryEnvironment env) { this.env = env; } /** * gets the parsed text of the document. this is all nice and clean... exactly as indri stores it. * @param docID the indri-internal numeric ID of the document. i.e. not its TREC-assigned DOCNO element * @return character String containing the full text of the document * @throws Exception */ public String getDocString(int docID) { StringBuilder b = new StringBuilder(); String[] toks = getDocToks(docID); for(String tok : toks) { if(tok.equals("[OOV]")) { continue; } b = b.append(" " + tok + " "); } String docText = b.toString(); return docText.replaceAll(" ", " "); } public String[] getDocToks(int docID) { int[] inds = new int[1]; inds[0] = docID; String[] stems = null; int[] positions = null; inds[0] = docID; try{ DocumentVector[] dv = env.documentVectors(inds); stems = dv[0].stems; positions = dv[0].positions; } catch (Exception e) { e.printStackTrace(); } String[] toks = new String[positions.length]; for(int i=0; i<positions.length; i++) { toks[i] = stems[positions[i]]; } return toks; } public FeatureVector getFeatureVector(int docID, Stopper stopper) { String[] toks = getDocToks(docID); FeatureVector features = new FeatureVector(stopper); for(String tok : toks) { if(tok.equals("[OOV]")) continue; if(stopper==null) { features.addTerm(tok, 1.0); } else if(!stopper.isStopWord(tok)) features.addTerm(tok, 1.0); } return features; } /** * gets the unparsed text of the document. i.e. all formatting/tags/structure are present. the document * is exactly as it appears in the input file. * @param docID the indri-internal numeric ID of the document. i.e. not its TREC-assigned DOCNO element * @return unparsed text of the document * @throws Exception */ public String getUnparsedText(int docID) { String trecText = null; int[] id = {docID}; try { ParsedDocument[] docArray = env.documents(id); trecText = docArray[0].text; } catch (Exception e) { e.printStackTrace(); } return trecText; } /** * gets the TREC-assigned docno element for the document with this indri docID, or null if docno element isn't present. * @param docID indri-internal numeric ID of the document. i.e. not its TREC-assigned DOCNO element * @return trec DOCNO element, or null * @throws Exception */ public String getDocno(int docID) { String docno = null; int[] docIDs = {docID}; try { String[] docnos = env.documentMetadata(docIDs, "docno"); docno = docnos[0]; } catch (Exception e) { e.printStackTrace(); } return docno; } /** * gets the indri-assigned docID for the document with this TREC-assigned docno element. * @param docno TREC-assigned docno of the document. * @return indri-assigned docID, or -1 * @throws Exception */ public int getDocID(String docno) { String[] docnos = {docno}; int[] docIDs = null; try { docIDs = env.documentIDsFromMetadata("docno", docnos); } catch (Exception e) { e.printStackTrace(); } if(docIDs==null || docIDs.length==0) { System.err.println("died trying to find the docId of doc " + docno); System.exit(-1); } return docIDs[0]; } /** * * @param e the QueryEnvironment that contains the document */ public void setIndex(QueryEnvironment e) { env = e; } /** * Returns an ordered list of terms for the specified document. * @param docID * @return */ public List<String> getTerms(int docID) { List<String> terms = new ArrayList<String>(); int[] inds = new int[1]; inds[0] = docID; String[] stems = null; int[] positions = null; inds[0] = docID; try{ DocumentVector[] dv = env.documentVectors(inds); stems = dv[0].stems; positions = dv[0].positions; } catch (Exception e) { e.printStackTrace(); } for(int i=0; i<positions.length; i++) { if(stems[positions[i]].equals("[OOV]")) continue; terms.add(stems[positions[i]]); } return terms; } }
src/main/java/edu/gslis/textrepresentation/IndriDocument.java
package edu.gslis.textrepresentation; import java.util.HashMap; import java.util.Map; import lemurproject.indri.DocumentVector; import lemurproject.indri.ParsedDocument; import lemurproject.indri.QueryEnvironment; import edu.gslis.utils.Stopper; /** * Basic class for handling interactions with an indri index pertaining to an individual document * * @author Miles Efron * */ public class IndriDocument { private QueryEnvironment env; /** * constructor for the case where we know the index */ public IndriDocument(QueryEnvironment env) { this.env = env; } /** * gets the parsed text of the document. this is all nice and clean... exactly as indri stores it. * @param docID the indri-internal numeric ID of the document. i.e. not its TREC-assigned DOCNO element * @return character String containing the full text of the document * @throws Exception */ public String getDocString(int docID) { StringBuilder b = new StringBuilder(); String[] toks = getDocToks(docID); for(String tok : toks) { if(tok.equals("[OOV]")) { continue; } b = b.append(" " + tok + " "); } String docText = b.toString(); return docText.replaceAll(" ", " "); } public String[] getDocToks(int docID) { int[] inds = new int[1]; inds[0] = docID; String[] stems = null; int[] positions = null; inds[0] = docID; try{ DocumentVector[] dv = env.documentVectors(inds); stems = dv[0].stems; positions = dv[0].positions; } catch (Exception e) { e.printStackTrace(); } String[] toks = new String[positions.length]; for(int i=0; i<positions.length; i++) { toks[i] = stems[positions[i]]; } return toks; } public FeatureVector getFeatureVector(int docID, Stopper stopper) { String[] toks = getDocToks(docID); FeatureVector features = new FeatureVector(stopper); for(String tok : toks) { if(tok.equals("[OOV]")) continue; if(stopper==null) { features.addTerm(tok, 1.0); } else if(!stopper.isStopWord(tok)) features.addTerm(tok, 1.0); } return features; } /** * gets the unparsed text of the document. i.e. all formatting/tags/structure are present. the document * is exactly as it appears in the input file. * @param docID the indri-internal numeric ID of the document. i.e. not its TREC-assigned DOCNO element * @return unparsed text of the document * @throws Exception */ public String getUnparsedText(int docID) { String trecText = null; int[] id = {docID}; try { ParsedDocument[] docArray = env.documents(id); trecText = docArray[0].text; } catch (Exception e) { e.printStackTrace(); } return trecText; } /** * gets the TREC-assigned docno element for the document with this indri docID, or null if docno element isn't present. * @param docID indri-internal numeric ID of the document. i.e. not its TREC-assigned DOCNO element * @return trec DOCNO element, or null * @throws Exception */ public String getDocno(int docID) { String docno = null; int[] docIDs = {docID}; try { String[] docnos = env.documentMetadata(docIDs, "docno"); docno = docnos[0]; } catch (Exception e) { e.printStackTrace(); } return docno; } /** * gets the indri-assigned docID for the document with this TREC-assigned docno element. * @param docno TREC-assigned docno of the document. * @return indri-assigned docID, or -1 * @throws Exception */ public int getDocID(String docno) { String[] docnos = {docno}; int[] docIDs = null; try { docIDs = env.documentIDsFromMetadata("docno", docnos); } catch (Exception e) { e.printStackTrace(); } if(docIDs==null || docIDs.length==0) { System.err.println("died trying to find the docId of doc " + docno); System.exit(-1); } return docIDs[0]; } /** * * @param e the QueryEnvironment that contains the document */ public void setIndex(QueryEnvironment e) { env = e; } /** * Returns a map of positions (key) to terms for the specified document. * @param docID * @return */ public Map<Integer, String> getTermPos(int docID) { Map<Integer, String> termPos = new HashMap<Integer, String>(); int[] inds = new int[1]; inds[0] = docID; String[] stems = null; int[] positions = null; inds[0] = docID; try{ DocumentVector[] dv = env.documentVectors(inds); stems = dv[0].stems; positions = dv[0].positions; } catch (Exception e) { e.printStackTrace(); } int j = 0; for(int i=0; i<positions.length; i++) { if(stems[positions[i]].equals("[OOV]")) continue; termPos.put(j, stems[positions[i]]); j++; } return termPos; } }
Changed term positions from map to list
src/main/java/edu/gslis/textrepresentation/IndriDocument.java
Changed term positions from map to list
<ide><path>rc/main/java/edu/gslis/textrepresentation/IndriDocument.java <ide> package edu.gslis.textrepresentation; <ide> <del>import java.util.HashMap; <add>import java.util.ArrayList; <add>import java.util.List; <ide> import java.util.Map; <ide> <ide> import lemurproject.indri.DocumentVector; <ide> } <ide> <ide> /** <del> * Returns a map of positions (key) to terms for the specified document. <add> * Returns an ordered list of terms for the specified document. <ide> * @param docID <ide> * @return <ide> */ <del> public Map<Integer, String> getTermPos(int docID) { <del> Map<Integer, String> termPos = new HashMap<Integer, String>(); <add> public List<String> getTerms(int docID) { <add> List<String> terms = new ArrayList<String>(); <ide> int[] inds = new int[1]; <ide> inds[0] = docID; <ide> String[] stems = null; <ide> e.printStackTrace(); <ide> } <ide> <del> int j = 0; <ide> for(int i=0; i<positions.length; i++) { <ide> if(stems[positions[i]].equals("[OOV]")) <ide> continue; <ide> <del> termPos.put(j, stems[positions[i]]); <del> j++; <add> terms.add(stems[positions[i]]); <ide> } <del> return termPos; <add> return terms; <ide> } <ide> <ide> }
Java
epl-1.0
710ea04a3fa3d4285af498f0c805674eeea97961
0
usethesource/rascal-value
package io.usethesource.vallang.util; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentLinkedDeque; public class WeakWriteLockingHashConsingMap<T> implements HashConsingMap<T> { private static class WeakReferenceWrap<T> extends WeakReference<T> { private final int hash; public WeakReferenceWrap(int hash, T referent, ReferenceQueue<? super T> q) { super(referent, q); this.hash = hash; } @Override public int hashCode() { return hash; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { assert obj instanceof WeakReferenceWrap<?> && obj != null; @SuppressWarnings("unchecked") WeakReferenceWrap<T> wrappedObj = (WeakReferenceWrap<T>) obj; if (wrappedObj.hash == hash) { T self = get(); if (self == null) { return false; } T other = wrappedObj.get(); return other != null && self.equals(other); } return false; } } private static final class LookupWrapper<T> { private final int hash; private final T ref; public LookupWrapper(int hash, T ref) { this.hash = hash; this.ref = ref; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { // only internal use of this class assert obj instanceof WeakReferenceWrap<?> && obj != null; @SuppressWarnings("unchecked") WeakReferenceWrap<T> wrappedObj = (WeakReferenceWrap<T>) obj; if (wrappedObj.hash == hash) { T other = wrappedObj.get(); return other != null && ref.equals(other); } return false; } } private final Map<WeakReferenceWrap<T>,WeakReferenceWrap<T>> data = new HashMap<>(); private final ReferenceQueue<T> cleared = new ReferenceQueue<>(); public WeakWriteLockingHashConsingMap() { Cleanup.register(this); } @Override public T get(T key) { LookupWrapper<T> keyLookup = new LookupWrapper<>(key.hashCode(), key); @SuppressWarnings("unlikely-arg-type") WeakReferenceWrap<T> result = data.get(keyLookup); if (result != null) { T actualResult = result.get(); if (actualResult != null) { return actualResult; } } synchronized (this) { WeakReferenceWrap<T> keyPut = new WeakReferenceWrap<>(keyLookup.hash, key, cleared); while (true) { result = data.merge(keyPut, keyPut, (oldValue, newValue) -> oldValue.get() == null ? newValue : oldValue); if (result == keyPut) { // a regular put return key; } else { T actualResult = result.get(); if (actualResult != null) { // value was already in there, and also still held a reference (which is true for most cases) keyPut.clear(); // avoid getting a cleared reference in the queue return actualResult; } } } } } private void cleanup() { WeakReferenceWrap<?> c = (WeakReferenceWrap<?>) cleared.poll(); if (c != null) { synchronized (this) { while (c != null) { data.remove(c); c = (WeakReferenceWrap<?>) cleared.poll(); } } } } private static class Cleanup extends Thread { private final ConcurrentLinkedDeque<WeakReference<WeakWriteLockingHashConsingMap<?>>> caches; private Cleanup() { caches = new ConcurrentLinkedDeque<>(); setDaemon(true); setName("Cleanup Thread for " + WeakWriteLockingHashConsingMap.class.getName()); start(); } private static class InstanceHolder { static final Cleanup INSTANCE = new Cleanup(); } public static void register(WeakWriteLockingHashConsingMap<?> cache) { InstanceHolder.INSTANCE.caches.add(new WeakReference<>(cache)); } @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { return; } try { Iterator<WeakReference<WeakWriteLockingHashConsingMap<?>>> it = caches.iterator(); while (it.hasNext()) { WeakWriteLockingHashConsingMap<?> cur = it.next().get(); if (cur == null) { it.remove(); } else { cur.cleanup(); } } } catch (Throwable e) { System.err.println("Cleanup thread failed with: " + e.getMessage()); e.printStackTrace(System.err); } } } } }
src/main/java/io/usethesource/vallang/util/WeakWriteLockingHashConsingMap.java
package io.usethesource.vallang.util; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentLinkedDeque; public class WeakWriteLockingHashConsingMap<T> implements HashConsingMap<T> { private static class WeakReferenceWrap<T> extends WeakReference<T> { private final int hash; public WeakReferenceWrap(int hash, T referent, ReferenceQueue<? super T> q) { super(referent, q); this.hash = hash; } @Override public int hashCode() { return hash; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (obj == null || obj.hashCode() != hash) { return false; } T self = get(); if (self == null) { return false; } T other; if ((obj instanceof WeakReferenceWrap<?>)) { other = ((WeakReferenceWrap<T>) obj).get(); } else { other = ((LookupWrapper<T>)obj).ref; } return other != null && other.equals(self); } } private static final class LookupWrapper<T> { private final int hash; private final T ref; public LookupWrapper(int hash, T ref) { this.hash = hash; this.ref = ref; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if (obj instanceof WeakReferenceWrap<?>) { return obj.equals(this); } return false; } } private final Map<WeakReferenceWrap<T>,WeakReferenceWrap<T>> data = new HashMap<>(); private final ReferenceQueue<T> cleared = new ReferenceQueue<>(); public WeakWriteLockingHashConsingMap() { Cleanup.register(this); } @Override public T get(T key) { LookupWrapper<T> keyLookup = new LookupWrapper<>(key.hashCode(), key); @SuppressWarnings("unlikely-arg-type") WeakReferenceWrap<T> result = data.get(keyLookup); if (result != null) { T actualResult = result.get(); if (actualResult != null) { return actualResult; } } synchronized (this) { WeakReferenceWrap<T> keyPut = new WeakReferenceWrap<>(keyLookup.hash, key, cleared); while (true) { result = data.merge(keyPut, keyPut, (oldValue, newValue) -> oldValue.get() == null ? newValue : oldValue); if (result == keyPut) { // a regular put return key; } else { T actualResult = result.get(); if (actualResult != null) { // value was already in there, and also still held a reference (which is true for most cases) keyPut.clear(); // avoid getting a cleared reference in the queue return actualResult; } } } } } private void cleanup() { WeakReferenceWrap<?> c = (WeakReferenceWrap<?>) cleared.poll(); if (c != null) { synchronized (this) { while (c != null) { data.remove(c); c = (WeakReferenceWrap<?>) cleared.poll(); } } } } private static class Cleanup extends Thread { private final ConcurrentLinkedDeque<WeakReference<WeakWriteLockingHashConsingMap<?>>> caches; private Cleanup() { caches = new ConcurrentLinkedDeque<>(); setDaemon(true); setName("Cleanup Thread for " + WeakWriteLockingHashConsingMap.class.getName()); start(); } private static class InstanceHolder { static final Cleanup INSTANCE = new Cleanup(); } public static void register(WeakWriteLockingHashConsingMap<?> cache) { InstanceHolder.INSTANCE.caches.add(new WeakReference<>(cache)); } @Override public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { return; } try { Iterator<WeakReference<WeakWriteLockingHashConsingMap<?>>> it = caches.iterator(); while (it.hasNext()) { WeakWriteLockingHashConsingMap<?> cur = it.next().get(); if (cur == null) { it.remove(); } else { cur.cleanup(); } } } catch (Throwable e) { System.err.println("Cleanup thread failed with: " + e.getMessage()); e.printStackTrace(System.err); } } } } }
Optimized equals method inside wrapped containers
src/main/java/io/usethesource/vallang/util/WeakWriteLockingHashConsingMap.java
Optimized equals method inside wrapped containers
<ide><path>rc/main/java/io/usethesource/vallang/util/WeakWriteLockingHashConsingMap.java <ide> public int hashCode() { <ide> return hash; <ide> } <add> <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public boolean equals(Object obj) { <del> if (obj == null || obj.hashCode() != hash) { <del> return false; <add> assert obj instanceof WeakReferenceWrap<?> && obj != null; <add> @SuppressWarnings("unchecked") <add> WeakReferenceWrap<T> wrappedObj = (WeakReferenceWrap<T>) obj; <add> if (wrappedObj.hash == hash) { <add> T self = get(); <add> if (self == null) { <add> return false; <add> } <add> T other = wrappedObj.get(); <add> return other != null && self.equals(other); <ide> } <del> T self = get(); <del> if (self == null) { <del> return false; <del> } <del> T other; <del> if ((obj instanceof WeakReferenceWrap<?>)) { <del> other = ((WeakReferenceWrap<T>) obj).get(); <del> } <del> else { <del> other = ((LookupWrapper<T>)obj).ref; <del> } <del> return other != null && other.equals(self); <add> return false; <ide> } <ide> } <ide> <ide> <ide> @Override <ide> public boolean equals(Object obj) { <del> if (obj instanceof WeakReferenceWrap<?>) { <del> return obj.equals(this); <del> } <del> return false; <add> // only internal use of this class <add> assert obj instanceof WeakReferenceWrap<?> && obj != null; <add> @SuppressWarnings("unchecked") <add> WeakReferenceWrap<T> wrappedObj = (WeakReferenceWrap<T>) obj; <add> if (wrappedObj.hash == hash) { <add> T other = wrappedObj.get(); <add> return other != null && ref.equals(other); <add> } <add> return false; <ide> } <ide> } <ide>
Java
apache-2.0
62f076f1396250260a91a803f29d09d16ebd13d6
0
prestodb/presto,prestodb/presto,prestodb/presto,prestodb/presto,prestodb/presto,prestodb/presto
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.router; import com.facebook.airlift.bootstrap.Bootstrap; import com.facebook.airlift.bootstrap.LifeCycleManager; import com.facebook.airlift.http.server.HttpServerInfo; import com.facebook.airlift.http.server.testing.TestingHttpServerModule; import com.facebook.airlift.jaxrs.JaxrsModule; import com.facebook.airlift.json.JsonCodec; import com.facebook.airlift.json.JsonModule; import com.facebook.airlift.log.Logging; import com.facebook.airlift.node.testing.TestingNodeModule; import com.facebook.presto.execution.QueryState; import com.facebook.presto.jdbc.PrestoResultSet; import com.facebook.presto.router.cluster.ClusterStatusTracker; import com.facebook.presto.server.testing.TestingPrestoServer; import com.facebook.presto.tpch.TpchPlugin; import com.google.common.collect.ImmutableList; import com.google.inject.Injector; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestClusterManager { private static final int NUM_CLUSTERS = 3; private static final int NUM_QUERIES = 7; private List<TestingPrestoServer> prestoServers; private LifeCycleManager lifeCycleManager; private HttpServerInfo httpServerInfo; private ClusterStatusTracker clusterStatusTracker; private File configFile; @BeforeClass public void setup() throws Exception { Logging.initialize(); // set up server ImmutableList.Builder builder = ImmutableList.builder(); for (int i = 0; i < NUM_CLUSTERS; ++i) { builder.add(createPrestoServer()); } prestoServers = builder.build(); configFile = getConfigFile(prestoServers); System.out.println(configFile.getAbsolutePath()); Bootstrap app = new Bootstrap( new TestingNodeModule("test"), new TestingHttpServerModule(), new JsonModule(), new JaxrsModule(true), new RouterModule()); Injector injector = app.doNotInitializeLogging().setRequiredConfigurationProperty("router.config-file", configFile.getAbsolutePath()).quiet().initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); httpServerInfo = injector.getInstance(HttpServerInfo.class); clusterStatusTracker = injector.getInstance(ClusterStatusTracker.class); } @AfterClass(alwaysRun = true) public void tearDownServer() throws Exception { for (TestingPrestoServer prestoServer : prestoServers) { prestoServer.close(); } lifeCycleManager.stop(); } @Test(enabled = false) public void testQuery() throws Exception { String sql = "SELECT row_number() OVER () n FROM tpch.tiny.orders"; for (int i = 0; i < NUM_QUERIES; ++i) { try (Connection connection = createConnection(httpServerInfo.getHttpUri()); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { long count = 0; long sum = 0; while (rs.next()) { count++; sum += rs.getLong("n"); } assertEquals(count, 15000); assertEquals(sum, (count / 2) * (1 + count)); } } sleepUninterruptibly(10, SECONDS); assertEquals(clusterStatusTracker.getAllQueryInfos().size(), NUM_QUERIES); assertQueryState(); } private void assertQueryState() throws SQLException { String sql = "SELECT query_id, state FROM system.runtime.queries"; int total = 0; for (TestingPrestoServer server : prestoServers) { try (Connection connection = createConnection(server.getBaseUrl()); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { String id = rs.unwrap(PrestoResultSet.class).getQueryId(); int count = 0; while (rs.next()) { if (!rs.getString("query_id").equals(id)) { assertEquals(QueryState.valueOf(rs.getString("state")), QueryState.FINISHED); count++; } } assertTrue(count > 0); total += count; } } assertEquals(total, NUM_QUERIES); } private static TestingPrestoServer createPrestoServer() throws Exception { TestingPrestoServer server = new TestingPrestoServer(); server.installPlugin(new TpchPlugin()); server.createCatalog("tpch", "tpch"); server.refreshNodes(); return server; } private File getConfigFile(List<TestingPrestoServer> servers) throws IOException { // setup router config file File tempFile = File.createTempFile("router", "json"); FileOutputStream fileOutputStream = new FileOutputStream(tempFile); String configTemplate = new String(Files.readAllBytes(Paths.get(getResourceFilePath("simple-router-template.json")))); fileOutputStream.write(configTemplate.replaceAll("\\$\\{SERVERS}", getClusterList(servers)).getBytes(UTF_8)); fileOutputStream.close(); return tempFile; } private static String getClusterList(List<TestingPrestoServer> servers) { JsonCodec<List<URI>> codec = JsonCodec.listJsonCodec(URI.class); return codec.toJson(servers.stream().map(TestingPrestoServer::getBaseUrl).collect(toImmutableList())); } private static Connection createConnection(URI uri) throws SQLException { String url = format("jdbc:presto://%s:%s", uri.getHost(), uri.getPort()); return DriverManager.getConnection(url, "test", null); } private String getResourceFilePath(String fileName) { return this.getClass().getClassLoader().getResource(fileName).getPath(); } }
presto-router/src/test/java/com/facebook/presto/router/TestClusterManager.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.router; import com.facebook.airlift.bootstrap.Bootstrap; import com.facebook.airlift.bootstrap.LifeCycleManager; import com.facebook.airlift.http.server.HttpServerInfo; import com.facebook.airlift.http.server.testing.TestingHttpServerModule; import com.facebook.airlift.jaxrs.JaxrsModule; import com.facebook.airlift.json.JsonCodec; import com.facebook.airlift.json.JsonModule; import com.facebook.airlift.log.Logging; import com.facebook.airlift.node.testing.TestingNodeModule; import com.facebook.presto.execution.QueryState; import com.facebook.presto.jdbc.PrestoResultSet; import com.facebook.presto.router.cluster.ClusterStatusTracker; import com.facebook.presto.server.testing.TestingPrestoServer; import com.facebook.presto.tpch.TpchPlugin; import com.google.common.collect.ImmutableList; import com.google.inject.Injector; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestClusterManager { private static final int NUM_CLUSTERS = 3; private static final int NUM_QUERIES = 7; private List<TestingPrestoServer> prestoServers; private LifeCycleManager lifeCycleManager; private HttpServerInfo httpServerInfo; private ClusterStatusTracker clusterStatusTracker; private File configFile; @BeforeClass public void setup() throws Exception { Logging.initialize(); // set up server ImmutableList.Builder builder = ImmutableList.builder(); for (int i = 0; i < NUM_CLUSTERS; ++i) { builder.add(createPrestoServer()); } prestoServers = builder.build(); configFile = getConfigFile(prestoServers); System.out.println(configFile.getAbsolutePath()); Bootstrap app = new Bootstrap( new TestingNodeModule("test"), new TestingHttpServerModule(), new JsonModule(), new JaxrsModule(true), new RouterModule()); Injector injector = app.doNotInitializeLogging().setRequiredConfigurationProperty("router.config-file", configFile.getAbsolutePath()).quiet().initialize(); lifeCycleManager = injector.getInstance(LifeCycleManager.class); httpServerInfo = injector.getInstance(HttpServerInfo.class); clusterStatusTracker = injector.getInstance(ClusterStatusTracker.class); } @AfterClass(alwaysRun = true) public void tearDownServer() throws Exception { for (TestingPrestoServer prestoServer : prestoServers) { prestoServer.close(); } lifeCycleManager.stop(); } @Test public void testQuery() throws Exception { String sql = "SELECT row_number() OVER () n FROM tpch.tiny.orders"; for (int i = 0; i < NUM_QUERIES; ++i) { try (Connection connection = createConnection(httpServerInfo.getHttpUri()); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { long count = 0; long sum = 0; while (rs.next()) { count++; sum += rs.getLong("n"); } assertEquals(count, 15000); assertEquals(sum, (count / 2) * (1 + count)); } } sleepUninterruptibly(10, SECONDS); assertEquals(clusterStatusTracker.getAllQueryInfos().size(), NUM_QUERIES); assertQueryState(); } private void assertQueryState() throws SQLException { String sql = "SELECT query_id, state FROM system.runtime.queries"; int total = 0; for (TestingPrestoServer server : prestoServers) { try (Connection connection = createConnection(server.getBaseUrl()); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql)) { String id = rs.unwrap(PrestoResultSet.class).getQueryId(); int count = 0; while (rs.next()) { if (!rs.getString("query_id").equals(id)) { assertEquals(QueryState.valueOf(rs.getString("state")), QueryState.FINISHED); count++; } } assertTrue(count > 0); total += count; } } assertEquals(total, NUM_QUERIES); } private static TestingPrestoServer createPrestoServer() throws Exception { TestingPrestoServer server = new TestingPrestoServer(); server.installPlugin(new TpchPlugin()); server.createCatalog("tpch", "tpch"); server.refreshNodes(); return server; } private File getConfigFile(List<TestingPrestoServer> servers) throws IOException { // setup router config file File tempFile = File.createTempFile("router", "json"); FileOutputStream fileOutputStream = new FileOutputStream(tempFile); String configTemplate = new String(Files.readAllBytes(Paths.get(getResourceFilePath("simple-router-template.json")))); fileOutputStream.write(configTemplate.replaceAll("\\$\\{SERVERS}", getClusterList(servers)).getBytes(UTF_8)); fileOutputStream.close(); return tempFile; } private static String getClusterList(List<TestingPrestoServer> servers) { JsonCodec<List<URI>> codec = JsonCodec.listJsonCodec(URI.class); return codec.toJson(servers.stream().map(TestingPrestoServer::getBaseUrl).collect(toImmutableList())); } private static Connection createConnection(URI uri) throws SQLException { String url = format("jdbc:presto://%s:%s", uri.getHost(), uri.getPort()); return DriverManager.getConnection(url, "test", null); } private String getResourceFilePath(String fileName) { return this.getClass().getClassLoader().getResource(fileName).getPath(); } }
Disable Presto router's flaky test
presto-router/src/test/java/com/facebook/presto/router/TestClusterManager.java
Disable Presto router's flaky test
<ide><path>resto-router/src/test/java/com/facebook/presto/router/TestClusterManager.java <ide> lifeCycleManager.stop(); <ide> } <ide> <del> @Test <add> @Test(enabled = false) <ide> public void testQuery() <ide> throws Exception <ide> {
Java
apache-2.0
a764864a1d5c03e35422feb480417e9b4e13c2d5
0
wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia
package org.wikipedia.page.bottomcontent; import android.app.Activity; import android.content.Context; import android.graphics.Paint; import android.net.Uri; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; import org.wikipedia.Constants; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.analytics.SuggestedPagesFunnel; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.dataclient.ServiceFactory; import org.wikipedia.dataclient.restbase.page.RbPageSummary; import org.wikipedia.history.HistoryEntry; import org.wikipedia.page.Namespace; import org.wikipedia.page.Page; import org.wikipedia.page.PageContainerLongPressHandler; import org.wikipedia.page.PageFragment; import org.wikipedia.page.PageTitle; import org.wikipedia.readinglist.ReadingListBookmarkMenu; import org.wikipedia.readinglist.database.ReadingList; import org.wikipedia.readinglist.database.ReadingListDbHelper; import org.wikipedia.readinglist.database.ReadingListPage; import org.wikipedia.util.DimenUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.GeoUtil; import org.wikipedia.util.L10nUtil; import org.wikipedia.util.StringUtil; import org.wikipedia.util.log.L; import org.wikipedia.views.ConfigurableTextView; import org.wikipedia.views.LinearLayoutOverWebView; import org.wikipedia.views.ObservableWebView; import org.wikipedia.views.PageItemView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import static org.wikipedia.Constants.InvokeSource.READ_MORE_BOOKMARK_BUTTON; import static org.wikipedia.util.L10nUtil.formatDateRelative; import static org.wikipedia.util.L10nUtil.getStringForArticleLanguage; import static org.wikipedia.util.L10nUtil.setConditionalLayoutDirection; import static org.wikipedia.util.UriUtil.visitInExternalBrowser; public class BottomContentView extends LinearLayoutOverWebView implements ObservableWebView.OnScrollChangeListener, ObservableWebView.OnContentHeightChangedListener { private PageFragment parentFragment; private WebView webView; private boolean firstTimeShown = false; private boolean webViewPadded = false; private int prevLayoutHeight; private Page page; @BindView(R.id.page_languages_container) View pageLanguagesContainer; @BindView(R.id.page_languages_divider) View pageLanguagesDivider; @BindView(R.id.page_languages_count_text) TextView pageLanguagesCount; @BindView(R.id.page_edit_history_container) View pageEditHistoryContainer; @BindView(R.id.page_edit_history_divider) View pageEditHistoryDivider; @BindView(R.id.page_last_updated_text) TextView pageLastUpdatedText; @BindView(R.id.page_talk_container) View pageTalkContainer; @BindView(R.id.page_talk_divider) View pageTalkDivider; @BindView(R.id.page_view_map_container) View pageMapContainer; @BindView(R.id.page_license_text) TextView pageLicenseText; @BindView(R.id.page_external_link) TextView pageExternalLink; @BindView(R.id.read_more_container) View readMoreContainer; @BindView(R.id.read_more_list) ListView readMoreList; private SuggestedPagesFunnel funnel; private ReadMoreAdapter readMoreAdapter = new ReadMoreAdapter(); private List<RbPageSummary> readMoreItems; private CommunicationBridge bridge; private CompositeDisposable disposables = new CompositeDisposable(); public BottomContentView(Context context) { super(context); init(); } public BottomContentView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BottomContentView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { inflate(getContext(), R.layout.fragment_page_bottom_content, this); ButterKnife.bind(this); } public void setup(PageFragment parentFragment, CommunicationBridge bridge, ObservableWebView webview) { this.parentFragment = parentFragment; this.webView = webview; this.bridge = bridge; setWebView(webview); webview.addOnScrollChangeListener(this); webview.addOnContentHeightChangedListener(this); pageExternalLink.setPaintFlags(pageExternalLink.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); if (parentFragment.callback() != null) { org.wikipedia.LongPressHandler.ListViewOverflowMenuListener overflowMenuListener = new LongPressHandler(parentFragment); new org.wikipedia.LongPressHandler(readMoreList, HistoryEntry.SOURCE_INTERNAL_LINK, overflowMenuListener); } addOnLayoutChangeListener((View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) -> { if (prevLayoutHeight == getHeight()) { if (!webViewPadded) { padWebView(); } return; } prevLayoutHeight = getHeight(); padWebView(); }); readMoreList.setAdapter(readMoreAdapter); // hide ourselves by default hide(); } public void dispose() { disposables.clear(); } public void setPage(@NonNull Page page) { this.page = page; funnel = new SuggestedPagesFunnel(WikipediaApp.getInstance()); firstTimeShown = false; webViewPadded = false; setConditionalLayoutDirection(readMoreList, page.getTitle().getWikiSite().languageCode()); setupAttribution(); setupPageButtons(); if (page.couldHaveReadMoreSection()) { preRequestReadMoreItems(); } else { hideReadMore(); } setVisibility(View.INVISIBLE); } @OnClick(R.id.page_external_link) void onExternalLinkClick(View v) { visitInExternalBrowser(parentFragment.getContext(), Uri.parse(page.getTitle().getMobileUri())); } @OnClick(R.id.page_languages_container) void onLanguagesClick(View v) { parentFragment.startLangLinksActivity(); } @OnClick(R.id.page_edit_history_container) void onEditHistoryClick(View v) { visitInExternalBrowser(parentFragment.getContext(), Uri.parse(page.getTitle().getUriForAction("history"))); } @OnClick(R.id.page_talk_container) void onTalkClick(View v) { PageTitle title = page.getTitle(); PageTitle talkPageTitle = new PageTitle("Talk", title.getPrefixedText(), title.getWikiSite()); visitInExternalBrowser(parentFragment.getContext(), Uri.parse(talkPageTitle.getMobileUri())); } @OnClick(R.id.page_view_map_container) void onViewMapClick(View v) { GeoUtil.sendGeoIntent(parentFragment.requireActivity(), page.getPageProperties().getGeo(), page.getDisplayTitle()); } @Override public void onScrollChanged(int oldScrollY, int scrollY, boolean isHumanScroll) { if (getVisibility() == View.GONE) { return; } int contentHeight = (int)(webView.getContentHeight() * DimenUtil.getDensityScalar()); int bottomOffset = contentHeight - scrollY - webView.getHeight(); int bottomHeight = getHeight(); if (bottomOffset > bottomHeight) { setTranslationY(bottomHeight); if (getVisibility() != View.INVISIBLE) { setVisibility(View.INVISIBLE); } } else { setTranslationY(bottomOffset); if (getVisibility() != View.VISIBLE) { setVisibility(View.VISIBLE); } if (!firstTimeShown && readMoreItems != null) { firstTimeShown = true; readMoreAdapter.notifyDataSetChanged(); funnel.logSuggestionsShown(page.getTitle(), readMoreItems); } } } @Override public void onContentHeightChanged(int contentHeight) { perturb(); } /** * Hide the bottom content entirely. * It can only be shown again by calling beginLayout() */ public void hide() { setVisibility(View.GONE); } private void perturb() { webView.post(() -> { if (!parentFragment.isAdded()) { return; } // trigger a manual scroll event to update our position relative to the WebView. onScrollChanged(webView.getScrollY(), webView.getScrollY(), false); }); } private void padWebView() { // pad the bottom of the webview, to make room for ourselves JSONObject payload = new JSONObject(); try { payload.put("paddingBottom", (int)((getHeight() + getResources().getDimension(R.dimen.bottom_toolbar_height)) / DimenUtil.getDensityScalar())); } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("setPaddingBottom", payload); webViewPadded = true; // ^ sending the padding event will guarantee a ContentHeightChanged event to be triggered, // which will update our margin based on the scroll offset, so we don't need to do it here. // And while we wait, let's make ourselves invisible, until we're made explicitly visible // by the scroll handler. setVisibility(View.INVISIBLE); } private void setupPageButtons() { // Don't display edit history for main page or file pages, because it's always wrong pageEditHistoryContainer.setVisibility((page.isMainPage() || page.isFilePage()) ? GONE : VISIBLE); pageLastUpdatedText.setText(parentFragment.getString(R.string.last_updated_text, formatDateRelative(page.getPageProperties().getLastModified()))); pageLastUpdatedText.setVisibility(View.VISIBLE); pageTalkContainer.setVisibility(page.getTitle().namespace() == Namespace.TALK ? GONE : VISIBLE); /** * TODO: It only updates the count when the article is in Chinese. * If an article is also available in Chinese, the count will be less one. * @see LangLinksActivity.java updateLanguageEntriesSupported() */ int getLanguageCount = L10nUtil.getUpdatedLanguageCountIfNeeded(page.getTitle().getWikiSite().languageCode(), page.getPageProperties().getLanguageCount()); pageLanguagesContainer.setVisibility(getLanguageCount == 0 ? GONE : VISIBLE); pageLanguagesCount.setText(parentFragment.getString(R.string.language_count_link_text, getLanguageCount)); pageMapContainer.setVisibility(page.getPageProperties().getGeo() == null ? GONE : VISIBLE); pageLanguagesDivider.setVisibility(pageLanguagesContainer.getVisibility()); pageTalkDivider.setVisibility(pageMapContainer.getVisibility()); } private void setupAttribution() { pageLicenseText.setText(StringUtil.fromHtml(String .format(parentFragment.getContext().getString(R.string.content_license_html), parentFragment.getContext().getString(R.string.cc_by_sa_3_url)))); pageLicenseText.setMovementMethod(new LinkMovementMethod()); } private void preRequestReadMoreItems() { if (page.isMainPage()) { disposables.add(Observable.fromCallable(new MainPageReadMoreTopicTask()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::requestReadMoreItems, throwable -> { L.w("Error while getting Read More topic for main page.", throwable); requestReadMoreItems(null); })); } else { requestReadMoreItems(new HistoryEntry(page.getTitle(), HistoryEntry.SOURCE_INTERNAL_LINK)); } } private void requestReadMoreItems(final HistoryEntry entry) { if (entry == null || TextUtils.isEmpty(entry.getTitle().getPrefixedText())) { hideReadMore(); return; } final long timeMillis = System.currentTimeMillis(); disposables.add(ServiceFactory.getRest(entry.getTitle().getWikiSite()).getRelatedPages(entry.getTitle().getConvertedText()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> response.getPages(Constants.MAX_SUGGESTION_RESULTS * 2)) .subscribe(results -> { funnel.setLatency(System.currentTimeMillis() - timeMillis); readMoreItems = results; if (readMoreItems != null && readMoreItems.size() > 0) { readMoreAdapter.setResults(results); showReadMore(); } else { // If there's no results, just hide the section hideReadMore(); } }, caught -> L.w("Error while fetching Read More titles.", caught))); } private void hideReadMore() { readMoreContainer.setVisibility(View.GONE); } private void showReadMore() { if (parentFragment.isAdded()) { ((ConfigurableTextView) readMoreContainer.findViewById(R.id.read_more_header)) .setText(getStringForArticleLanguage(parentFragment.getTitle(), R.string.read_more_section), page.getTitle().getWikiSite().languageCode()); } readMoreContainer.setVisibility(View.VISIBLE); } private class LongPressHandler extends PageContainerLongPressHandler implements org.wikipedia.LongPressHandler.ListViewOverflowMenuListener { private int lastPosition; LongPressHandler(@NonNull PageFragment fragment) { super(fragment); } @Override public PageTitle getTitleForListPosition(int position) { lastPosition = position; return ((RbPageSummary) readMoreList.getAdapter().getItem(position)).getPageTitle(page.getTitle().getWikiSite()); } @Override public void onOpenLink(PageTitle title, HistoryEntry entry) { super.onOpenLink(title, entry); funnel.logSuggestionClicked(page.getTitle(), readMoreItems, lastPosition); } @Override public void onOpenInNewTab(PageTitle title, HistoryEntry entry) { super.onOpenInNewTab(title, entry); funnel.logSuggestionClicked(page.getTitle(), readMoreItems, lastPosition); } } private final class ReadMoreAdapter extends BaseAdapter implements PageItemView.Callback<RbPageSummary> { private List<RbPageSummary> results; public void setResults(List<RbPageSummary> results) { this.results = results; notifyDataSetChanged(); } @Override public int getCount() { return results == null ? 0 : Math.min(results.size(), Constants.MAX_SUGGESTION_RESULTS); } @Override public RbPageSummary getItem(int position) { return results.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convView, ViewGroup parent) { PageItemView<RbPageSummary> itemView = new PageItemView<>(getContext()); RbPageSummary result = getItem(position); PageTitle pageTitle = result.getPageTitle(page.getTitle().getWikiSite()); itemView.setItem(result); final int paddingEnd = 8; itemView.setPaddingRelative(itemView.getPaddingStart(), itemView.getPaddingTop(), DimenUtil.roundedDpToPx(paddingEnd), itemView.getPaddingBottom()); itemView.setCallback(this); itemView.setTitle(pageTitle.getDisplayText()); itemView.setDescription(StringUtils.capitalize(pageTitle.getDescription())); itemView.setImageUrl(pageTitle.getThumbUrl()); return itemView; } @Override public void onClick(@Nullable RbPageSummary item) { PageTitle title = item.getPageTitle(page.getTitle().getWikiSite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); parentFragment.loadPage(title, historyEntry); funnel.logSuggestionClicked(page.getTitle(), readMoreItems, results.indexOf(item)); } @Override public void onActionClick(@Nullable RbPageSummary item, @NonNull View view) { if (item == null) { return; } PageTitle pageTitle = item.getPageTitle(page.getTitle().getWikiSite()); disposables.add(Observable.fromCallable(() -> ReadingListDbHelper.instance().findPageInAnyList(pageTitle) != null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(pageInList -> { if (!pageInList) { parentFragment.addToReadingList(pageTitle, READ_MORE_BOOKMARK_BUTTON); } else { new ReadingListBookmarkMenu(view, new ReadingListBookmarkMenu.Callback() { @Override public void onAddRequest(@Nullable ReadingListPage page) { parentFragment.addToReadingList(pageTitle, READ_MORE_BOOKMARK_BUTTON); } @Override public void onDeleted(@Nullable ReadingListPage page) { FeedbackUtil.showMessage((Activity) getContext(), getContext().getString(R.string.reading_list_item_deleted, pageTitle.getDisplayText())); } @Override public void onShare() { // ignore } }).show(pageTitle); } }, L::w)); } @Override public boolean onLongClick(@Nullable RbPageSummary item) { return false; } @Override public void onThumbClick(@Nullable RbPageSummary item) { } @Override public void onSecondaryActionClick(@Nullable RbPageSummary item, @NonNull View view) { } @Override public void onListChipClick(@Nullable ReadingList readingList) { } } }
app/src/main/java/org/wikipedia/page/bottomcontent/BottomContentView.java
package org.wikipedia.page.bottomcontent; import android.app.Activity; import android.content.Context; import android.graphics.Paint; import android.net.Uri; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; import org.wikipedia.Constants; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.analytics.SuggestedPagesFunnel; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.dataclient.ServiceFactory; import org.wikipedia.dataclient.restbase.page.RbPageSummary; import org.wikipedia.history.HistoryEntry; import org.wikipedia.page.Namespace; import org.wikipedia.page.Page; import org.wikipedia.page.PageContainerLongPressHandler; import org.wikipedia.page.PageFragment; import org.wikipedia.page.PageTitle; import org.wikipedia.readinglist.ReadingListBookmarkMenu; import org.wikipedia.readinglist.database.ReadingList; import org.wikipedia.readinglist.database.ReadingListDbHelper; import org.wikipedia.readinglist.database.ReadingListPage; import org.wikipedia.util.DimenUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.GeoUtil; import org.wikipedia.util.L10nUtil; import org.wikipedia.util.StringUtil; import org.wikipedia.util.log.L; import org.wikipedia.views.ConfigurableTextView; import org.wikipedia.views.LinearLayoutOverWebView; import org.wikipedia.views.ObservableWebView; import org.wikipedia.views.PageItemView; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import static org.wikipedia.Constants.InvokeSource.READ_MORE_BOOKMARK_BUTTON; import static org.wikipedia.util.L10nUtil.formatDateRelative; import static org.wikipedia.util.L10nUtil.getStringForArticleLanguage; import static org.wikipedia.util.L10nUtil.setConditionalLayoutDirection; import static org.wikipedia.util.UriUtil.visitInExternalBrowser; public class BottomContentView extends LinearLayoutOverWebView implements ObservableWebView.OnScrollChangeListener, ObservableWebView.OnContentHeightChangedListener { private PageFragment parentFragment; private WebView webView; private boolean firstTimeShown = false; private boolean webViewPadded = false; private int prevLayoutHeight; private Page page; @BindView(R.id.page_languages_container) View pageLanguagesContainer; @BindView(R.id.page_languages_divider) View pageLanguagesDivider; @BindView(R.id.page_languages_count_text) TextView pageLanguagesCount; @BindView(R.id.page_edit_history_container) View pageEditHistoryContainer; @BindView(R.id.page_edit_history_divider) View pageEditHistoryDivider; @BindView(R.id.page_last_updated_text) TextView pageLastUpdatedText; @BindView(R.id.page_talk_container) View pageTalkContainer; @BindView(R.id.page_talk_divider) View pageTalkDivider; @BindView(R.id.page_view_map_container) View pageMapContainer; @BindView(R.id.page_license_text) TextView pageLicenseText; @BindView(R.id.page_external_link) TextView pageExternalLink; @BindView(R.id.read_more_container) View readMoreContainer; @BindView(R.id.read_more_list) ListView readMoreList; private SuggestedPagesFunnel funnel; private ReadMoreAdapter readMoreAdapter = new ReadMoreAdapter(); private List<RbPageSummary> readMoreItems; private CommunicationBridge bridge; private CompositeDisposable disposables = new CompositeDisposable(); public BottomContentView(Context context) { super(context); init(); } public BottomContentView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BottomContentView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { inflate(getContext(), R.layout.fragment_page_bottom_content, this); ButterKnife.bind(this); } public void setup(PageFragment parentFragment, CommunicationBridge bridge, ObservableWebView webview) { this.parentFragment = parentFragment; this.webView = webview; this.bridge = bridge; setWebView(webview); webview.addOnScrollChangeListener(this); webview.addOnContentHeightChangedListener(this); pageExternalLink.setPaintFlags(pageExternalLink.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); if (parentFragment.callback() != null) { org.wikipedia.LongPressHandler.ListViewOverflowMenuListener overflowMenuListener = new LongPressHandler(parentFragment); new org.wikipedia.LongPressHandler(readMoreList, HistoryEntry.SOURCE_INTERNAL_LINK, overflowMenuListener); } addOnLayoutChangeListener((View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) -> { if (prevLayoutHeight == getHeight()) { if (!webViewPadded) { padWebView(); } return; } prevLayoutHeight = getHeight(); padWebView(); }); readMoreList.setAdapter(readMoreAdapter); // hide ourselves by default hide(); } public void dispose() { disposables.clear(); } public void setPage(@NonNull Page page) { this.page = page; funnel = new SuggestedPagesFunnel(WikipediaApp.getInstance()); firstTimeShown = false; webViewPadded = false; setConditionalLayoutDirection(readMoreList, page.getTitle().getWikiSite().languageCode()); setupAttribution(); setupPageButtons(); if (page.couldHaveReadMoreSection()) { preRequestReadMoreItems(); } else { hideReadMore(); } setVisibility(View.INVISIBLE); } @OnClick(R.id.page_external_link) void onExternalLinkClick(View v) { visitInExternalBrowser(parentFragment.getContext(), Uri.parse(page.getTitle().getMobileUri())); } @OnClick(R.id.page_languages_container) void onLanguagesClick(View v) { parentFragment.startLangLinksActivity(); } @OnClick(R.id.page_edit_history_container) void onEditHistoryClick(View v) { visitInExternalBrowser(parentFragment.getContext(), Uri.parse(page.getTitle().getUriForAction("history"))); } @OnClick(R.id.page_talk_container) void onTalkClick(View v) { PageTitle title = page.getTitle(); PageTitle talkPageTitle = new PageTitle("Talk", title.getPrefixedText(), title.getWikiSite()); visitInExternalBrowser(parentFragment.getContext(), Uri.parse(talkPageTitle.getMobileUri())); } @OnClick(R.id.page_view_map_container) void onViewMapClick(View v) { GeoUtil.sendGeoIntent(parentFragment.requireActivity(), page.getPageProperties().getGeo(), page.getDisplayTitle()); } @Override public void onScrollChanged(int oldScrollY, int scrollY, boolean isHumanScroll) { if (getVisibility() == View.GONE) { return; } int contentHeight = (int)(webView.getContentHeight() * DimenUtil.getDensityScalar()); int bottomOffset = contentHeight - scrollY - webView.getHeight(); int bottomHeight = getHeight(); if (bottomOffset > bottomHeight) { setTranslationY(bottomHeight); if (getVisibility() != View.INVISIBLE) { setVisibility(View.INVISIBLE); } } else { setTranslationY(bottomOffset); if (getVisibility() != View.VISIBLE) { setVisibility(View.VISIBLE); } if (!firstTimeShown && readMoreItems != null) { firstTimeShown = true; readMoreAdapter.notifyDataSetChanged(); funnel.logSuggestionsShown(page.getTitle(), readMoreItems); } } } @Override public void onContentHeightChanged(int contentHeight) { perturb(); } /** * Hide the bottom content entirely. * It can only be shown again by calling beginLayout() */ public void hide() { setVisibility(View.GONE); } private void perturb() { webView.post(() -> { if (!parentFragment.isAdded()) { return; } // trigger a manual scroll event to update our position relative to the WebView. onScrollChanged(webView.getScrollY(), webView.getScrollY(), false); }); } private void padWebView() { // pad the bottom of the webview, to make room for ourselves JSONObject payload = new JSONObject(); try { payload.put("paddingBottom", (int)((getHeight() + getResources().getDimension(R.dimen.bottom_toolbar_height)) / DimenUtil.getDensityScalar())); } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("setPaddingBottom", payload); webViewPadded = true; // ^ sending the padding event will guarantee a ContentHeightChanged event to be triggered, // which will update our margin based on the scroll offset, so we don't need to do it here. // And while we wait, let's make ourselves invisible, until we're made explicitly visible // by the scroll handler. setVisibility(View.INVISIBLE); } private void setupPageButtons() { // Don't display edit history for main page or file pages, because it's always wrong pageEditHistoryContainer.setVisibility((page.isMainPage() || page.isFilePage()) ? GONE : VISIBLE); pageLastUpdatedText.setText(parentFragment.getString(R.string.last_updated_text, formatDateRelative(page.getPageProperties().getLastModified()))); pageLastUpdatedText.setVisibility(View.VISIBLE); pageTalkContainer.setVisibility(page.getTitle().namespace() == Namespace.TALK ? GONE : VISIBLE); /** * TODO: It only updates the count when the article is in Chinese. * If an article is also available in Chinese, the count will be less one. * @see LangLinksActivity.java updateLanguageEntriesSupported() */ int getLanguageCount = L10nUtil.getUpdatedLanguageCountIfNeeded(page.getTitle().getWikiSite().languageCode(), page.getPageProperties().getLanguageCount()); pageLanguagesContainer.setVisibility(getLanguageCount == 0 ? GONE : VISIBLE); pageLanguagesCount.setText(parentFragment.getString(R.string.language_count_link_text, getLanguageCount)); pageMapContainer.setVisibility(page.getPageProperties().getGeo() == null ? GONE : VISIBLE); pageLanguagesDivider.setVisibility(pageLanguagesContainer.getVisibility()); pageTalkDivider.setVisibility(pageMapContainer.getVisibility()); } private void setupAttribution() { pageLicenseText.setText(StringUtil.fromHtml(String .format(parentFragment.getContext().getString(R.string.content_license_html), parentFragment.getContext().getString(R.string.cc_by_sa_3_url)))); pageLicenseText.setMovementMethod(new LinkMovementMethod()); } private void preRequestReadMoreItems() { if (page.isMainPage()) { disposables.add(Observable.fromCallable(new MainPageReadMoreTopicTask()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::requestReadMoreItems, throwable -> { L.w("Error while getting Read More topic for main page.", throwable); requestReadMoreItems(null); })); } else { requestReadMoreItems(new HistoryEntry(page.getTitle(), HistoryEntry.SOURCE_INTERNAL_LINK)); } } private void requestReadMoreItems(final HistoryEntry entry) { if (entry == null || TextUtils.isEmpty(entry.getTitle().getPrefixedText())) { hideReadMore(); return; } final long timeMillis = System.currentTimeMillis(); disposables.add(ServiceFactory.getRest(entry.getTitle().getWikiSite()).getRelatedPages(entry.getTitle().getConvertedText()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> response.getPages(Constants.MAX_SUGGESTION_RESULTS * 2)) .subscribe(results -> { funnel.setLatency(System.currentTimeMillis() - timeMillis); readMoreItems = results; if (readMoreItems != null && readMoreItems.size() > 0) { readMoreAdapter.setResults(results); showReadMore(); } else { // If there's no results, just hide the section hideReadMore(); } }, caught -> L.w("Error while fetching Read More titles.", caught))); } private void hideReadMore() { readMoreContainer.setVisibility(View.GONE); } private void showReadMore() { if (parentFragment.isAdded()) { ((ConfigurableTextView) readMoreContainer.findViewById(R.id.read_more_header)) .setText(getStringForArticleLanguage(parentFragment.getTitle(), R.string.read_more_section), page.getTitle().getWikiSite().languageCode()); } readMoreContainer.setVisibility(View.VISIBLE); } private class LongPressHandler extends PageContainerLongPressHandler implements org.wikipedia.LongPressHandler.ListViewOverflowMenuListener { private int lastPosition; LongPressHandler(@NonNull PageFragment fragment) { super(fragment); } @Override public PageTitle getTitleForListPosition(int position) { lastPosition = position; return ((RbPageSummary) readMoreList.getAdapter().getItem(position)).getPageTitle(page.getTitle().getWikiSite()); } @Override public void onOpenLink(PageTitle title, HistoryEntry entry) { super.onOpenLink(title, entry); funnel.logSuggestionClicked(page.getTitle(), readMoreItems, lastPosition); } @Override public void onOpenInNewTab(PageTitle title, HistoryEntry entry) { super.onOpenInNewTab(title, entry); funnel.logSuggestionClicked(page.getTitle(), readMoreItems, lastPosition); } } private final class ReadMoreAdapter extends BaseAdapter implements PageItemView.Callback<RbPageSummary> { private List<RbPageSummary> results; public void setResults(List<RbPageSummary> results) { this.results = results; notifyDataSetChanged(); } @Override public int getCount() { return results == null ? 0 : Math.min(results.size(), Constants.MAX_SUGGESTION_RESULTS); } @Override public RbPageSummary getItem(int position) { return results.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convView, ViewGroup parent) { PageItemView<RbPageSummary> itemView = new PageItemView<>(getContext()); RbPageSummary result = getItem(position); PageTitle pageTitle = result.getPageTitle(page.getTitle().getWikiSite()); itemView.setItem(result); final int paddingEnd = 8; itemView.setPaddingRelative(itemView.getPaddingStart(), itemView.getPaddingTop(), DimenUtil.roundedDpToPx(paddingEnd), itemView.getPaddingBottom()); itemView.setCallback(this); itemView.setTitle(pageTitle.getDisplayText()); itemView.setDescription(StringUtils.capitalize(pageTitle.getDescription())); itemView.setImageUrl(pageTitle.getThumbUrl()); return itemView; } @Override public void onClick(@Nullable RbPageSummary item) { PageTitle title = item.getPageTitle(page.getTitle().getWikiSite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); parentFragment.loadPage(title, historyEntry); funnel.logSuggestionClicked(page.getTitle(), readMoreItems, results.indexOf(item)); } @Override public void onActionClick(@Nullable RbPageSummary item, @NonNull View view) { if (item == null) { return; } PageTitle pageTitle = item.getPageTitle(page.getTitle().getWikiSite()); disposables.add(Observable.fromCallable(() -> ReadingListDbHelper.instance().findPageInAnyList(pageTitle) != null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(pageInList -> { if (!pageInList) { parentFragment.addToReadingList(pageTitle, READ_MORE_BOOKMARK_BUTTON); } else { new ReadingListBookmarkMenu(view, new ReadingListBookmarkMenu.Callback() { @Override public void onAddRequest(@Nullable ReadingListPage page) { parentFragment.addToReadingList(pageTitle, READ_MORE_BOOKMARK_BUTTON); } @Override public void onDeleted(@Nullable ReadingListPage page) { FeedbackUtil.showMessage((Activity) getContext(), getContext().getString(R.string.reading_list_item_deleted, pageTitle.getDisplayText())); } @Override public void onShare() { // ignore } }).show(pageTitle); } }, L::w)); } @Override public boolean onLongClick(@Nullable RbPageSummary item) { return false; } @Override public void onThumbClick(@Nullable RbPageSummary item) { } @Override public void onSecondaryActionClick(@Nullable RbPageSummary item, @NonNull View view) { } @Override public void onListChipClick(@Nullable ReadingList readingList) { } } }
Checkstyle linting
app/src/main/java/org/wikipedia/page/bottomcontent/BottomContentView.java
Checkstyle linting
<ide><path>pp/src/main/java/org/wikipedia/page/bottomcontent/BottomContentView.java <ide> import android.view.ViewGroup; <ide> import android.webkit.WebView; <ide> import android.widget.BaseAdapter; <del>import android.widget.ImageView; <ide> import android.widget.ListView; <ide> import android.widget.TextView; <ide>
Java
apache-2.0
2455ed30c55c248c0c57c9a77742975249b53fcf
0
nikita36078/J2ME-Loader,nikita36078/J2ME-Loader,nikita36078/J2ME-Loader,nikita36078/J2ME-Loader
/* * Copyright 2012 Kulikov Dmitriy * Copyright 2017-2018 Nikita Shakarun * Copyright 2021 Yury Kharchenko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.microedition.lcdui.keyboard; import android.graphics.PointF; import android.graphics.RectF; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.util.SparseBooleanArray; import android.view.View; import androidx.annotation.NonNull; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.graphics.CanvasWrapper; import javax.microedition.lcdui.overlay.Overlay; import javax.microedition.shell.MicroActivity; import javax.microedition.util.ContextHolder; import ru.playsoftware.j2meloader.config.Config; import ru.playsoftware.j2meloader.config.ProfileModel; import static javax.microedition.lcdui.keyboard.KeyMapper.SE_KEY_SPECIAL_GAMING_A; import static javax.microedition.lcdui.keyboard.KeyMapper.SE_KEY_SPECIAL_GAMING_B; public class VirtualKeyboard implements Overlay, Runnable { private static final String TAG = VirtualKeyboard.class.getName(); private static final String ARROW_LEFT = "\u2190"; private static final String ARROW_UP = "\u2191"; private static final String ARROW_RIGHT = "\u2192"; private static final String ARROW_DOWN = "\u2193"; private static final String ARROW_UP_LEFT = "\u2196"; private static final String ARROW_UP_RIGHT = "\u2197"; private static final String ARROW_DOWN_LEFT = "\u2199"; private static final String ARROW_DOWN_RIGHT = "\u2198"; private static final int LAYOUT_SIGNATURE = 0x564B4C00; private static final int LAYOUT_VERSION = 3; public static final int LAYOUT_EOF = -1; public static final int LAYOUT_KEYS = 0; public static final int LAYOUT_SCALES = 1; public static final int LAYOUT_COLORS = 2; public static final int LAYOUT_TYPE = 3; private static final int OVAL_SHAPE = 0; private static final int RECT_SHAPE = 1; public static final int ROUND_RECT_SHAPE = 2; public static final int TYPE_CUSTOM = 0; private static final int TYPE_PHONE = 1; private static final int TYPE_PHONE_ARROWS = 2; private static final int TYPE_NUM_ARR = 3; private static final int TYPE_ARR_NUM = 4; private static final int TYPE_NUMBERS = 5; private static final int TYPE_ARRAYS = 6; private static final float PHONE_KEY_ROWS = 5; private static final float PHONE_KEY_SCALE_X = 2.0f; private static final float PHONE_KEY_SCALE_Y = 0.75f; private static final long[] REPEAT_INTERVALS = {200, 400, 128, 128, 128, 128, 128}; private static final int SCREEN = -1; private static final int KEY_NUM1 = 0; private static final int KEY_NUM2 = 1; private static final int KEY_NUM3 = 2; private static final int KEY_NUM4 = 3; private static final int KEY_NUM5 = 4; private static final int KEY_NUM6 = 5; private static final int KEY_NUM7 = 6; private static final int KEY_NUM8 = 7; private static final int KEY_NUM9 = 8; private static final int KEY_NUM0 = 9; private static final int KEY_STAR = 10; private static final int KEY_POUND = 11; private static final int KEY_SOFT_LEFT = 12; private static final int KEY_SOFT_RIGHT = 13; private static final int KEY_D = 14; private static final int KEY_C = 15; private static final int KEY_UP_LEFT = 16; private static final int KEY_UP = 17; private static final int KEY_UP_RIGHT = 18; private static final int KEY_LEFT = 19; private static final int KEY_RIGHT = 20; private static final int KEY_DOWN_LEFT = 21; private static final int KEY_DOWN = 22; private static final int KEY_DOWN_RIGHT = 23; private static final int KEY_FIRE = 24; private static final int KEY_A = 25; private static final int KEY_B = 26; private static final int KEY_MENU = 27; private static final int KEYBOARD_SIZE = 28; private static final float SCALE_SNAP_RADIUS = 0.05f; private static final int FEEDBACK_DURATION = 50; private final float[] keyScales = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; private final int[][] keyScaleGroups = {{ KEY_UP_LEFT, KEY_UP, KEY_UP_RIGHT, KEY_LEFT, KEY_RIGHT, KEY_DOWN_LEFT, KEY_DOWN, KEY_DOWN_RIGHT }, { KEY_SOFT_LEFT, KEY_SOFT_RIGHT }, { KEY_A, KEY_B, KEY_C, KEY_D, }, { KEY_NUM1, KEY_NUM2, KEY_NUM3, KEY_NUM4, KEY_NUM5, KEY_NUM6, KEY_NUM7, KEY_NUM8, KEY_NUM9, KEY_NUM0, KEY_STAR, KEY_POUND }, { KEY_FIRE }, { KEY_MENU }}; private final VirtualKey[] keypad = new VirtualKey[KEYBOARD_SIZE]; // the average user usually has no more than 10 fingers... private final VirtualKey[] associatedKeys = new VirtualKey[10]; private final int[] snapStack = new int[KEYBOARD_SIZE]; private final Handler handler; private final File saveFile; private final ProfileModel settings; private Canvas target; private View overlayView; private boolean obscuresVirtualScreen; private boolean visible = true; private int layoutEditMode = LAYOUT_EOF; private int editedIndex; private float offsetX; private float offsetY; private float prevScaleX; private float prevScaleY; private RectF screen; private RectF virtualScreen; private float keySize = Math.min(ContextHolder.getDisplayWidth(), ContextHolder.getDisplayHeight()) / 6.0f; private float snapRadius; private int layoutVariant; public VirtualKeyboard(ProfileModel settings) { this.settings = settings; this.saveFile = new File(settings.dir + Config.MIDLET_KEY_LAYOUT_FILE); for (int i = KEY_NUM1; i < 9; i++) { keypad[i] = new VirtualKey(Canvas.KEY_NUM1 + i, Integer.toString(1 + i)); } keypad[KEY_NUM0] = new VirtualKey(Canvas.KEY_NUM0, "0"); keypad[KEY_STAR] = new VirtualKey(Canvas.KEY_STAR, "*"); keypad[KEY_POUND] = new VirtualKey(Canvas.KEY_POUND, "#"); keypad[KEY_SOFT_LEFT] = new VirtualKey(Canvas.KEY_SOFT_LEFT, "L"); keypad[KEY_SOFT_RIGHT] = new VirtualKey(Canvas.KEY_SOFT_RIGHT, "R"); keypad[KEY_A] = new VirtualKey(SE_KEY_SPECIAL_GAMING_A, "A"); keypad[KEY_B] = new VirtualKey(SE_KEY_SPECIAL_GAMING_B, "B"); keypad[KEY_C] = new VirtualKey(Canvas.KEY_END, "C"); keypad[KEY_D] = new VirtualKey(Canvas.KEY_SEND, "D"); keypad[KEY_UP_LEFT] = new DualKey(Canvas.KEY_UP, Canvas.KEY_LEFT, ARROW_UP_LEFT); keypad[KEY_UP] = new VirtualKey(Canvas.KEY_UP, ARROW_UP); keypad[KEY_UP_RIGHT] = new DualKey(Canvas.KEY_UP, Canvas.KEY_RIGHT, ARROW_UP_RIGHT); keypad[KEY_LEFT] = new VirtualKey(Canvas.KEY_LEFT, ARROW_LEFT); keypad[KEY_RIGHT] = new VirtualKey(Canvas.KEY_RIGHT, ARROW_RIGHT); keypad[KEY_DOWN_LEFT] = new DualKey(Canvas.KEY_DOWN, Canvas.KEY_LEFT, ARROW_DOWN_LEFT); keypad[KEY_DOWN] = new VirtualKey(Canvas.KEY_DOWN, ARROW_DOWN); keypad[KEY_DOWN_RIGHT] = new DualKey(Canvas.KEY_DOWN, Canvas.KEY_RIGHT, ARROW_DOWN_RIGHT); keypad[KEY_FIRE] = new VirtualKey(Canvas.KEY_FIRE, "F"); keypad[KEY_MENU] = new MenuKey(); layoutVariant = readLayoutType(); if (layoutVariant == -1) { layoutVariant = settings.vkType; } resetLayout(layoutVariant); if (layoutVariant == TYPE_CUSTOM) { try { readLayout(); } catch (IOException e) { e.printStackTrace(); resetLayout(TYPE_NUM_ARR); onLayoutChanged(TYPE_NUM_ARR); } } HandlerThread thread = new HandlerThread("MidletVirtualKeyboard"); thread.start(); handler = new Handler(thread.getLooper()); } public void onLayoutChanged(int variant) { if (variant == TYPE_CUSTOM && isPhone()) { float min = overlayView.getWidth(); float max = overlayView.getHeight(); if (min > max) { float tmp = max; max = min; min = tmp; } float oldSize = min / 6.0f; float newSize = Math.min(oldSize, max / 12.0f); float s = oldSize / newSize; for (int i = 0; i < keyScales.length; i++) { keyScales[i] *= s; } } layoutVariant = variant; try { saveLayout(); } catch (IOException e) { e.printStackTrace(); } if (target != null && target.isShown()) { target.updateSize(); } } private void resetLayout(int variant) { switch (variant) { case TYPE_PHONE: for (int j = 0, len = keyScales.length; j < len;) { keyScales[j++] = PHONE_KEY_SCALE_X; keyScales[j++] = PHONE_KEY_SCALE_Y; } setSnap(KEY_NUM0, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_SOFT_LEFT, KEY_NUM1, RectSnap.EXT_NORTH, true); setSnap(KEY_MENU, KEY_NUM2, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_NUM3, RectSnap.EXT_NORTH, true); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_C, KEY_A, RectSnap.EXT_SOUTH, false); setSnap(KEY_D, KEY_B, RectSnap.EXT_SOUTH, false); setSnap(KEY_UP_LEFT, KEY_C, RectSnap.EXT_SOUTH, false); setSnap(KEY_UP, KEY_C, RectSnap.EXT_SOUTHEAST, false); setSnap(KEY_UP_RIGHT, KEY_D, RectSnap.EXT_SOUTH, false); setSnap(KEY_LEFT, KEY_UP_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_FIRE, KEY_UP, RectSnap.EXT_SOUTH, false); setSnap(KEY_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_LEFT, KEY_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN, KEY_FIRE, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_RIGHT, KEY_RIGHT, RectSnap.EXT_SOUTH, false); break; case TYPE_PHONE_ARROWS: for (int j = 0, len = keyScales.length; j < len;) { keyScales[j++] = PHONE_KEY_SCALE_X; keyScales[j++] = PHONE_KEY_SCALE_Y; } setSnap(KEY_NUM0, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_DOWN, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_DOWN, RectSnap.EXT_EAST, true); setSnap(KEY_LEFT, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_FIRE, KEY_LEFT, RectSnap.EXT_EAST, true); setSnap(KEY_RIGHT, KEY_FIRE, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_UP, RectSnap.EXT_EAST, true); setSnap(KEY_SOFT_LEFT, KEY_NUM1, RectSnap.EXT_NORTH, true); setSnap(KEY_MENU, KEY_UP, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_NUM3, RectSnap.EXT_NORTH, true); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_C, KEY_A, RectSnap.EXT_SOUTH, false); setSnap(KEY_D, KEY_B, RectSnap.EXT_SOUTH, false); setSnap(KEY_UP_LEFT, KEY_C, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM2, KEY_C, RectSnap.EXT_SOUTHEAST, false); setSnap(KEY_UP_RIGHT, KEY_D, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM4, KEY_UP_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM5, KEY_NUM2, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM6, KEY_UP_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_LEFT, KEY_NUM4, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_RIGHT, KEY_NUM6, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM8, KEY_NUM5, RectSnap.EXT_SOUTH, false); break; case TYPE_NUM_ARR: default: Arrays.fill(keyScales, 1.0f); setSnap(KEY_DOWN_RIGHT, SCREEN, RectSnap.INT_SOUTHEAST, true); setSnap(KEY_DOWN, KEY_DOWN_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_DOWN_LEFT, KEY_DOWN, RectSnap.EXT_WEST, true); setSnap(KEY_LEFT, KEY_DOWN_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_RIGHT, KEY_DOWN_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP_RIGHT, KEY_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_UP_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, true); setSnap(KEY_FIRE, KEY_DOWN_RIGHT, RectSnap.EXT_NORTHWEST, true); setSnap(KEY_SOFT_LEFT, KEY_UP_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_STAR, SCREEN, RectSnap.INT_SOUTHWEST, true); setSnap(KEY_NUM0, KEY_STAR, RectSnap.EXT_EAST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_D, KEY_NUM1, RectSnap.EXT_NORTH, false); setSnap(KEY_C, KEY_NUM3, RectSnap.EXT_NORTH, false); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_MENU, KEY_UP, RectSnap.EXT_NORTH, false); break; case TYPE_ARR_NUM: Arrays.fill(keyScales, 1); setSnap(KEY_DOWN_LEFT, SCREEN, RectSnap.INT_SOUTHWEST, true); setSnap(KEY_DOWN, KEY_DOWN_LEFT, RectSnap.EXT_EAST, true); setSnap(KEY_DOWN_RIGHT, KEY_DOWN, RectSnap.EXT_EAST, true); setSnap(KEY_LEFT, KEY_DOWN_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_RIGHT, KEY_DOWN_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP_RIGHT, KEY_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_UP_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, true); setSnap(KEY_FIRE, KEY_DOWN_RIGHT, RectSnap.EXT_NORTHWEST, true); setSnap(KEY_SOFT_LEFT, KEY_UP_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_POUND, SCREEN, RectSnap.INT_SOUTHEAST, true); setSnap(KEY_NUM0, KEY_POUND, RectSnap.EXT_WEST, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_D, KEY_NUM1, RectSnap.EXT_NORTH, false); setSnap(KEY_C, KEY_NUM3, RectSnap.EXT_NORTH, false); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_MENU, KEY_UP, RectSnap.EXT_NORTH, false); break; case TYPE_NUMBERS: Arrays.fill(keyScales, 1); setSnap(KEY_NUM0, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_SOFT_LEFT, KEY_NUM1, RectSnap.EXT_WEST, true); setSnap(KEY_SOFT_RIGHT, KEY_NUM3, RectSnap.EXT_EAST, true); setSnap(KEY_UP, SCREEN, RectSnap.INT_NORTH, false); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, false); setSnap(KEY_UP_RIGHT, KEY_UP, RectSnap.EXT_EAST, false); setSnap(KEY_FIRE, KEY_UP, RectSnap.EXT_SOUTH, false); setSnap(KEY_LEFT, KEY_UP_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_LEFT, KEY_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_RIGHT, KEY_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN, KEY_DOWN_LEFT, RectSnap.EXT_EAST, false); setSnap(KEY_A, KEY_NUM4, RectSnap.EXT_WEST, false); setSnap(KEY_B, KEY_NUM6, RectSnap.EXT_EAST, false); setSnap(KEY_C, KEY_NUM7, RectSnap.EXT_WEST, false); setSnap(KEY_D, KEY_NUM9, RectSnap.EXT_EAST, false); setSnap(KEY_MENU, SCREEN, RectSnap.INT_NORTHEAST, false); break; case TYPE_ARRAYS: Arrays.fill(keyScales, 1); setSnap(KEY_DOWN, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_DOWN_RIGHT, KEY_DOWN, RectSnap.EXT_EAST, true); setSnap(KEY_DOWN_LEFT, KEY_DOWN, RectSnap.EXT_WEST, true); setSnap(KEY_LEFT, KEY_DOWN_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_RIGHT, KEY_DOWN_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP_RIGHT, KEY_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_UP_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, true); setSnap(KEY_FIRE, KEY_DOWN_RIGHT, RectSnap.EXT_NORTHWEST, true); setSnap(KEY_SOFT_LEFT, KEY_UP_LEFT, RectSnap.EXT_WEST, true); setSnap(KEY_SOFT_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM2, RectSnap.EXT_WEST, false); setSnap(KEY_NUM2, SCREEN, RectSnap.INT_NORTH, false); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, false); setSnap(KEY_NUM4, KEY_NUM1, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM5, KEY_NUM2, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM6, KEY_NUM3, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM7, KEY_NUM4, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM8, KEY_NUM5, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM9, KEY_NUM6, RectSnap.EXT_SOUTH, false); setSnap(KEY_STAR, KEY_NUM7, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM0, KEY_NUM8, RectSnap.EXT_SOUTH, false); setSnap(KEY_POUND, KEY_NUM9, RectSnap.EXT_SOUTH, false); setSnap(KEY_A, KEY_LEFT, RectSnap.EXT_WEST, false); setSnap(KEY_B, KEY_RIGHT, RectSnap.EXT_EAST, false); setSnap(KEY_C, KEY_DOWN_LEFT, RectSnap.EXT_WEST, false); setSnap(KEY_D, KEY_DOWN_RIGHT, RectSnap.EXT_EAST, false); setSnap(KEY_MENU, SCREEN, RectSnap.INT_NORTHEAST, false); break; } } public int getLayout() { return layoutVariant; } public float getPhoneKeyboardHeight() { return PHONE_KEY_ROWS * keySize * PHONE_KEY_SCALE_Y; } public void setLayout(int variant) { resetLayout(variant); if (variant == TYPE_CUSTOM) { try { readLayout(); } catch (IOException ioe) { ioe.printStackTrace(); resetLayout(layoutVariant); return; } } onLayoutChanged(variant); for (int group = 0; group < keyScaleGroups.length; group++) { resizeKeyGroup(group); } snapKeys(); overlayView.postInvalidate(); if (target != null && target.isShown()) { target.updateSize(); } } private void saveLayout() throws IOException { try (RandomAccessFile raf = new RandomAccessFile(saveFile, "rw")) { int variant = layoutVariant; if (variant != TYPE_CUSTOM && raf.length() > 16) { try { if (raf.readInt() != LAYOUT_SIGNATURE) { throw new IOException("file signature not found"); } int version = raf.readInt(); if (version < 1 || version > LAYOUT_VERSION) { throw new IOException("incompatible file version"); } loop:while (true) { int block = raf.readInt(); int length = raf.readInt(); switch (block) { case LAYOUT_EOF: raf.seek(raf.getFilePointer() - 8); raf.writeInt(LAYOUT_TYPE); raf.writeInt(1); raf.write(variant); raf.writeInt(LAYOUT_EOF); raf.writeInt(0); return; case LAYOUT_TYPE: raf.write(variant); return; default: if (raf.skipBytes(length) != length) { break loop; } break; } } } catch (IOException e) { e.printStackTrace(); } } raf.seek(0); raf.writeInt(LAYOUT_SIGNATURE); raf.writeInt(LAYOUT_VERSION); raf.writeInt(LAYOUT_TYPE); raf.writeInt(1); raf.write(variant); if (variant != TYPE_CUSTOM) { raf.writeInt(LAYOUT_EOF); raf.writeInt(0); raf.setLength(raf.getFilePointer()); return; } raf.writeInt(LAYOUT_KEYS); raf.writeInt(keypad.length * 21 + 4); raf.writeInt(keypad.length); for (VirtualKey key : keypad) { raf.writeInt(key.hashCode()); raf.writeBoolean(key.visible); raf.writeInt(key.snapOrigin); raf.writeInt(key.snapMode); PointF snapOffset = key.snapOffset; raf.writeFloat(snapOffset.x); raf.writeFloat(snapOffset.y); } raf.writeInt(LAYOUT_SCALES); raf.writeInt(keyScales.length * 4 + 4); raf.writeInt(keyScales.length); for (float keyScale : keyScales) { raf.writeFloat(keyScale); } raf.writeInt(LAYOUT_EOF); raf.writeInt(0); raf.setLength(raf.getFilePointer()); } } private int readLayoutType() { try (DataInputStream dis = new DataInputStream(new FileInputStream(saveFile))) { if (dis.readInt() != LAYOUT_SIGNATURE) { throw new IOException("file signature not found"); } int version = dis.readInt(); if (version < 1 || version > LAYOUT_VERSION) { throw new IOException("incompatible file version"); } while (true) { int block = dis.readInt(); int length = dis.readInt(); switch (block) { case LAYOUT_EOF: return -1; case LAYOUT_TYPE: return dis.read(); default: if (dis.skipBytes(length) != length) { return -1; } } } } catch (IOException e) { e.printStackTrace(); } return -1; } private void readLayout() throws IOException { try (DataInputStream dis = new DataInputStream(new FileInputStream(saveFile))) { if (dis.readInt() != LAYOUT_SIGNATURE) { throw new IOException("file signature not found"); } int version = dis.readInt(); if (version < 1 || version > LAYOUT_VERSION) { throw new IOException("incompatible file version"); } while (true) { int block = dis.readInt(); int length = dis.readInt(); int count; switch (block) { case LAYOUT_EOF: return; case LAYOUT_KEYS: count = dis.readInt(); for (int i = 0; i < count; i++) { int hash = dis.readInt(); boolean found = false; for (VirtualKey key : keypad) { if (key.hashCode() == hash) { if (version >= 2) { key.visible = dis.readBoolean(); } key.snapOrigin = dis.readInt(); key.snapMode = dis.readInt(); key.snapOffset.x = dis.readFloat(); key.snapOffset.y = dis.readFloat(); found = true; break; } } if (!found) { dis.skipBytes(version >= 2 ? 17 : 16); } } break; case LAYOUT_SCALES: count = dis.readInt(); if (version >= 3) { for (int i = 0; i < count; i++) { keyScales[i] = dis.readFloat(); } } else if (count * 2 <= keyScales.length) { for (int i = 0; i < keyScales.length; i++) { float v = dis.readFloat(); keyScales[i++] = v; keyScales[i] = v; } } else { dis.skipBytes(count * 4); } break; default: dis.skipBytes(length); break; } } } } public String[] getKeyNames() { String[] names = new String[KEYBOARD_SIZE]; for (int i = 0; i < KEYBOARD_SIZE; i++) { names[i] = keypad[i].label; } return names; } public boolean[] getKeysVisibility() { boolean[] states = new boolean[KEYBOARD_SIZE]; for (int i = 0; i < KEYBOARD_SIZE; i++) { states[i] = !keypad[i].visible; } return states; } public void setKeysVisibility(SparseBooleanArray states) { for (int i = 0; i < states.size(); i++) { keypad[states.keyAt(i)].visible = !states.valueAt(i); } overlayView.postInvalidate(); } @Override public void setTarget(Canvas canvas) { target = canvas; highlightGroup(-1); } private void setSnap(int key, int origin, int mode, boolean visible) { VirtualKey vKey = keypad[key]; vKey.snapOrigin = origin; vKey.snapMode = mode; vKey.snapOffset.set(0, 0); vKey.snapValid = false; vKey.visible = visible; } private boolean findSnap(int target, int origin) { VirtualKey tk = keypad[target]; VirtualKey ok = keypad[origin]; tk.snapMode = RectSnap.getSnap(tk.rect, ok.rect, snapRadius, RectSnap.COARSE_MASK, true); if (tk.snapMode != RectSnap.NO_SNAP) { tk.snapOrigin = origin; tk.snapOffset.set(0, 0); for (int i = 0; i < keypad.length; i++) { origin = keypad[origin].snapOrigin; if (origin == SCREEN) { return true; } } } return false; } private void snapKey(int key, int level) { if (level >= snapStack.length) { Log.d(TAG, "Snap loop detected: "); for (int i = 1; i < snapStack.length; i++) { System.out.print(snapStack[i]); System.out.print(", "); } Log.d(TAG, String.valueOf(key)); return; } snapStack[level] = key; VirtualKey vKey = keypad[key]; if (vKey.snapOrigin == SCREEN) { RectSnap.snap(vKey.rect, screen, vKey.snapMode, vKey.snapOffset); } else { if (!keypad[vKey.snapOrigin].snapValid) { snapKey(vKey.snapOrigin, level + 1); } RectSnap.snap(vKey.rect, keypad[vKey.snapOrigin].rect, vKey.snapMode, vKey.snapOffset); } vKey.snapValid = true; } private void snapKeys() { obscuresVirtualScreen = false; boolean isPhone = isPhone(); for (int i = 0; i < keypad.length; i++) { snapKey(i, 0); VirtualKey key = keypad[i]; RectF rect = key.rect; key.corners = (int) (Math.min(rect.width(), rect.height()) * 0.25F); if (!isPhone && RectF.intersects(rect, virtualScreen)) { obscuresVirtualScreen = true; key.opaque = false; } else { key.opaque = true; } } boolean opaque = !obscuresVirtualScreen || settings.vkForceOpacity; for (VirtualKey key : keypad) { key.opaque &= opaque; } } public boolean isPhone() { return layoutVariant == TYPE_PHONE || layoutVariant == TYPE_PHONE_ARROWS; } private void highlightGroup(int group) { for (VirtualKey aKeypad : keypad) { aKeypad.selected = false; } if (group >= 0) { for (int key = 0; key < keyScaleGroups[group].length; key++) { keypad[keyScaleGroups[group][key]].selected = true; } } } public int getLayoutEditMode() { return layoutEditMode; } public void setLayoutEditMode(int mode) { layoutEditMode = mode; int group = -1; if (mode == LAYOUT_SCALES) { editedIndex = 0; group = 0; } highlightGroup(group); handler.removeCallbacks(this); visible = true; overlayView.postInvalidate(); hide(); if (target != null && target.isShown()) { target.updateSize(); } } private void resizeKey(int key, float w, float h) { VirtualKey vKey = keypad[key]; vKey.resize(w, h); vKey.snapValid = false; } private void resizeKeyGroup(int group) { float sizeX = (float) Math.ceil(keySize * keyScales[group * 2]); float sizeY = (float) Math.ceil(keySize * keyScales[group * 2 + 1]); for (int key = 0; key < keyScaleGroups[group].length; key++) { resizeKey(keyScaleGroups[group][key], sizeX, sizeY); } } @Override public void resize(RectF screen, RectF virtualScreen) { this.screen = screen; this.virtualScreen = virtualScreen; snapRadius = keyScales[0]; for (int i = 1; i < keyScales.length; i++) { if (keyScales[i] < snapRadius) { snapRadius = keyScales[i]; } } float min = overlayView.getWidth(); float max = overlayView.getHeight(); if (min > max) { float tmp = max; max = min; min = tmp; } float keySize = min / 6.5f; keySize = isPhone() ? keySize : Math.min(keySize, max / 12.0f); snapRadius = keySize * snapRadius / 4; this.keySize = keySize; for (int group = 0; group < keyScaleGroups.length; group++) { resizeKeyGroup(group); } snapKeys(); overlayView.postInvalidate(); int delay = settings.vkHideDelay; if (delay > 0 && obscuresVirtualScreen && layoutEditMode == LAYOUT_EOF) { for (VirtualKey key : associatedKeys) { if (key != null) { return; } } handler.postDelayed(this, delay); } } @Override public void paint(CanvasWrapper g) { if (visible) { for (VirtualKey key : keypad) { if (key.visible) { key.paint(g); } } } } @Override public boolean pointerPressed(int pointer, float x, float y) { switch (layoutEditMode) { case LAYOUT_EOF: if (pointer > associatedKeys.length) { return false; } for (VirtualKey key : keypad) { if (key.contains(x, y)) { vibrate(); associatedKeys[pointer] = key; key.onDown(); overlayView.postInvalidate(); break; } } break; case LAYOUT_KEYS: editedIndex = -1; for (int i = 0; i < keypad.length; i++) { if (keypad[i].contains(x, y)) { editedIndex = i; RectF rect = keypad[i].rect; offsetX = x - rect.left; offsetY = y - rect.top; break; } } break; case LAYOUT_SCALES: int index = -1; for (int group = 0; group < keyScaleGroups.length && index < 0; group++) { for (int key = 0; key < keyScaleGroups[group].length && index < 0; key++) { if (keypad[keyScaleGroups[group][key]].contains(x, y)) { index = group; } } } if (index >= 0) { editedIndex = index; highlightGroup(index); overlayView.postInvalidate(); } offsetX = x; offsetY = y; prevScaleX = keyScales[editedIndex * 2]; prevScaleY = keyScales[editedIndex * 2 + 1]; break; } return false; } @Override public boolean pointerDragged(int pointer, float x, float y) { switch (layoutEditMode) { case LAYOUT_EOF: if (pointer > associatedKeys.length) { return false; } VirtualKey aKey = associatedKeys[pointer]; if (aKey == null) { pointerPressed(pointer, x, y); } else if (!aKey.contains(x, y)) { associatedKeys[pointer] = null; aKey.onUp(); overlayView.postInvalidate(); pointerPressed(pointer, x, y); } break; case LAYOUT_KEYS: if (editedIndex >= 0) { VirtualKey key = keypad[editedIndex]; RectF rect = key.rect; rect.offsetTo(x - offsetX, y - offsetY); key.snapMode = RectSnap.NO_SNAP; for (int i = 0; i < keypad.length; i++) { if (i != editedIndex && findSnap(editedIndex, i)) { break; } } if (key.snapMode == RectSnap.NO_SNAP) { key.snapMode = RectSnap.getSnap(rect, screen, key.snapOffset); key.snapOrigin = SCREEN; if (Math.abs(key.snapOffset.x) <= snapRadius) { key.snapOffset.x = 0; } if (Math.abs(key.snapOffset.y) <= snapRadius) { key.snapOffset.y = 0; } } snapKey(editedIndex, 0); overlayView.postInvalidate(); } break; case LAYOUT_SCALES: float dx = x - offsetX; float dy = offsetY - y; float scale; int index = this.editedIndex * 2; if (Math.abs(dx) > Math.abs(dy)) { scale = prevScaleX + dx / Math.min(screen.centerX(), screen.centerY()); } else { scale = prevScaleY + dy / Math.min(screen.centerX(), screen.centerY()); index++; } if (Math.abs(1 - scale) <= SCALE_SNAP_RADIUS) { scale = 1; } else { for (int i = index % 2; i < keyScales.length; i += 2) { if (i != index && Math.abs(keyScales[i] - scale) <= SCALE_SNAP_RADIUS) { scale = keyScales[i]; break; } } } keyScales[index] = scale; resizeKeyGroup(this.editedIndex); snapKeys(); overlayView.postInvalidate(); break; } return false; } @Override public boolean pointerReleased(int pointer, float x, float y) { if (layoutEditMode == LAYOUT_EOF) { if (pointer > associatedKeys.length) { return false; } VirtualKey key = associatedKeys[pointer]; if (key != null) { associatedKeys[pointer] = null; key.onUp(); overlayView.postInvalidate(); } } else if (layoutEditMode == LAYOUT_KEYS) { for (int key = 0; key < keypad.length; key++) { VirtualKey vKey = keypad[key]; if (vKey.snapOrigin == editedIndex) { vKey.snapMode = RectSnap.NO_SNAP; for (int i = 0; i < KEYBOARD_SIZE; i++) { if (i != key && findSnap(key, i)) { break; } } if (vKey.snapMode == RectSnap.NO_SNAP) { vKey.snapMode = RectSnap.getSnap(vKey.rect, screen, vKey.snapOffset); vKey.snapOrigin = SCREEN; if (Math.abs(vKey.snapOffset.x) <= snapRadius) { vKey.snapOffset.x = 0; } if (Math.abs(vKey.snapOffset.y) <= snapRadius) { vKey.snapOffset.y = 0; } } snapKey(key, 0); } } snapKeys(); editedIndex = -1; } return false; } @Override public void show() { if (settings.vkHideDelay > 0 && obscuresVirtualScreen) { handler.removeCallbacks(this); if (!visible) { visible = true; overlayView.postInvalidate(); } } } @Override public void hide() { long delay = settings.vkHideDelay; if (delay > 0 && obscuresVirtualScreen && layoutEditMode == LAYOUT_EOF) { handler.postDelayed(this, delay); } } @Override public void cancel() { for (VirtualKey key : keypad) { key.selected = false; handler.removeCallbacks(key); } } @Override public void run() { visible = false; overlayView.postInvalidate(); } @Override public boolean keyPressed(int keyCode) { int hashCode = 31 * (31 + keyCode); for (VirtualKey key : keypad) { if (key.hashCode() == hashCode) { key.selected = true; overlayView.postInvalidate(); break; } } return false; } @Override public boolean keyRepeated(int keyCode) { return false; } @Override public boolean keyReleased(int keyCode) { int hashCode = 31 * (31 + keyCode); for (VirtualKey key : keypad) { if (key.hashCode() == hashCode) { key.selected = false; overlayView.postInvalidate(); break; } } return false; } private void vibrate() { if (settings.vkFeedback) ContextHolder.vibrateKey(FEEDBACK_DURATION); } public void setView(View view) { overlayView = view; } public int getKeyStatesVodafone() { int keyStates = 0; for (int i = 0; i < keypad.length; i++) { VirtualKey key = keypad[i]; if (key.selected) { keyStates |= getKeyBit(i); } } return keyStates; } private int getKeyBit(int vKey) { switch (vKey) { case KEY_NUM0 : return 1; // 0 0 key KEY_NUM0 = 9; case KEY_NUM1 : return 1 << 1; // 1 1 key KEY_NUM1 = 0; case KEY_NUM2 : return 1 << 2; // 2 2 key KEY_NUM2 = 1; case KEY_NUM3 : return 1 << 3; // 3 3 key KEY_NUM3 = 2; case KEY_NUM4 : return 1 << 4; // 4 4 key KEY_NUM4 = 3; case KEY_NUM5 : return 1 << 5; // 5 5 key KEY_NUM5 = 4; case KEY_NUM6 : return 1 << 6; // 6 6 key KEY_NUM6 = 5; case KEY_NUM7 : return 1 << 7; // 7 7 key KEY_NUM7 = 6; case KEY_NUM8 : return 1 << 8; // 8 8 key KEY_NUM8 = 7; case KEY_NUM9 : return 1 << 9; // 9 9 key KEY_NUM9 = 8; case KEY_STAR : return 1 << 10; // 10 * key KEY_STAR = 10; case KEY_POUND : return 1 << 11; // 11 # key KEY_POUND = 11; case KEY_UP : return 1 << 12; // 12 Up key KEY_UP = 17; case KEY_LEFT : return 1 << 13; // 13 Left key KEY_LEFT = 19; case KEY_RIGHT : return 1 << 14; // 14 Right key KEY_RIGHT = 20; case KEY_DOWN : return 1 << 15; // 15 Down key KEY_DOWN = 22; case KEY_FIRE : return 1 << 16; // 16 Select key KEY_FIRE = 24; case KEY_SOFT_LEFT : return 1 << 17; // 17 Softkey 1 KEY_SOFT_LEFT = 12; case KEY_SOFT_RIGHT: return 1 << 18; // 18 Softkey 2 KEY_SOFT_RIGHT = 13; // TODO: 05.08.2020 Softkey3 mapped to KEY_C case KEY_C : return 1 << 19; // 19 Softkey 3 KEY_C = 15; case KEY_UP_RIGHT : return 1 << 20; // 20 Upper Right KEY_UP_RIGHT = 18; case KEY_UP_LEFT : return 1 << 21; // 21 Upper Left KEY_UP_LEFT = 16; case KEY_DOWN_RIGHT: return 1 << 22; // 22 Lower Right KEY_DOWN_RIGHT = 23; case KEY_DOWN_LEFT : return 1 << 23; // 23 Lower Left KEY_DOWN_LEFT = 21; } return 0; } private class VirtualKey implements Runnable { final String label; final int keyCode; final RectF rect = new RectF(); final PointF snapOffset = new PointF(); int snapOrigin; int snapMode; boolean snapValid; boolean selected; boolean visible = true; boolean opaque = true; int corners; private final int hashCode; private int repeatCount; VirtualKey(int keyCode, String label) { this.keyCode = keyCode; this.label = label; hashCode = 31 * (31 + this.keyCode); } void resize(float width, float height) { rect.right = rect.left + width; rect.bottom = rect.top + height; } boolean contains(float x, float y) { return visible && rect.contains(x, y); } void paint(CanvasWrapper g) { int bgColor; int fgColor; if (selected) { bgColor = settings.vkBgColorSelected; fgColor = settings.vkFgColorSelected; } else { bgColor = settings.vkBgColor; fgColor = settings.vkFgColor; } int alpha = (opaque || layoutEditMode != LAYOUT_EOF ? 0xFF : settings.vkAlpha) << 24; g.setFillColor(alpha | bgColor); g.setTextColor(alpha | fgColor); g.setDrawColor(alpha | settings.vkOutlineColor); switch (settings.vkButtonShape) { case ROUND_RECT_SHAPE: g.fillRoundRect(rect, corners, corners); g.drawRoundRect(rect, corners, corners); break; case RECT_SHAPE: g.fillRect(rect); g.drawRect(rect); break; case OVAL_SHAPE: g.fillArc(rect, 0, 360); g.drawArc(rect, 0, 360); break; } g.drawString(label, rect.centerX(), rect.centerY()); } @NonNull public String toString() { return "[" + label + ": " + rect.left + ", " + rect.top + ", " + rect.right + ", " + rect.bottom + "]"; } public int hashCode() { return hashCode; } @Override public void run() { if (target == null) { selected = false; repeatCount = 0; return; } if (selected) { onRepeat(); } else { repeatCount = 0; } } public void onRepeat() { handler.postDelayed(this, repeatCount > 6 ? 80 : REPEAT_INTERVALS[repeatCount++]); target.postKeyRepeated(keyCode); } protected void onDown() { selected = true; target.postKeyPressed(keyCode); handler.postDelayed(this, 400); } public void onUp() { selected = false; handler.removeCallbacks(this); target.postKeyReleased(keyCode); } } private class DualKey extends VirtualKey { final int secondKeyCode; private final int hashCode; DualKey(int keyCode, int secondKeyCode, String label) { super(keyCode, label); if (secondKeyCode == 0) throw new IllegalArgumentException(); this.secondKeyCode = secondKeyCode; hashCode = 31 * (31 + this.keyCode) + this.secondKeyCode; } @Override protected void onDown() { super.onDown(); target.postKeyPressed(secondKeyCode); } @Override public void onUp() { super.onUp(); target.postKeyReleased(secondKeyCode); } @Override public void onRepeat() { super.onRepeat(); target.postKeyRepeated(secondKeyCode); } @Override public int hashCode() { return hashCode; } } private class MenuKey extends VirtualKey { MenuKey() { super(KeyMapper.KEY_OPTIONS_MENU, "M"); } @Override protected void onDown() { selected = true; handler.postDelayed(this, 500); } @Override public void onUp() { if (selected) { selected = false; handler.removeCallbacks(this); MicroActivity activity = ContextHolder.getActivity(); if (activity != null) { activity.openOptionsMenu(); } } } @Override public void run() { selected = false; MicroActivity activity = ContextHolder.getActivity(); if (activity != null) { activity.showExitConfirmation(); } } } }
app/src/main/java/javax/microedition/lcdui/keyboard/VirtualKeyboard.java
/* * Copyright 2012 Kulikov Dmitriy * Copyright 2017-2018 Nikita Shakarun * Copyright 2021 Yury Kharchenko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.microedition.lcdui.keyboard; import android.graphics.PointF; import android.graphics.RectF; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.util.SparseBooleanArray; import android.view.View; import androidx.annotation.NonNull; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.graphics.CanvasWrapper; import javax.microedition.lcdui.overlay.Overlay; import javax.microedition.shell.MicroActivity; import javax.microedition.util.ContextHolder; import ru.playsoftware.j2meloader.config.Config; import ru.playsoftware.j2meloader.config.ProfileModel; import static javax.microedition.lcdui.keyboard.KeyMapper.SE_KEY_SPECIAL_GAMING_A; import static javax.microedition.lcdui.keyboard.KeyMapper.SE_KEY_SPECIAL_GAMING_B; public class VirtualKeyboard implements Overlay, Runnable { private static final String TAG = VirtualKeyboard.class.getName(); private static final String ARROW_LEFT = "\u2190"; private static final String ARROW_UP = "\u2191"; private static final String ARROW_RIGHT = "\u2192"; private static final String ARROW_DOWN = "\u2193"; private static final String ARROW_UP_LEFT = "\u2196"; private static final String ARROW_UP_RIGHT = "\u2197"; private static final String ARROW_DOWN_LEFT = "\u2199"; private static final String ARROW_DOWN_RIGHT = "\u2198"; private static final int LAYOUT_SIGNATURE = 0x564B4C00; private static final int LAYOUT_VERSION = 3; public static final int LAYOUT_EOF = -1; public static final int LAYOUT_KEYS = 0; public static final int LAYOUT_SCALES = 1; public static final int LAYOUT_COLORS = 2; public static final int LAYOUT_TYPE = 3; private static final int OVAL_SHAPE = 0; private static final int RECT_SHAPE = 1; public static final int ROUND_RECT_SHAPE = 2; public static final int TYPE_CUSTOM = 0; private static final int TYPE_PHONE = 1; private static final int TYPE_PHONE_ARROWS = 2; private static final int TYPE_NUM_ARR = 3; private static final int TYPE_ARR_NUM = 4; private static final int TYPE_NUMBERS = 5; private static final int TYPE_ARRAYS = 6; private static final float PHONE_KEY_ROWS = 5; private static final float PHONE_KEY_SCALE_X = 2.0f; private static final float PHONE_KEY_SCALE_Y = 0.75f; private static final long[] REPEAT_INTERVALS = {200, 400, 128, 128, 128, 128, 128}; private static final int SCREEN = -1; private static final int KEY_NUM1 = 0; private static final int KEY_NUM2 = 1; private static final int KEY_NUM3 = 2; private static final int KEY_NUM4 = 3; private static final int KEY_NUM5 = 4; private static final int KEY_NUM6 = 5; private static final int KEY_NUM7 = 6; private static final int KEY_NUM8 = 7; private static final int KEY_NUM9 = 8; private static final int KEY_NUM0 = 9; private static final int KEY_STAR = 10; private static final int KEY_POUND = 11; private static final int KEY_SOFT_LEFT = 12; private static final int KEY_SOFT_RIGHT = 13; private static final int KEY_D = 14; private static final int KEY_C = 15; private static final int KEY_UP_LEFT = 16; private static final int KEY_UP = 17; private static final int KEY_UP_RIGHT = 18; private static final int KEY_LEFT = 19; private static final int KEY_RIGHT = 20; private static final int KEY_DOWN_LEFT = 21; private static final int KEY_DOWN = 22; private static final int KEY_DOWN_RIGHT = 23; private static final int KEY_FIRE = 24; private static final int KEY_A = 25; private static final int KEY_B = 26; private static final int KEY_MENU = 27; private static final int KEYBOARD_SIZE = 28; private static final float SCALE_SNAP_RADIUS = 0.05f; private static final int FEEDBACK_DURATION = 50; private final float[] keyScales = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; private final int[][] keyScaleGroups = {{ KEY_UP_LEFT, KEY_UP, KEY_UP_RIGHT, KEY_LEFT, KEY_RIGHT, KEY_DOWN_LEFT, KEY_DOWN, KEY_DOWN_RIGHT }, { KEY_SOFT_LEFT, KEY_SOFT_RIGHT }, { KEY_A, KEY_B, KEY_C, KEY_D, }, { KEY_NUM1, KEY_NUM2, KEY_NUM3, KEY_NUM4, KEY_NUM5, KEY_NUM6, KEY_NUM7, KEY_NUM8, KEY_NUM9, KEY_NUM0, KEY_STAR, KEY_POUND }, { KEY_FIRE }, { KEY_MENU }}; private final VirtualKey[] keypad = new VirtualKey[KEYBOARD_SIZE]; // the average user usually has no more than 10 fingers... private final VirtualKey[] associatedKeys = new VirtualKey[10]; private final int[] snapStack = new int[KEYBOARD_SIZE]; private final Handler handler; private final File saveFile; private final ProfileModel settings; private Canvas target; private View overlayView; private boolean obscuresVirtualScreen; private boolean visible = true; private int layoutEditMode = LAYOUT_EOF; private int editedIndex; private float offsetX; private float offsetY; private float prevScaleX; private float prevScaleY; private RectF screen; private RectF virtualScreen; private float keySize = Math.min(ContextHolder.getDisplayWidth(), ContextHolder.getDisplayHeight()) / 6.0f; private float snapRadius; private int layoutVariant; public VirtualKeyboard(ProfileModel settings) { this.settings = settings; this.saveFile = new File(settings.dir + Config.MIDLET_KEY_LAYOUT_FILE); for (int i = KEY_NUM1; i < 9; i++) { keypad[i] = new VirtualKey(Canvas.KEY_NUM1 + i, Integer.toString(1 + i)); } keypad[KEY_NUM0] = new VirtualKey(Canvas.KEY_NUM0, "0"); keypad[KEY_STAR] = new VirtualKey(Canvas.KEY_STAR, "*"); keypad[KEY_POUND] = new VirtualKey(Canvas.KEY_POUND, "#"); keypad[KEY_SOFT_LEFT] = new VirtualKey(Canvas.KEY_SOFT_LEFT, "L"); keypad[KEY_SOFT_RIGHT] = new VirtualKey(Canvas.KEY_SOFT_RIGHT, "R"); keypad[KEY_A] = new VirtualKey(SE_KEY_SPECIAL_GAMING_A, "A"); keypad[KEY_B] = new VirtualKey(SE_KEY_SPECIAL_GAMING_B, "B"); keypad[KEY_C] = new VirtualKey(Canvas.KEY_END, "C"); keypad[KEY_D] = new VirtualKey(Canvas.KEY_SEND, "D"); keypad[KEY_UP_LEFT] = new DualKey(Canvas.KEY_UP, Canvas.KEY_LEFT, ARROW_UP_LEFT); keypad[KEY_UP] = new VirtualKey(Canvas.KEY_UP, ARROW_UP); keypad[KEY_UP_RIGHT] = new DualKey(Canvas.KEY_UP, Canvas.KEY_RIGHT, ARROW_UP_RIGHT); keypad[KEY_LEFT] = new VirtualKey(Canvas.KEY_LEFT, ARROW_LEFT); keypad[KEY_RIGHT] = new VirtualKey(Canvas.KEY_RIGHT, ARROW_RIGHT); keypad[KEY_DOWN_LEFT] = new DualKey(Canvas.KEY_DOWN, Canvas.KEY_LEFT, ARROW_DOWN_LEFT); keypad[KEY_DOWN] = new VirtualKey(Canvas.KEY_DOWN, ARROW_DOWN); keypad[KEY_DOWN_RIGHT] = new DualKey(Canvas.KEY_DOWN, Canvas.KEY_RIGHT, ARROW_DOWN_RIGHT); keypad[KEY_FIRE] = new VirtualKey(Canvas.KEY_FIRE, "F"); keypad[KEY_MENU] = new MenuKey(); layoutVariant = readLayoutType(); if (layoutVariant == -1) { layoutVariant = settings.vkType; } resetLayout(layoutVariant); if (layoutVariant == TYPE_CUSTOM) { try { readLayout(); } catch (IOException e) { e.printStackTrace(); resetLayout(TYPE_NUM_ARR); onLayoutChanged(TYPE_NUM_ARR); } } HandlerThread thread = new HandlerThread("MidletVirtualKeyboard"); thread.start(); handler = new Handler(thread.getLooper()); } public void onLayoutChanged(int variant) { if (variant == TYPE_CUSTOM && isPhone()) { float min = overlayView.getWidth(); float max = overlayView.getHeight(); if (min > max) { float tmp = max; max = min; min = tmp; } float oldSize = min / 6.0f; float newSize = Math.min(oldSize, max / 12.0f); float s = oldSize / newSize; for (int i = 0; i < keyScales.length; i++) { keyScales[i] *= s; } } layoutVariant = variant; try { saveLayout(); } catch (IOException e) { e.printStackTrace(); } if (target != null && target.isShown()) { target.updateSize(); } } private void resetLayout(int variant) { switch (variant) { case TYPE_PHONE: for (int j = 0, len = keyScales.length; j < len;) { keyScales[j++] = PHONE_KEY_SCALE_X; keyScales[j++] = PHONE_KEY_SCALE_Y; } setSnap(KEY_NUM0, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_SOFT_LEFT, KEY_NUM1, RectSnap.EXT_NORTH, true); setSnap(KEY_MENU, KEY_NUM2, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_NUM3, RectSnap.EXT_NORTH, true); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_C, KEY_A, RectSnap.EXT_SOUTH, false); setSnap(KEY_D, KEY_B, RectSnap.EXT_SOUTH, false); setSnap(KEY_UP_LEFT, KEY_C, RectSnap.EXT_SOUTH, false); setSnap(KEY_UP, KEY_C, RectSnap.EXT_SOUTHEAST, false); setSnap(KEY_UP_RIGHT, KEY_D, RectSnap.EXT_SOUTH, false); setSnap(KEY_LEFT, KEY_UP_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_FIRE, KEY_UP, RectSnap.EXT_SOUTH, false); setSnap(KEY_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_LEFT, KEY_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN, KEY_FIRE, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_RIGHT, KEY_RIGHT, RectSnap.EXT_SOUTH, false); break; case TYPE_PHONE_ARROWS: for (int j = 0, len = keyScales.length; j < len;) { keyScales[j++] = PHONE_KEY_SCALE_X; keyScales[j++] = PHONE_KEY_SCALE_Y; } setSnap(KEY_NUM0, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_DOWN, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_DOWN, RectSnap.EXT_EAST, true); setSnap(KEY_LEFT, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_FIRE, KEY_LEFT, RectSnap.EXT_EAST, true); setSnap(KEY_RIGHT, KEY_FIRE, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_UP, RectSnap.EXT_EAST, true); setSnap(KEY_SOFT_LEFT, KEY_NUM1, RectSnap.EXT_NORTH, true); setSnap(KEY_MENU, KEY_UP, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_NUM3, RectSnap.EXT_NORTH, true); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_C, KEY_A, RectSnap.EXT_SOUTH, false); setSnap(KEY_D, KEY_B, RectSnap.EXT_SOUTH, false); setSnap(KEY_UP_LEFT, KEY_C, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM2, KEY_C, RectSnap.EXT_SOUTHEAST, false); setSnap(KEY_UP_RIGHT, KEY_D, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM4, KEY_UP_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM5, KEY_NUM2, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM6, KEY_UP_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_LEFT, KEY_NUM4, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_RIGHT, KEY_NUM6, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM8, KEY_NUM5, RectSnap.EXT_SOUTH, false); break; case TYPE_NUM_ARR: default: Arrays.fill(keyScales, 1.0f); setSnap(KEY_DOWN_RIGHT, SCREEN, RectSnap.INT_SOUTHEAST, true); setSnap(KEY_DOWN, KEY_DOWN_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_DOWN_LEFT, KEY_DOWN, RectSnap.EXT_WEST, true); setSnap(KEY_LEFT, KEY_DOWN_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_RIGHT, KEY_DOWN_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP_RIGHT, KEY_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_UP_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, true); setSnap(KEY_FIRE, KEY_DOWN_RIGHT, RectSnap.EXT_NORTHWEST, true); setSnap(KEY_SOFT_LEFT, KEY_UP_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_STAR, SCREEN, RectSnap.INT_SOUTHWEST, true); setSnap(KEY_NUM0, KEY_STAR, RectSnap.EXT_EAST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_D, KEY_NUM1, RectSnap.EXT_NORTH, false); setSnap(KEY_C, KEY_NUM3, RectSnap.EXT_NORTH, false); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_MENU, KEY_UP, RectSnap.EXT_NORTH, false); break; case TYPE_ARR_NUM: Arrays.fill(keyScales, 1); setSnap(KEY_DOWN_LEFT, SCREEN, RectSnap.INT_SOUTHWEST, true); setSnap(KEY_DOWN, KEY_DOWN_LEFT, RectSnap.EXT_EAST, true); setSnap(KEY_DOWN_RIGHT, KEY_DOWN, RectSnap.EXT_EAST, true); setSnap(KEY_LEFT, KEY_DOWN_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_RIGHT, KEY_DOWN_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP_RIGHT, KEY_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_UP_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, true); setSnap(KEY_FIRE, KEY_DOWN_RIGHT, RectSnap.EXT_NORTHWEST, true); setSnap(KEY_SOFT_LEFT, KEY_UP_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_SOFT_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_POUND, SCREEN, RectSnap.INT_SOUTHEAST, true); setSnap(KEY_NUM0, KEY_POUND, RectSnap.EXT_WEST, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_D, KEY_NUM1, RectSnap.EXT_NORTH, false); setSnap(KEY_C, KEY_NUM3, RectSnap.EXT_NORTH, false); setSnap(KEY_A, SCREEN, RectSnap.INT_NORTHWEST, false); setSnap(KEY_B, SCREEN, RectSnap.INT_NORTHEAST, false); setSnap(KEY_MENU, KEY_UP, RectSnap.EXT_NORTH, false); break; case TYPE_NUMBERS: Arrays.fill(keyScales, 1); setSnap(KEY_NUM0, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_STAR, KEY_NUM0, RectSnap.EXT_WEST, true); setSnap(KEY_POUND, KEY_NUM0, RectSnap.EXT_EAST, true); setSnap(KEY_NUM7, KEY_STAR, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM8, KEY_NUM7, RectSnap.EXT_EAST, true); setSnap(KEY_NUM9, KEY_NUM8, RectSnap.EXT_EAST, true); setSnap(KEY_NUM4, KEY_NUM7, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM5, KEY_NUM4, RectSnap.EXT_EAST, true); setSnap(KEY_NUM6, KEY_NUM5, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM4, RectSnap.EXT_NORTH, true); setSnap(KEY_NUM2, KEY_NUM1, RectSnap.EXT_EAST, true); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, true); setSnap(KEY_SOFT_LEFT, KEY_NUM1, RectSnap.EXT_WEST, true); setSnap(KEY_SOFT_RIGHT, KEY_NUM3, RectSnap.EXT_EAST, true); setSnap(KEY_UP, SCREEN, RectSnap.INT_NORTH, false); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, false); setSnap(KEY_UP_RIGHT, KEY_UP, RectSnap.EXT_EAST, false); setSnap(KEY_FIRE, KEY_UP, RectSnap.EXT_SOUTH, false); setSnap(KEY_LEFT, KEY_UP_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_LEFT, KEY_LEFT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN_RIGHT, KEY_RIGHT, RectSnap.EXT_SOUTH, false); setSnap(KEY_DOWN, KEY_DOWN_LEFT, RectSnap.EXT_EAST, false); setSnap(KEY_A, KEY_NUM4, RectSnap.EXT_WEST, false); setSnap(KEY_B, KEY_NUM6, RectSnap.EXT_EAST, false); setSnap(KEY_C, KEY_NUM7, RectSnap.EXT_WEST, false); setSnap(KEY_D, KEY_NUM9, RectSnap.EXT_EAST, false); setSnap(KEY_MENU, SCREEN, RectSnap.INT_NORTHEAST, false); break; case TYPE_ARRAYS: Arrays.fill(keyScales, 1); setSnap(KEY_DOWN, SCREEN, RectSnap.INT_SOUTH, true); setSnap(KEY_DOWN_RIGHT, KEY_DOWN, RectSnap.EXT_EAST, true); setSnap(KEY_DOWN_LEFT, KEY_DOWN, RectSnap.EXT_WEST, true); setSnap(KEY_LEFT, KEY_DOWN_LEFT, RectSnap.EXT_NORTH, true); setSnap(KEY_RIGHT, KEY_DOWN_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP_RIGHT, KEY_RIGHT, RectSnap.EXT_NORTH, true); setSnap(KEY_UP, KEY_UP_RIGHT, RectSnap.EXT_WEST, true); setSnap(KEY_UP_LEFT, KEY_UP, RectSnap.EXT_WEST, true); setSnap(KEY_FIRE, KEY_DOWN_RIGHT, RectSnap.EXT_NORTHWEST, true); setSnap(KEY_SOFT_LEFT, KEY_UP_LEFT, RectSnap.EXT_WEST, true); setSnap(KEY_SOFT_RIGHT, KEY_UP_RIGHT, RectSnap.EXT_EAST, true); setSnap(KEY_NUM1, KEY_NUM2, RectSnap.EXT_WEST, false); setSnap(KEY_NUM2, SCREEN, RectSnap.INT_NORTH, false); setSnap(KEY_NUM3, KEY_NUM2, RectSnap.EXT_EAST, false); setSnap(KEY_NUM4, KEY_NUM1, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM5, KEY_NUM2, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM6, KEY_NUM3, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM7, KEY_NUM4, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM8, KEY_NUM5, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM9, KEY_NUM6, RectSnap.EXT_SOUTH, false); setSnap(KEY_STAR, KEY_NUM7, RectSnap.EXT_SOUTH, false); setSnap(KEY_NUM0, KEY_NUM8, RectSnap.EXT_SOUTH, false); setSnap(KEY_POUND, KEY_NUM9, RectSnap.EXT_SOUTH, false); setSnap(KEY_A, KEY_LEFT, RectSnap.EXT_WEST, false); setSnap(KEY_B, KEY_RIGHT, RectSnap.EXT_EAST, false); setSnap(KEY_C, KEY_DOWN_LEFT, RectSnap.EXT_WEST, false); setSnap(KEY_D, KEY_DOWN_RIGHT, RectSnap.EXT_EAST, false); setSnap(KEY_MENU, SCREEN, RectSnap.INT_NORTHEAST, false); break; } } public int getLayout() { return layoutVariant; } public float getPhoneKeyboardHeight() { return PHONE_KEY_ROWS * keySize * PHONE_KEY_SCALE_Y; } public void setLayout(int variant) { resetLayout(variant); if (variant == TYPE_CUSTOM) { try { readLayout(); } catch (IOException ioe) { ioe.printStackTrace(); resetLayout(layoutVariant); return; } } onLayoutChanged(variant); for (int group = 0; group < keyScaleGroups.length; group++) { resizeKeyGroup(group); } snapKeys(); overlayView.postInvalidate(); if (target != null && target.isShown()) { target.updateSize(); } } private void saveLayout() throws IOException { try (RandomAccessFile raf = new RandomAccessFile(saveFile, "rw")) { int variant = layoutVariant; if (variant != TYPE_CUSTOM && raf.length() > 16) { try { if (raf.readInt() != LAYOUT_SIGNATURE) { throw new IOException("file signature not found"); } int version = raf.readInt(); if (version < 1 || version > LAYOUT_VERSION) { throw new IOException("incompatible file version"); } loop:while (true) { int block = raf.readInt(); int length = raf.readInt(); switch (block) { case LAYOUT_EOF: raf.seek(raf.getFilePointer() - 8); raf.writeInt(LAYOUT_TYPE); raf.writeInt(1); raf.write(variant); raf.writeInt(LAYOUT_EOF); raf.writeInt(0); return; case LAYOUT_TYPE: raf.write(variant); return; default: if (raf.skipBytes(length) != length) { break loop; } break; } } } catch (IOException e) { e.printStackTrace(); } } raf.seek(0); raf.writeInt(LAYOUT_SIGNATURE); raf.writeInt(LAYOUT_VERSION); raf.writeInt(LAYOUT_TYPE); raf.writeInt(1); raf.write(variant); if (variant != TYPE_CUSTOM) { raf.writeInt(LAYOUT_EOF); raf.writeInt(0); raf.setLength(raf.getFilePointer()); return; } raf.writeInt(LAYOUT_KEYS); raf.writeInt(keypad.length * 21 + 4); raf.writeInt(keypad.length); for (VirtualKey key : keypad) { raf.writeInt(key.hashCode()); raf.writeBoolean(key.visible); raf.writeInt(key.snapOrigin); raf.writeInt(key.snapMode); PointF snapOffset = key.snapOffset; raf.writeFloat(snapOffset.x); raf.writeFloat(snapOffset.y); } raf.writeInt(LAYOUT_SCALES); raf.writeInt(keyScales.length * 4 + 4); raf.writeInt(keyScales.length); for (float keyScale : keyScales) { raf.writeFloat(keyScale); } raf.writeInt(LAYOUT_EOF); raf.writeInt(0); raf.setLength(raf.getFilePointer()); } } private int readLayoutType() { try (DataInputStream dis = new DataInputStream(new FileInputStream(saveFile))) { if (dis.readInt() != LAYOUT_SIGNATURE) { throw new IOException("file signature not found"); } int version = dis.readInt(); if (version < 1 || version > LAYOUT_VERSION) { throw new IOException("incompatible file version"); } while (true) { int block = dis.readInt(); int length = dis.readInt(); switch (block) { case LAYOUT_EOF: return -1; case LAYOUT_TYPE: return dis.read(); default: if (dis.skipBytes(length) != length) { return -1; } } } } catch (IOException e) { e.printStackTrace(); } return -1; } private void readLayout() throws IOException { try (DataInputStream dis = new DataInputStream(new FileInputStream(saveFile))) { if (dis.readInt() != LAYOUT_SIGNATURE) { throw new IOException("file signature not found"); } int version = dis.readInt(); if (version < 1 || version > LAYOUT_VERSION) { throw new IOException("incompatible file version"); } while (true) { int block = dis.readInt(); int length = dis.readInt(); int count; switch (block) { case LAYOUT_EOF: return; case LAYOUT_KEYS: count = dis.readInt(); for (int i = 0; i < count; i++) { int hash = dis.readInt(); boolean found = false; for (VirtualKey key : keypad) { if (key.hashCode() == hash) { if (version >= 2) { key.visible = dis.readBoolean(); } key.snapOrigin = dis.readInt(); key.snapMode = dis.readInt(); key.snapOffset.x = dis.readFloat(); key.snapOffset.y = dis.readFloat(); found = true; break; } } if (!found) { dis.skipBytes(version >= 2 ? 17 : 16); } } break; case LAYOUT_SCALES: count = dis.readInt(); if (version >= 3) { for (int i = 0; i < count; i++) { keyScales[i] = dis.readFloat(); } } else if (count * 2 <= keyScales.length) { for (int i = 0; i < keyScales.length; i++) { float v = dis.readFloat(); keyScales[i++] = v; keyScales[i] = v; } } else { dis.skipBytes(count * 4); } break; default: dis.skipBytes(length); break; } } } } public String[] getKeyNames() { String[] names = new String[KEYBOARD_SIZE]; for (int i = 0; i < KEYBOARD_SIZE; i++) { names[i] = keypad[i].label; } return names; } public boolean[] getKeysVisibility() { boolean[] states = new boolean[KEYBOARD_SIZE]; for (int i = 0; i < KEYBOARD_SIZE; i++) { states[i] = !keypad[i].visible; } return states; } public void setKeysVisibility(SparseBooleanArray states) { for (int i = 0; i < states.size(); i++) { keypad[states.keyAt(i)].visible = !states.valueAt(i); } overlayView.postInvalidate(); } @Override public void setTarget(Canvas canvas) { target = canvas; highlightGroup(-1); } private void setSnap(int key, int origin, int mode, boolean visible) { VirtualKey vKey = keypad[key]; vKey.snapOrigin = origin; vKey.snapMode = mode; vKey.snapOffset.set(0, 0); vKey.snapValid = false; vKey.visible = visible; } private boolean findSnap(int target, int origin) { VirtualKey tk = keypad[target]; VirtualKey ok = keypad[origin]; tk.snapMode = RectSnap.getSnap(tk.rect, ok.rect, snapRadius, RectSnap.COARSE_MASK, true); if (tk.snapMode != RectSnap.NO_SNAP) { tk.snapOrigin = origin; tk.snapOffset.set(0, 0); for (int i = 0; i < keypad.length; i++) { origin = keypad[origin].snapOrigin; if (origin == SCREEN) { return true; } } } return false; } private void snapKey(int key, int level) { if (level >= snapStack.length) { Log.d(TAG, "Snap loop detected: "); for (int i = 1; i < snapStack.length; i++) { System.out.print(snapStack[i]); System.out.print(", "); } Log.d(TAG, String.valueOf(key)); return; } snapStack[level] = key; VirtualKey vKey = keypad[key]; if (vKey.snapOrigin == SCREEN) { RectSnap.snap(vKey.rect, screen, vKey.snapMode, vKey.snapOffset); } else { if (!keypad[vKey.snapOrigin].snapValid) { snapKey(vKey.snapOrigin, level + 1); } RectSnap.snap(vKey.rect, keypad[vKey.snapOrigin].rect, vKey.snapMode, vKey.snapOffset); } vKey.snapValid = true; } private void snapKeys() { obscuresVirtualScreen = false; boolean isPhone = isPhone(); for (int i = 0; i < keypad.length; i++) { snapKey(i, 0); VirtualKey key = keypad[i]; RectF rect = key.rect; key.corners = (int) (Math.min(rect.width(), rect.height()) * 0.25F); if (!isPhone && RectF.intersects(rect, virtualScreen)) { obscuresVirtualScreen = true; key.opaque = false; } else { key.opaque = true; } } boolean opaque = !obscuresVirtualScreen || settings.vkForceOpacity; for (VirtualKey key : keypad) { key.opaque &= opaque; } } public boolean isPhone() { return layoutVariant == TYPE_PHONE || layoutVariant == TYPE_PHONE_ARROWS; } private void highlightGroup(int group) { for (VirtualKey aKeypad : keypad) { aKeypad.selected = false; } if (group >= 0) { for (int key = 0; key < keyScaleGroups[group].length; key++) { keypad[keyScaleGroups[group][key]].selected = true; } } } public int getLayoutEditMode() { return layoutEditMode; } public void setLayoutEditMode(int mode) { layoutEditMode = mode; int group = -1; if (mode == LAYOUT_SCALES) { editedIndex = 0; group = 0; } highlightGroup(group); handler.removeCallbacks(this); visible = true; overlayView.postInvalidate(); hide(); if (target != null && target.isShown()) { target.updateSize(); } } private void resizeKey(int key, float w, float h) { VirtualKey vKey = keypad[key]; vKey.resize(w, h); vKey.snapValid = false; } private void resizeKeyGroup(int group) { float sizeX = (float) Math.ceil(keySize * keyScales[group * 2]); float sizeY = (float) Math.ceil(keySize * keyScales[group * 2 + 1]); for (int key = 0; key < keyScaleGroups[group].length; key++) { resizeKey(keyScaleGroups[group][key], sizeX, sizeY); } } @Override public void resize(RectF screen, RectF virtualScreen) { this.screen = screen; this.virtualScreen = virtualScreen; snapRadius = keyScales[0]; for (int i = 1; i < keyScales.length; i++) { if (keyScales[i] < snapRadius) { snapRadius = keyScales[i]; } } float min = overlayView.getWidth(); float max = overlayView.getHeight(); if (min > max) { float tmp = max; max = min; min = tmp; } float keySize = min / 6.5f; keySize = isPhone() ? keySize : Math.min(keySize, max / 12.0f); snapRadius = keySize * snapRadius / 4; this.keySize = keySize; for (int group = 0; group < keyScaleGroups.length; group++) { resizeKeyGroup(group); } snapKeys(); overlayView.postInvalidate(); int delay = settings.vkHideDelay; if (delay > 0 && obscuresVirtualScreen && layoutEditMode == LAYOUT_EOF) { for (VirtualKey key : associatedKeys) { if (key != null) { return; } } handler.postDelayed(this, delay); } } @Override public void paint(CanvasWrapper g) { if (visible) { for (VirtualKey key : keypad) { if (key.visible) { key.paint(g); } } } } @Override public boolean pointerPressed(int pointer, float x, float y) { switch (layoutEditMode) { case LAYOUT_EOF: if (pointer > associatedKeys.length) { return false; } for (VirtualKey key : keypad) { if (key.contains(x, y)) { vibrate(); associatedKeys[pointer] = key; key.onDown(); overlayView.postInvalidate(); break; } } break; case LAYOUT_KEYS: editedIndex = -1; for (int i = 0; i < keypad.length; i++) { if (keypad[i].contains(x, y)) { editedIndex = i; RectF rect = keypad[i].rect; offsetX = x - rect.left; offsetY = y - rect.top; break; } } break; case LAYOUT_SCALES: int index = -1; for (int group = 0; group < keyScaleGroups.length && index < 0; group++) { for (int key = 0; key < keyScaleGroups[group].length && index < 0; key++) { if (keypad[keyScaleGroups[group][key]].contains(x, y)) { index = group; } } } if (index >= 0) { editedIndex = index; highlightGroup(index); overlayView.postInvalidate(); } offsetX = x; offsetY = y; prevScaleX = keyScales[editedIndex * 2]; prevScaleY = keyScales[editedIndex * 2 + 1]; break; } return false; } @Override public boolean pointerDragged(int pointer, float x, float y) { switch (layoutEditMode) { case LAYOUT_EOF: if (pointer > associatedKeys.length) { return false; } VirtualKey aKey = associatedKeys[pointer]; if (aKey == null) { pointerPressed(pointer, x, y); } else if (!aKey.contains(x, y)) { associatedKeys[pointer] = null; aKey.onUp(); overlayView.postInvalidate(); pointerPressed(pointer, x, y); } break; case LAYOUT_KEYS: if (editedIndex >= 0) { VirtualKey key = keypad[editedIndex]; RectF rect = key.rect; rect.offsetTo(x - offsetX, y - offsetY); key.snapMode = RectSnap.NO_SNAP; for (int i = 0; i < keypad.length; i++) { if (i != editedIndex && findSnap(editedIndex, i)) { break; } } if (key.snapMode == RectSnap.NO_SNAP) { key.snapMode = RectSnap.getSnap(rect, screen, key.snapOffset); key.snapOrigin = SCREEN; if (Math.abs(key.snapOffset.x) <= snapRadius) { key.snapOffset.x = 0; } if (Math.abs(key.snapOffset.y) <= snapRadius) { key.snapOffset.y = 0; } } snapKey(editedIndex, 0); overlayView.postInvalidate(); } break; case LAYOUT_SCALES: float dx = x - offsetX; float dy = offsetY - y; float scale; int index = this.editedIndex * 2; if (Math.abs(dx) > Math.abs(dy)) { scale = prevScaleX + dx / Math.min(screen.centerX(), screen.centerY()); } else { scale = prevScaleY + dy / Math.min(screen.centerX(), screen.centerY()); index++; } if (Math.abs(1 - scale) <= SCALE_SNAP_RADIUS) { scale = 1; } else { for (int i = index % 2; i < keyScales.length; i += 2) { if (i != index && Math.abs(keyScales[i] - scale) <= SCALE_SNAP_RADIUS) { scale = keyScales[i]; break; } } } keyScales[index] = scale; resizeKeyGroup(this.editedIndex); snapKeys(); overlayView.postInvalidate(); break; } return false; } @Override public boolean pointerReleased(int pointer, float x, float y) { if (layoutEditMode == LAYOUT_EOF) { if (pointer > associatedKeys.length) { return false; } VirtualKey key = associatedKeys[pointer]; if (key != null) { associatedKeys[pointer] = null; key.onUp(); overlayView.postInvalidate(); } } else if (layoutEditMode == LAYOUT_KEYS) { for (int key = 0; key < keypad.length; key++) { VirtualKey vKey = keypad[key]; if (vKey.snapOrigin == editedIndex) { vKey.snapMode = RectSnap.NO_SNAP; for (int i = 0; i < KEYBOARD_SIZE; i++) { if (i != key && findSnap(key, i)) { break; } } if (vKey.snapMode == RectSnap.NO_SNAP) { vKey.snapMode = RectSnap.getSnap(vKey.rect, screen, vKey.snapOffset); vKey.snapOrigin = SCREEN; if (Math.abs(vKey.snapOffset.x) <= snapRadius) { vKey.snapOffset.x = 0; } if (Math.abs(vKey.snapOffset.y) <= snapRadius) { vKey.snapOffset.y = 0; } } snapKey(key, 0); } } snapKeys(); editedIndex = -1; } return false; } @Override public void show() { if (settings.vkHideDelay > 0 && obscuresVirtualScreen) { handler.removeCallbacks(this); if (!visible) { visible = true; overlayView.postInvalidate(); } } } @Override public void hide() { long delay = settings.vkHideDelay; if (delay > 0 && obscuresVirtualScreen && layoutEditMode == LAYOUT_EOF) { handler.postDelayed(this, delay); } } @Override public void cancel() { for (VirtualKey key : keypad) { key.selected = false; handler.removeCallbacks(key); } } @Override public void run() { visible = false; overlayView.postInvalidate(); } @Override public boolean keyPressed(int keyCode) { int hashCode = 31 * (31 + keyCode); for (VirtualKey key : keypad) { if (key.hashCode == hashCode) { key.selected = true; overlayView.postInvalidate(); break; } } return false; } @Override public boolean keyRepeated(int keyCode) { return false; } @Override public boolean keyReleased(int keyCode) { int hashCode = 31 * (31 + keyCode); for (VirtualKey key : keypad) { if (key.hashCode == hashCode) { key.selected = false; overlayView.postInvalidate(); break; } } return false; } private void vibrate() { if (settings.vkFeedback) ContextHolder.vibrateKey(FEEDBACK_DURATION); } public void setView(View view) { overlayView = view; } public int getKeyStatesVodafone() { int keyStates = 0; for (int i = 0; i < keypad.length; i++) { VirtualKey key = keypad[i]; if (key.selected) { keyStates |= getKeyBit(i); } } return keyStates; } private int getKeyBit(int vKey) { switch (vKey) { case KEY_NUM0 : return 1; // 0 0 key KEY_NUM0 = 9; case KEY_NUM1 : return 1 << 1; // 1 1 key KEY_NUM1 = 0; case KEY_NUM2 : return 1 << 2; // 2 2 key KEY_NUM2 = 1; case KEY_NUM3 : return 1 << 3; // 3 3 key KEY_NUM3 = 2; case KEY_NUM4 : return 1 << 4; // 4 4 key KEY_NUM4 = 3; case KEY_NUM5 : return 1 << 5; // 5 5 key KEY_NUM5 = 4; case KEY_NUM6 : return 1 << 6; // 6 6 key KEY_NUM6 = 5; case KEY_NUM7 : return 1 << 7; // 7 7 key KEY_NUM7 = 6; case KEY_NUM8 : return 1 << 8; // 8 8 key KEY_NUM8 = 7; case KEY_NUM9 : return 1 << 9; // 9 9 key KEY_NUM9 = 8; case KEY_STAR : return 1 << 10; // 10 * key KEY_STAR = 10; case KEY_POUND : return 1 << 11; // 11 # key KEY_POUND = 11; case KEY_UP : return 1 << 12; // 12 Up key KEY_UP = 17; case KEY_LEFT : return 1 << 13; // 13 Left key KEY_LEFT = 19; case KEY_RIGHT : return 1 << 14; // 14 Right key KEY_RIGHT = 20; case KEY_DOWN : return 1 << 15; // 15 Down key KEY_DOWN = 22; case KEY_FIRE : return 1 << 16; // 16 Select key KEY_FIRE = 24; case KEY_SOFT_LEFT : return 1 << 17; // 17 Softkey 1 KEY_SOFT_LEFT = 12; case KEY_SOFT_RIGHT: return 1 << 18; // 18 Softkey 2 KEY_SOFT_RIGHT = 13; // TODO: 05.08.2020 Softkey3 mapped to KEY_C case KEY_C : return 1 << 19; // 19 Softkey 3 KEY_C = 15; case KEY_UP_RIGHT : return 1 << 20; // 20 Upper Right KEY_UP_RIGHT = 18; case KEY_UP_LEFT : return 1 << 21; // 21 Upper Left KEY_UP_LEFT = 16; case KEY_DOWN_RIGHT: return 1 << 22; // 22 Lower Right KEY_DOWN_RIGHT = 23; case KEY_DOWN_LEFT : return 1 << 23; // 23 Lower Left KEY_DOWN_LEFT = 21; } return 0; } private class VirtualKey implements Runnable { final String label; final int keyCode; final RectF rect = new RectF(); final PointF snapOffset = new PointF(); int snapOrigin; int snapMode; boolean snapValid; boolean selected; boolean visible = true; boolean opaque = true; int corners; private final int hashCode; private int repeatCount; VirtualKey(int keyCode, String label) { this.keyCode = keyCode; this.label = label; hashCode = 31 * (31 + this.keyCode); } void resize(float width, float height) { rect.right = rect.left + width; rect.bottom = rect.top + height; } boolean contains(float x, float y) { return visible && rect.contains(x, y); } void paint(CanvasWrapper g) { int bgColor; int fgColor; if (selected) { bgColor = settings.vkBgColorSelected; fgColor = settings.vkFgColorSelected; } else { bgColor = settings.vkBgColor; fgColor = settings.vkFgColor; } int alpha = (opaque || layoutEditMode != LAYOUT_EOF ? 0xFF : settings.vkAlpha) << 24; g.setFillColor(alpha | bgColor); g.setTextColor(alpha | fgColor); g.setDrawColor(alpha | settings.vkOutlineColor); switch (settings.vkButtonShape) { case ROUND_RECT_SHAPE: g.fillRoundRect(rect, corners, corners); g.drawRoundRect(rect, corners, corners); break; case RECT_SHAPE: g.fillRect(rect); g.drawRect(rect); break; case OVAL_SHAPE: g.fillArc(rect, 0, 360); g.drawArc(rect, 0, 360); break; } g.drawString(label, rect.centerX(), rect.centerY()); } @NonNull public String toString() { return "[" + label + ": " + rect.left + ", " + rect.top + ", " + rect.right + ", " + rect.bottom + "]"; } public int hashCode() { return hashCode; } @Override public void run() { if (target == null) { selected = false; repeatCount = 0; return; } if (selected) { onRepeat(); } else { repeatCount = 0; } } public void onRepeat() { handler.postDelayed(this, repeatCount > 6 ? 80 : REPEAT_INTERVALS[repeatCount++]); target.postKeyRepeated(keyCode); } protected void onDown() { selected = true; target.postKeyPressed(keyCode); handler.postDelayed(this, 400); } public void onUp() { selected = false; handler.removeCallbacks(this); target.postKeyReleased(keyCode); } } private class DualKey extends VirtualKey { final int secondKeyCode; private final int hashCode; DualKey(int keyCode, int secondKeyCode, String label) { super(keyCode, label); if (secondKeyCode == 0) throw new IllegalArgumentException(); this.secondKeyCode = secondKeyCode; hashCode = 31 * (31 + this.keyCode) + this.secondKeyCode; } @Override protected void onDown() { super.onDown(); target.postKeyPressed(secondKeyCode); } @Override public void onUp() { super.onUp(); target.postKeyReleased(secondKeyCode); } @Override public void onRepeat() { super.onRepeat(); target.postKeyRepeated(secondKeyCode); } @Override public int hashCode() { return hashCode; } } private class MenuKey extends VirtualKey { MenuKey() { super(KeyMapper.KEY_OPTIONS_MENU, "M"); } @Override protected void onDown() { selected = true; handler.postDelayed(this, 500); } @Override public void onUp() { if (selected) { selected = false; handler.removeCallbacks(this); MicroActivity activity = ContextHolder.getActivity(); if (activity != null) { activity.openOptionsMenu(); } } } @Override public void run() { selected = false; MicroActivity activity = ContextHolder.getActivity(); if (activity != null) { activity.showExitConfirmation(); } } } }
Fix DualKey hashcodes
app/src/main/java/javax/microedition/lcdui/keyboard/VirtualKeyboard.java
Fix DualKey hashcodes
<ide><path>pp/src/main/java/javax/microedition/lcdui/keyboard/VirtualKeyboard.java <ide> public boolean keyPressed(int keyCode) { <ide> int hashCode = 31 * (31 + keyCode); <ide> for (VirtualKey key : keypad) { <del> if (key.hashCode == hashCode) { <add> if (key.hashCode() == hashCode) { <ide> key.selected = true; <ide> overlayView.postInvalidate(); <ide> break; <ide> public boolean keyReleased(int keyCode) { <ide> int hashCode = 31 * (31 + keyCode); <ide> for (VirtualKey key : keypad) { <del> if (key.hashCode == hashCode) { <add> if (key.hashCode() == hashCode) { <ide> key.selected = false; <ide> overlayView.postInvalidate(); <ide> break;
Java
apache-2.0
4bccb8cb04eb64698e2ad224a7135a27f794a164
0
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
package info.u_team.u_team_test.screen; import org.apache.logging.log4j.*; import com.mojang.blaze3d.matrix.MatrixStack; import info.u_team.u_team_core.gui.elements.*; import info.u_team.u_team_core.gui.renderer.*; import info.u_team.u_team_core.util.RGBA; import info.u_team.u_team_test.TestMod; import net.minecraft.client.gui.screen.Screen; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.*; public class ButtonTestScreen extends Screen { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation TEXTURE1 = new ResourceLocation(TestMod.MODID, "textures/item/better_enderpearl.png"); private static final ResourceLocation TEXTURE2 = new ResourceLocation(TestMod.MODID, "textures/item/basicitem.png"); public ButtonTestScreen() { super(new StringTextComponent("test")); } private ScalingTextRenderer scalingRenderer; private ScrollingTextRenderer scrollingRenderer; @Override protected void init() { // U Button Test final UButton uButton = addButton(new UButton(10, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("U Button"))); uButton.setPressable(() -> LOGGER.info("Pressed U Button")); uButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("U Button Tooltip"), mouseX, mouseY); } }); // Scalable Button Test final ScalableButton scalableButton = addButton(new ScalableButton(10, 30, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Button"), 0.75F)); scalableButton.setTextColor(new RGBA(0x00FFFF80)); scalableButton.setPressable(button -> LOGGER.info("Pressed Scalable Button")); scalableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Button Tooltip"), mouseX, mouseY); } }); // Scalable Activatable Button Test final ScalableActivatableButton scalableActivatableButton = addButton(new ScalableActivatableButton(10, 50, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button"), 0.75F, false, new RGBA(0x006442FF))); scalableActivatableButton.setPressable(() -> { System.out.println("Pressed Scalable Activatable Button"); scalableActivatableButton.setActivated(!scalableActivatableButton.isActivated()); }); scalableActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button Tooltip"), mouseX, mouseY); } }); // Image Button Test final ImageButton imageButton = addButton(new ImageButton(10, 70, 15, 15, TEXTURE1)); imageButton.setPressable(() -> { System.out.println("Pressed Image Button"); }); imageButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button Tooltip"), mouseX, mouseY); } }); final ImageButton imageButton2 = addButton(new ImageButton(30, 70, 15, 15, TEXTURE1)); imageButton2.setButtonColor(new RGBA(0xFFFF2080)); imageButton2.setImageColor(new RGBA(0x00FFFF80)); imageButton2.setPressable(() -> { System.out.println("Pressed Image Button 2"); }); imageButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button 2 Tooltip"), mouseX, mouseY); } }); // Image Activatable Button Test final ImageActivatableButton imageActivatableButton = addButton(new ImageActivatableButton(10, 90, 15, 15, TEXTURE1, false, new RGBA(0x006442FF))); imageActivatableButton.setPressable(() -> { System.out.println("Pressed Image Activatable Button"); imageActivatableButton.setActivated(!imageActivatableButton.isActivated()); }); imageActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Activatable Button Tooltip"), mouseX, mouseY); } }); // Image Toggle Button Test final ImageToggleButton imageToggleButton = addButton(new ImageToggleButton(10, 110, 15, 15, TEXTURE1, TEXTURE2, false)); imageToggleButton.setPressable(() -> { System.out.println("Pressed Image Toggle Button"); }); imageToggleButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button Tooltip"), mouseX, mouseY); } }); final ImageToggleButton imageToggleButton2 = addButton(new ImageToggleButton(30, 110, 15, 15, TEXTURE1, TEXTURE1, false)); imageToggleButton2.setImageColor(new RGBA(0x0000FFFF)); imageToggleButton2.setToggleImageColor(new RGBA(0xFF0000FF)); imageToggleButton2.setPressable(() -> { System.out.println("Pressed Image Toggle Button 2"); }); imageToggleButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button 2 Tooltip"), mouseX, mouseY); } }); addButton(new BetterFontSlider(300, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("Test: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 0.75F, slider -> { System.out.println("Updated slider value: " + slider.getValueInt() + " --> draging: " + slider.dragging); })); addButton(new BetterFontSlider(300, 30, 200, 40, ITextComponent.getTextComponentOrEmpty("Test: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 2, slider -> { System.out.println("Updated slider value: " + slider.getValueInt() + " --> draging: " + slider.dragging); })); scalingRenderer = new ScalingTextRenderer(() -> font, () -> "This is a test for the scaling text renderer"); scalingRenderer.setColor(0xFFFFFF); scalingRenderer.setScale(2); scrollingRenderer = new ScrollingTextRenderer(() -> font, () -> "This is a test for the scrolling text renderer that should be really long to test the scrolling"); scrollingRenderer.setColor(0xFFFFFF); scrollingRenderer.setWidth(200); scrollingRenderer.setScale(0.75F); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { renderBackground(matrixStack); super.render(matrixStack, mouseX, mouseY, partialTicks); scalingRenderer.render(matrixStack, 10, 145); scrollingRenderer.render(matrixStack, 10, 170); buttons.forEach(widget -> widget.renderToolTip(matrixStack, mouseX, mouseY)); } }
src/test/java/info/u_team/u_team_test/screen/ButtonTestScreen.java
package info.u_team.u_team_test.screen; import org.apache.logging.log4j.*; import com.mojang.blaze3d.matrix.MatrixStack; import info.u_team.u_team_core.gui.elements.*; import info.u_team.u_team_core.gui.renderer.*; import info.u_team.u_team_core.util.RGBA; import info.u_team.u_team_test.TestMod; import net.minecraft.client.gui.screen.Screen; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.*; public class ButtonTestScreen extends Screen { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation TEXTURE1 = new ResourceLocation(TestMod.MODID, "textures/item/better_enderpearl.png"); private static final ResourceLocation TEXTURE2 = new ResourceLocation(TestMod.MODID, "textures/item/basicitem.png"); public ButtonTestScreen() { super(new StringTextComponent("test")); } private ScalingTextRenderer scalingRenderer; private ScrollingTextRenderer scrollingRenderer; @Override protected void init() { // U Button Test final UButton uButton = addButton(new UButton(10, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("U Button"))); uButton.setPressable(() -> LOGGER.info("Pressed U Button")); uButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("U Button Tooltip"), mouseX, mouseY); } }); // Scalable Button Test final ScalableButton scalableButton = addButton(new ScalableButton(10, 30, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Button"), 0.75F)); scalableButton.setTextColor(new RGBA(0x00FFFF80)); scalableButton.setPressable(button -> LOGGER.info("Pressed Scalable Button")); scalableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Button Tooltip"), mouseX, mouseY); } }); // Scalable Activatable Button Test final ScalableActivatableButton scalableActivatableButton = addButton(new ScalableActivatableButton(10, 50, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button"), 0.75F, false, new RGBA(0x006442FF))); scalableActivatableButton.setPressable(() -> { System.out.println("Pressed Scalable Activatable Button"); scalableActivatableButton.setActivated(!scalableActivatableButton.isActivated()); }); scalableActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button Tooltip"), mouseX, mouseY); } }); // Image Button Test final ImageButton imageButton = addButton(new ImageButton(10, 70, 15, 15, TEXTURE1)); imageButton.setPressable(() -> { System.out.println("Pressed Image Button"); }); imageButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button Tooltip"), mouseX, mouseY); } }); final ImageButton imageButton2 = addButton(new ImageButton(30, 70, 15, 15, TEXTURE1)); imageButton2.setButtonColor(new RGBA(0xFFFF2080)); imageButton2.setImageColor(new RGBA(0x00FFFF80)); imageButton2.setPressable(() -> { System.out.println("Pressed Image Button 2"); }); imageButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button 2 Tooltip"), mouseX, mouseY); } }); // Image Activatable Button Test final ImageActivatableButton imageActivatableButton = addButton(new ImageActivatableButton(10, 90, 20, 20, TEXTURE1, false, new RGBA(0x006442FF))); imageActivatableButton.setPressable(() -> { System.out.println("Pressed Image Activatable Button"); imageActivatableButton.setActivated(!imageActivatableButton.isActivated()); }); imageActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Activatable Button Tooltip"), mouseX, mouseY); } }); final ToggleImageButton toggleImageButton = addButton(new ToggleImageButton(10, 115, 20, 20, TEXTURE1, TEXTURE2)); toggleImageButton.setPressable(() -> { System.out.println("Pressed ToggleImageButton"); }); addButton(new BetterFontSlider(300, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("Test: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 0.75F, slider -> { System.out.println("Updated slider value: " + slider.getValueInt() + " --> draging: " + slider.dragging); })); addButton(new BetterFontSlider(300, 30, 200, 40, ITextComponent.getTextComponentOrEmpty("Test: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 2, slider -> { System.out.println("Updated slider value: " + slider.getValueInt() + " --> draging: " + slider.dragging); })); scalingRenderer = new ScalingTextRenderer(() -> font, () -> "This is a test for the scaling text renderer"); scalingRenderer.setColor(0xFFFFFF); scalingRenderer.setScale(2); scrollingRenderer = new ScrollingTextRenderer(() -> font, () -> "This is a test for the scrolling text renderer that should be really long to test the scrolling"); scrollingRenderer.setColor(0xFFFFFF); scrollingRenderer.setWidth(200); scrollingRenderer.setScale(0.75F); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { renderBackground(matrixStack); super.render(matrixStack, mouseX, mouseY, partialTicks); scalingRenderer.render(matrixStack, 10, 145); scrollingRenderer.render(matrixStack, 10, 170); buttons.forEach(widget -> widget.renderToolTip(matrixStack, mouseX, mouseY)); } }
Add all buttons again
src/test/java/info/u_team/u_team_test/screen/ButtonTestScreen.java
Add all buttons again
<ide><path>rc/test/java/info/u_team/u_team_test/screen/ButtonTestScreen.java <ide> }); <ide> <ide> // Image Activatable Button Test <del> final ImageActivatableButton imageActivatableButton = addButton(new ImageActivatableButton(10, 90, 20, 20, TEXTURE1, false, new RGBA(0x006442FF))); <add> final ImageActivatableButton imageActivatableButton = addButton(new ImageActivatableButton(10, 90, 15, 15, TEXTURE1, false, new RGBA(0x006442FF))); <ide> imageActivatableButton.setPressable(() -> { <ide> System.out.println("Pressed Image Activatable Button"); <ide> imageActivatableButton.setActivated(!imageActivatableButton.isActivated()); <ide> } <ide> }); <ide> <del> final ToggleImageButton toggleImageButton = addButton(new ToggleImageButton(10, 115, 20, 20, TEXTURE1, TEXTURE2)); <del> toggleImageButton.setPressable(() -> { <del> System.out.println("Pressed ToggleImageButton"); <add> // Image Toggle Button Test <add> final ImageToggleButton imageToggleButton = addButton(new ImageToggleButton(10, 110, 15, 15, TEXTURE1, TEXTURE2, false)); <add> imageToggleButton.setPressable(() -> { <add> System.out.println("Pressed Image Toggle Button"); <add> }); <add> imageToggleButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { <add> if (button.isHovered()) { <add> renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button Tooltip"), mouseX, mouseY); <add> } <add> }); <add> <add> final ImageToggleButton imageToggleButton2 = addButton(new ImageToggleButton(30, 110, 15, 15, TEXTURE1, TEXTURE1, false)); <add> imageToggleButton2.setImageColor(new RGBA(0x0000FFFF)); <add> imageToggleButton2.setToggleImageColor(new RGBA(0xFF0000FF)); <add> imageToggleButton2.setPressable(() -> { <add> System.out.println("Pressed Image Toggle Button 2"); <add> }); <add> imageToggleButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { <add> if (button.isHovered()) { <add> renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button 2 Tooltip"), mouseX, mouseY); <add> } <ide> }); <ide> <ide> addButton(new BetterFontSlider(300, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("Test: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 0.75F, slider -> {
Java
mit
8dff8c411f03bb1de222500208c11dcdf4f808f7
0
gfneto/Hive2Hive,Hive2Hive/Hive2Hive
package org.hive2hive.core.network.data.vdht; import java.io.IOException; import java.security.KeyPair; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Random; import java.util.Set; import java.util.TreeMap; import net.tomp2p.dht.FutureGet; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.rpc.DigestResult; import net.tomp2p.storage.Data; import org.hive2hive.core.H2HConstants; import org.hive2hive.core.exceptions.GetFailedException; import org.hive2hive.core.exceptions.PutFailedException; import org.hive2hive.core.exceptions.VersionForkAfterPutException; import org.hive2hive.core.model.versioned.BaseVersionedNetworkContent; import org.hive2hive.core.network.data.DataManager; import org.hive2hive.core.network.data.DataManager.H2HPutStatus; import org.hive2hive.core.network.data.parameters.IParameters; import org.hive2hive.core.network.data.parameters.Parameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VersionManager<T extends BaseVersionedNetworkContent> { private static final Logger logger = LoggerFactory.getLogger(VersionManager.class); private final DataManager dataManager; private final Parameters parameters; private final Random random = new Random(); // limit constants private static final int getFailedLimit = 2; private static final int forkAfterGetLimit = 2; private static final int delayLimit = 2; // caches private Cache<Set<Number160>> digestCache = new Cache<Set<Number160>>(); private Cache<T> contentCache = new Cache<T>(); public VersionManager(DataManager dataManager, String locationKey, String contentKey) { this.dataManager = dataManager; this.parameters = new Parameters().setLocationKey(locationKey).setContentKey(contentKey); } /** * Performs a get call (blocking). * * @throws GetFailedException */ public T get() throws GetFailedException { // load the current digest list from network NavigableMap<Number640, Collection<Number160>> digest = dataManager.getDigestLatest(parameters); // compare the latest version key with the cached one if (!contentCache.isEmpty() && digest != null && digest.lastEntry() != null && digest.lastEntry().getKey().versionKey().equals(contentCache.lastKey())) { logger.debug("No need for getting from network. Returning cached version. {}", parameters.toString()); return contentCache.lastEntry().getValue(); } else { int delayCounter = 0; int delayWaitTime = random.nextInt(1000) + 1000; int forkAfterGetCounter = 0; int forkAfterGetWaitTime = random.nextInt(1000) + 1000; // fetch latest versions from the network, request also digest while (true) { Cache<T> fetchedVersions = new Cache<T>(); int getCounter = 0; int getWaitTime = random.nextInt(1000) + 1000; while (true) { // load latest data FutureGet futureGet = dataManager.getLatestUnblocked(parameters); futureGet.awaitUninterruptibly(H2HConstants.AWAIT_NETWORK_OPERATION_MS); // build and merge the version tree from raw digest result; digestCache.putAll(buildDigest(futureGet.rawDigest())); // join all freshly loaded versions in one map fetchedVersions.putAll(buildData(futureGet.rawData())); // merge freshly loaded versions with cache contentCache.putAll(fetchedVersions); // check if get was successful if (futureGet.isFailed() || fetchedVersions.isEmpty()) { if (getCounter > getFailedLimit) { logger.warn("Loading of data failed after {} tries. {}", getCounter, parameters.toString()); throw new GetFailedException("Couldn't load data."); } else { logger.warn("Couldn't get data. Try #{}. Retrying. reason = '{}' {}", getCounter++, futureGet.failedReason(), parameters.toString()); // TODO reput latest versions for maintenance // exponential back off waiting try { Thread.sleep(getWaitTime); getWaitTime = getWaitTime * 2; } catch (InterruptedException ignore) { } } } else { break; } } // check if version delays or forks occurred if (hasVersionDelay(fetchedVersions, digestCache) && delayCounter < delayLimit) { logger.warn("Detected a version delay. #{}", delayCounter++); // TODO reput latest versions for maintenance, consider only latest // exponential back off waiting try { Thread.sleep(delayWaitTime); delayWaitTime = delayWaitTime * 2; } catch (InterruptedException ignore) { } continue; } // get latest versions according cache Cache<Set<Number160>> latestVersionKeys = getLatest(digestCache); // check for version fork if (latestVersionKeys.size() > 1 && delayCounter < delayLimit) { if (forkAfterGetCounter < forkAfterGetLimit) { logger.warn("Got a version fork. Waiting. #{}", forkAfterGetCounter++); // exponential back off waiting try { Thread.sleep(forkAfterGetWaitTime); forkAfterGetWaitTime = forkAfterGetWaitTime * 2; } catch (InterruptedException ignore) { } continue; } logger.warn("Got a version fork."); // TODO implement merging throw new GetFailedException("Got a version fork."); } else { if (delayCounter >= delayLimit) { logger.warn("Ignoring delay after {} retries.", delayCounter); } if (contentCache.isEmpty()) { logger.warn("Did not find any version."); throw new GetFailedException("No version found. Got null."); } else { try { return (T) contentCache.lastEntry().getValue(); } catch (Exception e) { logger.error("Cannot get the version.", e); throw new GetFailedException(String.format("Cannot get the version. reason = '%s'", e.getMessage())); } } } } } } /** * Encrypts the modified user profile and puts it (blocking). * * @throws PutFailedException */ public void put(T networkContent, KeyPair protectionKeys) throws PutFailedException { networkContent.generateVersionKey(); IParameters parameters = new Parameters().setLocationKey(this.parameters.getLocationKey()) .setContentKey(this.parameters.getContentKey()).setVersionKey(networkContent.getVersionKey()) .setBasedOnKey(networkContent.getBasedOnKey()).setNetworkContent(networkContent) .setProtectionKeys(protectionKeys).setTTL(networkContent.getTimeToLive()).setPrepareFlag(true); H2HPutStatus status = dataManager.put(parameters); if (status.equals(H2HPutStatus.FAILED)) { throw new PutFailedException("Put failed."); } else if (status.equals(H2HPutStatus.VERSION_FORK)) { logger.warn("Version fork after put detected. Rejecting put"); if (!dataManager.remove(parameters)) { logger.warn("Removing of conflicting version failed."); } throw new VersionForkAfterPutException(); } else { // cache digest digestCache.put(parameters.getVersionKey(), new HashSet<Number160>(parameters.getData().basedOnSet())); // cache network content contentCache.put(parameters.getVersionKey(), networkContent); } } private NavigableMap<Number160, Set<Number160>> buildDigest(Map<PeerAddress, DigestResult> rawDigest) { NavigableMap<Number160, Set<Number160>> digestMap = new TreeMap<Number160, Set<Number160>>(); if (rawDigest == null) { return digestMap; } for (PeerAddress peerAddress : rawDigest.keySet()) { NavigableMap<Number640, Collection<Number160>> tmp = rawDigest.get(peerAddress).keyDigest(); if (tmp == null || tmp.isEmpty()) { // ignore this peer } else { for (Number640 key : tmp.keySet()) { for (Number160 bKey : tmp.get(key)) { if (!digestMap.containsKey(key.versionKey())) { digestMap.put(key.versionKey(), new HashSet<Number160>()); } digestMap.get(key.versionKey()).add(bKey); } } } } return digestMap; } @SuppressWarnings("unchecked") private NavigableMap<Number160, T> buildData(Map<PeerAddress, Map<Number640, Data>> rawData) { NavigableMap<Number160, T> dataMap = new TreeMap<Number160, T>(); if (rawData == null) { return dataMap; } for (PeerAddress peerAddress : rawData.keySet()) { Map<Number640, Data> tmp = rawData.get(peerAddress); if (tmp == null || tmp.isEmpty()) { // ignore this peer } else { for (Number640 key : tmp.keySet()) { try { Object object = tmp.get(key).object(); if (object instanceof BaseVersionedNetworkContent) { dataMap.put(key.versionKey(), (T) tmp.get(key).object()); } else { logger.warn("Received unkown object = '{}'", object.getClass().getSimpleName()); } } catch (ClassNotFoundException | IOException e) { logger.warn("Could not get data. reason = '{}'", e.getMessage()); } } } } return dataMap; } private boolean hasVersionDelay(Map<Number160, ?> latestVersions, Cache<Set<Number160>> digestCache) { for (Number160 version : digestCache.keySet()) { for (Number160 basedOnKey : digestCache.get(version)) { if (latestVersions.containsKey(basedOnKey)) { return true; } } } return false; } private Cache<Set<Number160>> getLatest(Cache<Set<Number160>> cache) { // delete all predecessors Cache<Set<Number160>> tmp = new Cache<Set<Number160>>(cache); Cache<Set<Number160>> result = new Cache<Set<Number160>>(); while (!tmp.isEmpty()) { // last entry is a latest version Entry<Number160, Set<Number160>> latest = tmp.lastEntry(); // store in results list result.put(latest.getKey(), latest.getValue()); // delete all predecessors of latest entry deletePredecessors(latest.getKey(), tmp); } return result; } private void deletePredecessors(Number160 key, Cache<Set<Number160>> cache) { Set<Number160> basedOnSet = cache.remove(key); // check if set has been already deleted if (basedOnSet == null) { return; } // check if version is initial version if (basedOnSet.isEmpty()) { return; } // remove all predecessor versions recursively for (Number160 basedOnKey : basedOnSet) { deletePredecessors(basedOnKey, cache); } } private class Cache<V> extends TreeMap<Number160, V> { private static final long serialVersionUID = 7731754953812711346L; public Cache() { super(); } public Cache(Cache<V> cache) { super(cache); } @Override public void putAll(Map<? extends Number160, ? extends V> map) { super.putAll(map); cleanUp(); } public V put(Number160 key, V value) { try { return super.put(key, value); } finally { cleanUp(); } } private void cleanUp() { if (!isEmpty()) { while (firstKey().timestamp() + H2HConstants.MAX_VERSIONS_HISTORY <= lastKey().timestamp()) { pollFirstEntry(); } } } } }
org.hive2hive.core/src/main/java/org/hive2hive/core/network/data/vdht/VersionManager.java
package org.hive2hive.core.network.data.vdht; import java.io.IOException; import java.security.KeyPair; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Random; import java.util.Set; import java.util.TreeMap; import net.tomp2p.dht.FutureGet; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.rpc.DigestResult; import net.tomp2p.storage.Data; import org.hive2hive.core.H2HConstants; import org.hive2hive.core.exceptions.GetFailedException; import org.hive2hive.core.exceptions.PutFailedException; import org.hive2hive.core.exceptions.VersionForkAfterPutException; import org.hive2hive.core.model.versioned.BaseVersionedNetworkContent; import org.hive2hive.core.network.data.DataManager; import org.hive2hive.core.network.data.DataManager.H2HPutStatus; import org.hive2hive.core.network.data.parameters.IParameters; import org.hive2hive.core.network.data.parameters.Parameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class VersionManager<T extends BaseVersionedNetworkContent> { private static final Logger logger = LoggerFactory.getLogger(VersionManager.class); private final DataManager dataManager; private final Parameters parameters; private final Random random = new Random(); // limit constants private final static int getFailedLimit = 2; private final static int forkAfterGetLimit = 2; private final static int delayLimit = 2; // caches private Cache<Set<Number160>> digestCache = new Cache<Set<Number160>>(); private Cache<T> contentCache = new Cache<T>(); public VersionManager(DataManager dataManager, String locationKey, String contentKey) { this.dataManager = dataManager; this.parameters = new Parameters().setLocationKey(locationKey).setContentKey(contentKey); } /** * Performs a get call (blocking). * * @throws GetFailedException */ public T get() throws GetFailedException { // load the current digest list from network NavigableMap<Number640, Collection<Number160>> digest = dataManager.getDigestLatest(parameters); // compare the latest version key with the cached one if (!contentCache.isEmpty() && digest != null && digest.lastEntry() != null && digest.lastEntry().getKey().versionKey().equals(contentCache.lastKey())) { logger.debug("No need for getting from network. Returning cached version. {}", parameters.toString()); return contentCache.lastEntry().getValue(); } else { int delayCounter = 0; int delayWaitTime = random.nextInt(1000) + 1000; int forkAfterGetCounter = 0; int forkAfterGetWaitTime = random.nextInt(1000) + 1000; // fetch latest versions from the network, request also digest while (true) { Cache<T> fetchedVersions = new Cache<T>(); int getCounter = 0; int getWaitTime = random.nextInt(1000) + 1000; while (true) { // load latest data FutureGet futureGet = dataManager.getLatestUnblocked(parameters); futureGet.awaitUninterruptibly(H2HConstants.AWAIT_NETWORK_OPERATION_MS); // build and merge the version tree from raw digest result; digestCache.putAll(buildDigest(futureGet.rawDigest())); // join all freshly loaded versions in one map fetchedVersions.putAll(buildData(futureGet.rawData())); // merge freshly loaded versions with cache contentCache.putAll(fetchedVersions); // check if get was successful if (futureGet.isFailed() || fetchedVersions.isEmpty()) { if (getCounter > getFailedLimit) { logger.warn("Loading of data failed after {} tries. {}", getCounter, parameters.toString()); throw new GetFailedException("Couldn't load data."); } else { logger.warn("Couldn't get data. Try #{}. Retrying. reason = '{}' {}", getCounter++, futureGet.failedReason(), parameters.toString()); // TODO reput latest versions for maintenance // exponential back off waiting try { Thread.sleep(getWaitTime); getWaitTime = getWaitTime * 2; } catch (InterruptedException ignore) { } } } else { break; } } // check if version delays or forks occurred if (hasVersionDelay(fetchedVersions, digestCache) && delayCounter < delayLimit) { logger.warn("Detected a version delay. #{}", delayCounter++); // TODO reput latest versions for maintenance, consider only latest // exponential back off waiting try { Thread.sleep(delayWaitTime); delayWaitTime = delayWaitTime * 2; } catch (InterruptedException ignore) { } continue; } // get latest versions according cache Cache<Set<Number160>> latestVersionKeys = getLatest(digestCache); // check for version fork if (latestVersionKeys.size() > 1 && delayCounter < delayLimit) { if (forkAfterGetCounter < forkAfterGetLimit) { logger.warn("Got a version fork. Waiting. #{}", forkAfterGetCounter++); // exponential back off waiting try { Thread.sleep(forkAfterGetWaitTime); forkAfterGetWaitTime = forkAfterGetWaitTime * 2; } catch (InterruptedException ignore) { } continue; } logger.warn("Got a version fork."); // TODO implement merging throw new GetFailedException("Got a version fork."); } else { if (delayCounter >= delayLimit) { logger.warn("Ignoring delay after {} retries.", delayCounter); } if (contentCache.isEmpty()) { logger.warn("Did not find any version."); throw new GetFailedException("No version found. Got null."); } else { try { return (T) contentCache.lastEntry().getValue(); } catch (Exception e) { logger.error("Cannot get the version.", e); throw new GetFailedException(String.format("Cannot get the version. reason = '%s'", e.getMessage())); } } } } } } /** * Encrypts the modified user profile and puts it (blocking). * * @throws PutFailedException */ public void put(T networkContent, KeyPair protectionKeys) throws PutFailedException { networkContent.generateVersionKey(); IParameters parameters = new Parameters().setLocationKey(this.parameters.getLocationKey()) .setContentKey(this.parameters.getContentKey()).setVersionKey(networkContent.getVersionKey()) .setBasedOnKey(networkContent.getBasedOnKey()).setNetworkContent(networkContent) .setProtectionKeys(protectionKeys).setTTL(networkContent.getTimeToLive()).setPrepareFlag(true); H2HPutStatus status = dataManager.put(parameters); if (status.equals(H2HPutStatus.FAILED)) { throw new PutFailedException("Put failed."); } else if (status.equals(H2HPutStatus.VERSION_FORK)) { logger.warn("Version fork after put detected. Rejecting put"); if (!dataManager.remove(parameters)) { logger.warn("Removing of conflicting version failed."); } throw new VersionForkAfterPutException(); } else { // cache digest digestCache.put(parameters.getVersionKey(), new HashSet<Number160>(parameters.getData().basedOnSet())); // cache network content contentCache.put(parameters.getVersionKey(), networkContent); } } private NavigableMap<Number160, Set<Number160>> buildDigest(Map<PeerAddress, DigestResult> rawDigest) { NavigableMap<Number160, Set<Number160>> digestMap = new TreeMap<Number160, Set<Number160>>(); if (rawDigest == null) { return digestMap; } for (PeerAddress peerAddress : rawDigest.keySet()) { NavigableMap<Number640, Collection<Number160>> tmp = rawDigest.get(peerAddress).keyDigest(); if (tmp == null || tmp.isEmpty()) { // ignore this peer } else { for (Number640 key : tmp.keySet()) { for (Number160 bKey : tmp.get(key)) { if (!digestMap.containsKey(key.versionKey())) { digestMap.put(key.versionKey(), new HashSet<Number160>()); } digestMap.get(key.versionKey()).add(bKey); } } } } return digestMap; } @SuppressWarnings("unchecked") private NavigableMap<Number160, T> buildData(Map<PeerAddress, Map<Number640, Data>> rawData) { NavigableMap<Number160, T> dataMap = new TreeMap<Number160, T>(); if (rawData == null) { return dataMap; } for (PeerAddress peerAddress : rawData.keySet()) { Map<Number640, Data> tmp = rawData.get(peerAddress); if (tmp == null || tmp.isEmpty()) { // ignore this peer } else { for (Number640 key : tmp.keySet()) { try { Object object = tmp.get(key).object(); if (object instanceof BaseVersionedNetworkContent) { dataMap.put(key.versionKey(), (T) tmp.get(key).object()); } else { logger.warn("Received unkown object = '{}'", object.getClass().getSimpleName()); } } catch (ClassNotFoundException | IOException e) { logger.warn("Could not get data. reason = '{}'", e.getMessage()); } } } } return dataMap; } private boolean hasVersionDelay(Map<Number160, ?> latestVersions, Cache<Set<Number160>> digestCache) { for (Number160 version : digestCache.keySet()) { for (Number160 basedOnKey : digestCache.get(version)) { if (latestVersions.containsKey(basedOnKey)) { return true; } } } return false; } private Cache<Set<Number160>> getLatest(Cache<Set<Number160>> cache) { // delete all predecessors Cache<Set<Number160>> tmp = new Cache<Set<Number160>>(cache); Cache<Set<Number160>> result = new Cache<Set<Number160>>(); while (!tmp.isEmpty()) { // last entry is a latest version Entry<Number160, Set<Number160>> latest = tmp.lastEntry(); // store in results list result.put(latest.getKey(), latest.getValue()); // delete all predecessors of latest entry deletePredecessors(latest.getKey(), tmp); } return result; } private void deletePredecessors(Number160 key, Cache<Set<Number160>> cache) { Set<Number160> basedOnSet = cache.remove(key); // check if set has been already deleted if (basedOnSet == null) { return; } // check if version is initial version if (basedOnSet.isEmpty()) { return; } // remove all predecessor versions recursively for (Number160 basedOnKey : basedOnSet) { deletePredecessors(basedOnKey, cache); } } private class Cache<V> extends TreeMap<Number160, V> { private static final long serialVersionUID = 7731754953812711346L; public Cache() { super(); } public Cache(Cache<V> cache) { super(cache); } @Override public void putAll(Map<? extends Number160, ? extends V> map) { super.putAll(map); cleanUp(); } public V put(Number160 key, V value) { try { return super.put(key, value); } finally { cleanUp(); } } private void cleanUp() { if (!isEmpty()) { while (firstKey().timestamp() + H2HConstants.MAX_VERSIONS_HISTORY <= lastKey().timestamp()) { pollFirstEntry(); } } } } }
Swap order of static and final
org.hive2hive.core/src/main/java/org/hive2hive/core/network/data/vdht/VersionManager.java
Swap order of static and final
<ide><path>rg.hive2hive.core/src/main/java/org/hive2hive/core/network/data/vdht/VersionManager.java <ide> private final Random random = new Random(); <ide> <ide> // limit constants <del> private final static int getFailedLimit = 2; <del> private final static int forkAfterGetLimit = 2; <del> private final static int delayLimit = 2; <add> private static final int getFailedLimit = 2; <add> private static final int forkAfterGetLimit = 2; <add> private static final int delayLimit = 2; <ide> <ide> // caches <ide> private Cache<Set<Number160>> digestCache = new Cache<Set<Number160>>();
Java
apache-2.0
e620177d07f93c0af07e56afc93509e777accd9c
0
apache/groovy,apache/groovy,paulk-asert/groovy,apache/groovy,apache/incubator-groovy,apache/groovy,apache/incubator-groovy,apache/incubator-groovy,apache/incubator-groovy,paulk-asert/groovy,paulk-asert/groovy,paulk-asert/groovy
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.IteratorClosureAdapter; import org.codehaus.groovy.runtime.RangeInfo; import org.codehaus.groovy.runtime.typehandling.NumberMath; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.AbstractList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareGreaterThan; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareGreaterThanEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareLessThan; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareLessThanEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareNotEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareTo; import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberMinus.minus; import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberMultiply.multiply; import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberPlus.plus; /** * Represents an immutable list of Numbers from a value to a value with a particular step size. * * In general, it isn't recommended using a NumberRange as a key to a map. The range * 0..3 is deemed to be equal to 0.0..3.0 but they have different hashCode values, * so storing a value using one of these ranges couldn't be retrieved using the other. * * @since 2.5.0 */ public class NumberRange extends AbstractList<Comparable> implements Range<Comparable>, Serializable { private static final long serialVersionUID = 5107424833653948484L; /** * The first value in the range. */ private final Comparable from; /** * The last value in the range. */ private final Comparable to; /** * The step size in the range. */ private final Number stepSize; /** * The cached size, or -1 if not yet computed */ private int size = -1; /** * The cached hashCode (once calculated) */ private Integer hashCodeCache = null; /** * <code>true</code> if the range counts backwards from <code>to</code> to <code>from</code>. */ private final boolean reverse; /** * <code>true</code> if the range includes the lower bound. */ private final boolean inclusiveLeft; /** * <code>true</code> if the range includes the upper bound. */ private final boolean inclusiveRight; /** * Creates an inclusive {@link NumberRange} with step size 1. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from the first value in the range * @param to the last value in the range */ public <T extends Number & Comparable, U extends Number & Comparable> NumberRange(T from, U to) { this(from, to, null, true, true); } /** * Creates a new {@link NumberRange} with step size 1. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param inclusive whether the range is inclusive */ public <T extends Number & Comparable, U extends Number & Comparable> NumberRange(T from, U to, boolean inclusive) { this(from, to, null, true, inclusive); } /** * Creates an inclusive {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param stepSize the gap between discrete elements in the range */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable<? super Number>> NumberRange(T from, U to, V stepSize) { this(from, to, stepSize, true, true); } /** * Creates a {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param stepSize the gap between discrete elements in the range * @param inclusive whether the range is inclusive (upper bound) */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable> NumberRange(T from, U to, V stepSize, boolean inclusive) { this(from, to, stepSize, true, inclusive); } /** * Creates a {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param inclusiveLeft whether the range is includes the lower bound * @param inclusiveRight whether the range is includes the upper bound */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable> NumberRange(T from, U to, boolean inclusiveLeft, boolean inclusiveRight) { this(from, to, null, inclusiveLeft, inclusiveRight); } /** * Creates a {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param stepSize the gap between discrete elements in the range * @param inclusiveLeft whether the range is includes the lower bound * @param inclusiveRight whether the range is includes the upper bound */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable> NumberRange(T from, U to, V stepSize, boolean inclusiveLeft, boolean inclusiveRight) { if (from == null) { throw new IllegalArgumentException("Must specify a non-null value for the 'from' index in a Range"); } if (to == null) { throw new IllegalArgumentException("Must specify a non-null value for the 'to' index in a Range"); } reverse = areReversed(from, to); Number tempFrom; Number tempTo; if (reverse) { tempFrom = to; tempTo = from; } else { tempFrom = from; tempTo = to; } if (tempFrom instanceof Short) { tempFrom = tempFrom.intValue(); } else if (tempFrom instanceof Float) { tempFrom = tempFrom.doubleValue(); } if (tempTo instanceof Short) { tempTo = tempTo.intValue(); } else if (tempTo instanceof Float) { tempTo = tempTo.doubleValue(); } if (tempFrom instanceof Integer && tempTo instanceof Long) { tempFrom = tempFrom.longValue(); } else if (tempTo instanceof Integer && tempFrom instanceof Long) { tempTo = tempTo.longValue(); } this.from = (Comparable) tempFrom; this.to = (Comparable) tempTo; this.stepSize = stepSize == null ? 1 : stepSize; this.inclusiveLeft = inclusiveLeft; this.inclusiveRight = inclusiveRight; } /** * A method for determining from and to information when using this IntRange to index an aggregate object of the specified size. * Normally only used internally within Groovy but useful if adding range indexing support for your own aggregates. * * @param size the size of the aggregate being indexed * @return the calculated range information (with 1 added to the to value, ready for providing to subList */ public RangeInfo subListBorders(int size) { if (stepSize.intValue() != 1) { throw new IllegalStateException("Step must be 1 when used by subList!"); } return IntRange.subListBorders(((Number) from).intValue(), ((Number) to).intValue(), inclusiveLeft, inclusiveRight, size); } /** * For a NumberRange with step size 1, creates a new NumberRange with the same * <code>from</code> and <code>to</code> as this NumberRange * but with a step size of <code>stepSize</code>. * * @param stepSize the desired step size * @return a new NumberRange */ public <T extends Number & Comparable> NumberRange by(T stepSize) { if (!Integer.valueOf(1).equals(this.stepSize)) { throw new IllegalStateException("by only allowed on ranges with original stepSize = 1 but found " + this.stepSize); } return new NumberRange(comparableNumber(from), comparableNumber(to), stepSize, inclusiveLeft, inclusiveRight); } @SuppressWarnings("unchecked") /* package private */ static <T extends Number & Comparable> T comparableNumber(Comparable c) { return (T) c; } @SuppressWarnings("unchecked") /* package private */ static <T extends Number & Comparable> T comparableNumber(Number n) { return (T) n; } private static boolean areReversed(Number from, Number to) { try { return compareGreaterThan(from, to); } catch (ClassCastException cce) { throw new IllegalArgumentException("Unable to create range due to incompatible types: " + from.getClass().getSimpleName() + ".." + to.getClass().getSimpleName() + " (possible missing brackets around range?)", cce); } } /** * An object is deemed equal to this NumberRange if it represents a List of items and * those items equal the list of discrete items represented by this NumberRange. * * @param that the object to be compared for equality with this NumberRange * @return {@code true} if the specified object is equal to this NumberRange * @see #fastEquals(NumberRange) */ @Override public boolean equals(Object that) { return super.equals(that); } /** * A NumberRange's hashCode is based on hashCode values of the discrete items it represents. * * @return the hashCode value */ @Override public int hashCode() { if (hashCodeCache == null) { hashCodeCache = super.hashCode(); } return hashCodeCache; } /* * NOTE: as per the class javadoc, this class doesn't obey the normal equals/hashCode contract. * The following field and method could assist some scenarios which required a similar sort of contract * (but between equals and the custom canonicalHashCode). Currently commented out since we haven't * found a real need. We will likely remove this commented out code if no usage is identified soon. */ /* * The cached canonical hashCode (once calculated) */ // private Integer canonicalHashCodeCache = null; /* * A NumberRange's canonicalHashCode is based on hashCode values of the discrete items it represents. * When two NumberRange's are equal they will have the same canonicalHashCode value. * Numerical values which Groovy deems equal have the same hashCode during this calculation. * So currently (0..3).equals(0.0..3.0) yet they have different hashCode values. This breaks * the normal equals/hashCode contract which is a weakness in Groovy's '==' operator. However * the contract isn't broken between equals and canonicalHashCode. * * @return the hashCode value */ // public int canonicalHashCode() { // if (canonicalHashCodeCache == null) { // int hashCode = 1; // for (Comparable e : this) { // int value; // if (e == null) { // value = 0; // } else { // BigDecimal next = new BigDecimal(e.toString()); // if (next.compareTo(BigDecimal.ZERO) == 0) { // // workaround on pre-Java8 for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6480539 // value = BigDecimal.ZERO.hashCode(); // } else { // value = next.stripTrailingZeros().hashCode(); // } // } // hashCode = 31 * hashCode + value; // } // canonicalHashCodeCache = hashCode; // } // return canonicalHashCodeCache; // } /** * Compares a {@link NumberRange} to another {@link NumberRange} using only a strict comparison * of the NumberRange properties. This won't return true for some ranges which represent the same * discrete items, use equals instead for that but will be much faster for large lists. * * @param that the NumberRange to check equality with * @return <code>true</code> if the ranges are equal */ public boolean fastEquals(NumberRange that) { return that != null && reverse == that.reverse && inclusiveLeft == that.inclusiveLeft && inclusiveRight == that.inclusiveRight && compareEqual(from, that.from) && compareEqual(to, that.to) && compareEqual(stepSize, that.stepSize); } /* * NOTE: as per the class javadoc, this class doesn't obey the normal equals/hashCode contract. * The following field and method could assist some scenarios which required a similar sort of contract * (but between fastEquals and the custom fastHashCode). Currently commented out since we haven't * found a real need. We will likely remove this commented out code if no usage is identified soon. */ /* * The cached fast hashCode (once calculated) */ // private Integer fastHashCodeCache = null; /* * A hashCode function that pairs with fastEquals, following the normal equals/hashCode contract. * * @return the calculated hash code */ // public int fastHashCode() { // if (fastHashCodeCache == null) { // int result = 17; // result = result * 31 + (reverse ? 1 : 0); // result = result * 31 + (inclusive ? 1 : 0); // result = result * 31 + new BigDecimal(from.toString()).stripTrailingZeros().hashCode(); // result = result * 31 + new BigDecimal(to.toString()).stripTrailingZeros().hashCode(); // result = result * 31 + new BigDecimal(stepSize.toString()).stripTrailingZeros().hashCode(); // fastHashCodeCache = result; // } // return fastHashCodeCache; // } @Override public Comparable getFrom() { return from; } @Override public Comparable getTo() { return to; } public Comparable getStepSize() { return (Comparable) stepSize; } @Override public boolean isReverse() { return reverse; } @Override public Comparable get(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index + " should not be negative"); } final Iterator<Comparable> iter = new StepIterator(this, stepSize); Comparable value = iter.next(); for (int i = 0; i < index; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + index + " is too big for range: " + this); } value = iter.next(); } return value; } /** * Checks whether a value is between the from and to values of a Range * * @param value the value of interest * @return true if the value is within the bounds */ @Override public boolean containsWithinBounds(Object value) { final int result = compareTo(from, value); return result == 0 || result < 0 && compareTo(to, value) >= 0; } /** * protection against calls from Groovy */ @SuppressWarnings("unused") private void setSize(int size) { throw new UnsupportedOperationException("size must not be changed"); } @Override public int size() { if (size == -1) { calcSize(from, to, stepSize); } return size; } void calcSize(Comparable from, Comparable to, Number stepSize) { int tempsize = 0; boolean shortcut = false; if (isIntegral(stepSize)) { if ((from instanceof Integer || from instanceof Long) && (to instanceof Integer || to instanceof Long)) { // let's fast calculate the size final BigInteger fromTemp = new BigInteger(from.toString()); final BigInteger fromNum = inclusiveLeft ? fromTemp : fromTemp.add(BigInteger.ONE); final BigInteger toTemp = new BigInteger(to.toString()); final BigInteger toNum = inclusiveRight ? toTemp : toTemp.subtract(BigInteger.ONE); final BigInteger sizeNum = new BigDecimal(toNum.subtract(fromNum)).divide(BigDecimal.valueOf(stepSize.longValue()), RoundingMode.DOWN).toBigInteger().add(BigInteger.ONE); tempsize = sizeNum.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) < 0 ? sizeNum.intValue() : Integer.MAX_VALUE; shortcut = true; } else if (((from instanceof BigDecimal || from instanceof BigInteger) && to instanceof Number) || ((to instanceof BigDecimal || to instanceof BigInteger) && from instanceof Number)) { // let's fast calculate the size final BigDecimal fromTemp = NumberMath.toBigDecimal((Number) from); final BigDecimal fromNum = inclusiveLeft ? fromTemp : fromTemp.add(BigDecimal.ONE); final BigDecimal toTemp = NumberMath.toBigDecimal((Number) to); final BigDecimal toNum = inclusiveRight ? toTemp : toTemp.subtract(BigDecimal.ONE); final BigInteger sizeNum = toNum.subtract(fromNum).divide(BigDecimal.valueOf(stepSize.longValue()), RoundingMode.DOWN).toBigInteger().add(BigInteger.ONE); tempsize = sizeNum.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) < 0 ? sizeNum.intValue() : Integer.MAX_VALUE; shortcut = true; } } if (!shortcut) { // let's brute-force calculate the size by iterating start to end final Iterator iter = new StepIterator(this, stepSize); while (iter.hasNext()) { tempsize++; // integer overflow if (tempsize < 0) { break; } iter.next(); } // integer overflow if (tempsize < 0) { tempsize = Integer.MAX_VALUE; } } size = tempsize; } private boolean isIntegral(Number stepSize) { BigDecimal tempStepSize = NumberMath.toBigDecimal(stepSize); return tempStepSize.equals(new BigDecimal(tempStepSize.toBigInteger())); } @Override public List<Comparable> subList(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex == toIndex) { return new EmptyRange<Comparable>(from); } // Performance detail: // not using get(fromIndex), get(toIndex) in the following to avoid stepping over elements twice final Iterator<Comparable> iter = new StepIterator(this, stepSize); Comparable value = iter.next(); int i = 0; for (; i < fromIndex; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } value = iter.next(); } final Comparable fromValue = value; for (; i < toIndex - 1; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } value = iter.next(); } final Comparable toValue = value; return new NumberRange(comparableNumber(fromValue), comparableNumber(toValue), comparableNumber(stepSize), true); } @Override public String toString() { return getToString(to.toString(), from.toString()); } @Override public String inspect() { return getToString(InvokerHelper.inspect(to), InvokerHelper.inspect(from)); } private String getToString(String toText, String fromText) { String sepLeft = inclusiveLeft ? ".." : "<.."; String sep = inclusiveRight ? sepLeft : sepLeft + "<"; String base = reverse ? "" + toText + sep + fromText : "" + fromText + sep + toText; return Integer.valueOf(1).equals(stepSize) ? base : base + ".by(" + stepSize + ")"; } /** * iterates over all values and returns true if one value matches. * Also see containsWithinBounds. */ @Override public boolean contains(Object value) { if (value == null) { return false; } final Iterator it = new StepIterator(this, stepSize); while (it.hasNext()) { if (compareEqual(value, it.next())) { return true; } } return false; } /** * {@inheritDoc} */ @Override public void step(int numSteps, Closure closure) { if (numSteps == 0 && compareTo(from, to) == 0) { return; // from == to and step == 0, nothing to do, so return } final StepIterator iter = new StepIterator(this, multiply(numSteps, stepSize)); while (iter.hasNext()) { closure.call(iter.next()); } } /** * {@inheritDoc} */ @Override public Iterator<Comparable> iterator() { return new StepIterator(this, stepSize); } /** * convenience class to serve in other methods. * It's not thread-safe, and lazily produces the next element only on calls of hasNext() or next() */ private class StepIterator implements Iterator<Comparable> { private final NumberRange range; private final Number step; private final boolean isAscending; private boolean isNextFetched = false; private Comparable next = null; StepIterator(NumberRange range, Number step) { if (compareEqual(step, 0) && compareNotEqual(range.getFrom(), range.getTo())) { throw new GroovyRuntimeException("Infinite loop detected due to step size of 0"); } this.range = range; if (compareLessThan(step, 0)) { this.step = multiply(step, -1); isAscending = range.isReverse(); } else { this.step = step; isAscending = !range.isReverse(); } } @Override public boolean hasNext() { fetchNextIfNeeded(); return (next != null) && (isAscending ? (range.inclusiveRight ? compareLessThanEqual(next, range.getTo()) : compareLessThan(next, range.getTo())) : (range.inclusiveRight ? compareGreaterThanEqual(next, range.getFrom()) : compareGreaterThan(next, range.getFrom()))); } @Override public Comparable next() { if (!hasNext()) { throw new NoSuchElementException(); } fetchNextIfNeeded(); isNextFetched = false; return next; } private void fetchNextIfNeeded() { if (!isNextFetched) { isNextFetched = true; if (next == null) { // make the first fetch lazy too next = isAscending ? range.getFrom() : range.getTo(); if (!range.inclusiveLeft) { next = isAscending ? increment(next, step) : decrement(next, step); } } else { next = isAscending ? increment(next, step) : decrement(next, step); } } } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public List<Comparable> step(int numSteps) { final IteratorClosureAdapter<Comparable> adapter = new IteratorClosureAdapter<Comparable>(this); step(numSteps, adapter); return adapter.asList(); } /** * Increments by given step * * @param value the value to increment * @param step the amount to increment * @return the incremented value */ @SuppressWarnings("unchecked") private Comparable increment(Object value, Number step) { return (Comparable) plus((Number) value, step); } /** * Decrements by given step * * @param value the value to decrement * @param step the amount to decrement * @return the decremented value */ @SuppressWarnings("unchecked") private Comparable decrement(Object value, Number step) { return (Comparable) minus((Number) value, step); } }
src/main/java/groovy/lang/NumberRange.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package groovy.lang; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.IteratorClosureAdapter; import org.codehaus.groovy.runtime.RangeInfo; import org.codehaus.groovy.runtime.typehandling.NumberMath; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.AbstractList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareGreaterThan; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareGreaterThanEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareLessThan; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareLessThanEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareNotEqual; import static org.codehaus.groovy.runtime.ScriptBytecodeAdapter.compareTo; import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberMinus.minus; import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberMultiply.multiply; import static org.codehaus.groovy.runtime.dgmimpl.NumberNumberPlus.plus; /** * Represents an immutable list of Numbers from a value to a value with a particular step size. * * In general, it isn't recommended using a NumberRange as a key to a map. The range * 0..3 is deemed to be equal to 0.0..3.0 but they have different hashCode values, * so storing a value using one of these ranges couldn't be retrieved using the other. * * @since 2.5.0 */ public class NumberRange extends AbstractList<Comparable> implements Range<Comparable>, Serializable { private static final long serialVersionUID = 5107424833653948484L; /** * The first value in the range. */ private final Comparable from; /** * The last value in the range. */ private final Comparable to; /** * The step size in the range. */ private final Number stepSize; /** * The cached size, or -1 if not yet computed */ private int size = -1; /** * The cached hashCode (once calculated) */ private Integer hashCodeCache = null; /** * <code>true</code> if the range counts backwards from <code>to</code> to <code>from</code>. */ private final boolean reverse; /** * <code>true</code> if the range includes the lower bound. */ private final boolean inclusiveLeft; /** * <code>true</code> if the range includes the upper bound. */ private final boolean inclusiveRight; /** * Creates an inclusive {@link NumberRange} with step size 1. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from the first value in the range * @param to the last value in the range */ public <T extends Number & Comparable, U extends Number & Comparable> NumberRange(T from, U to) { this(from, to, null, true, true); } /** * Creates a new {@link NumberRange} with step size 1. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param inclusive whether the range is inclusive */ public <T extends Number & Comparable, U extends Number & Comparable> NumberRange(T from, U to, boolean inclusive) { this(from, to, null, true, inclusive); } /** * Creates an inclusive {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param stepSize the gap between discrete elements in the range */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable<? super Number>> NumberRange(T from, U to, V stepSize) { this(from, to, stepSize, true, true); } /** * Creates a {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param stepSize the gap between discrete elements in the range * @param inclusive whether the range is inclusive (upper bound) */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable> NumberRange(T from, U to, V stepSize, boolean inclusive) { this(from, to, stepSize, true, inclusive); } /** * Creates a {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param inclusiveLeft whether the range is includes the lower bound * @param inclusiveRight whether the range is includes the upper bound */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable> NumberRange(T from, U to, boolean inclusiveLeft, boolean inclusiveRight) { this(from, to, null, inclusiveLeft, inclusiveRight); } /** * Creates a {@link NumberRange}. * Creates a reversed range if <code>from</code> &lt; <code>to</code>. * * @param from start of the range * @param to end of the range * @param stepSize the gap between discrete elements in the range * @param inclusiveLeft whether the range is includes the lower bound * @param inclusiveRight whether the range is includes the upper bound */ public <T extends Number & Comparable, U extends Number & Comparable, V extends Number & Comparable> NumberRange(T from, U to, V stepSize, boolean inclusiveLeft, boolean inclusiveRight) { if (from == null) { throw new IllegalArgumentException("Must specify a non-null value for the 'from' index in a Range"); } if (to == null) { throw new IllegalArgumentException("Must specify a non-null value for the 'to' index in a Range"); } reverse = areReversed(from, to); Number tempFrom; Number tempTo; if (reverse) { tempFrom = to; tempTo = from; } else { tempFrom = from; tempTo = to; } if (tempFrom instanceof Short) { tempFrom = tempFrom.intValue(); } else if (tempFrom instanceof Float) { tempFrom = tempFrom.doubleValue(); } if (tempTo instanceof Short) { tempTo = tempTo.intValue(); } else if (tempTo instanceof Float) { tempTo = tempTo.doubleValue(); } if (tempFrom instanceof Integer && tempTo instanceof Long) { tempFrom = tempFrom.longValue(); } else if (tempTo instanceof Integer && tempFrom instanceof Long) { tempTo = tempTo.longValue(); } this.from = (Comparable) tempFrom; this.to = (Comparable) tempTo; this.stepSize = stepSize == null ? 1 : stepSize; this.inclusiveLeft = inclusiveLeft; this.inclusiveRight = inclusiveRight; } /** * A method for determining from and to information when using this IntRange to index an aggregate object of the specified size. * Normally only used internally within Groovy but useful if adding range indexing support for your own aggregates. * * @param size the size of the aggregate being indexed * @return the calculated range information (with 1 added to the to value, ready for providing to subList */ public RangeInfo subListBorders(int size) { if (stepSize.intValue() != 1) { throw new IllegalStateException("Step must be 1 when used by subList!"); } return IntRange.subListBorders(((Number) from).intValue(), ((Number) to).intValue(), inclusiveLeft, inclusiveRight, size); } /** * For a NumberRange with step size 1, creates a new NumberRange with the same * <code>from</code> and <code>to</code> as this NumberRange * but with a step size of <code>stepSize</code>. * * @param stepSize the desired step size * @return a new NumberRange */ public <T extends Number & Comparable> NumberRange by(T stepSize) { if (!Integer.valueOf(1).equals(this.stepSize)) { throw new IllegalStateException("by only allowed on ranges with original stepSize = 1 but found " + this.stepSize); } return new NumberRange(comparableNumber(from), comparableNumber(to), stepSize, inclusiveLeft, inclusiveRight); } @SuppressWarnings("unchecked") /* package private */ static <T extends Number & Comparable> T comparableNumber(Comparable c) { return (T) c; } @SuppressWarnings("unchecked") /* package private */ static <T extends Number & Comparable> T comparableNumber(Number n) { return (T) n; } private static boolean areReversed(Number from, Number to) { try { return compareGreaterThan(from, to); } catch (ClassCastException cce) { throw new IllegalArgumentException("Unable to create range due to incompatible types: " + from.getClass().getSimpleName() + ".." + to.getClass().getSimpleName() + " (possible missing brackets around range?)", cce); } } /** * An object is deemed equal to this NumberRange if it represents a List of items and * those items equal the list of discrete items represented by this NumberRange. * * @param that the object to be compared for equality with this NumberRange * @return {@code true} if the specified object is equal to this NumberRange * @see #fastEquals(NumberRange) */ @Override public boolean equals(Object that) { return super.equals(that); } /** * A NumberRange's hashCode is based on hashCode values of the discrete items it represents. * * @return the hashCode value */ @Override public int hashCode() { if (hashCodeCache == null) { hashCodeCache = super.hashCode(); } return hashCodeCache; } /* * NOTE: as per the class javadoc, this class doesn't obey the normal equals/hashCode contract. * The following field and method could assist some scenarios which required a similar sort of contract * (but between equals and the custom canonicalHashCode). Currently commented out since we haven't * found a real need. We will likely remove this commented out code if no usage is identified soon. */ /* * The cached canonical hashCode (once calculated) */ // private Integer canonicalHashCodeCache = null; /* * A NumberRange's canonicalHashCode is based on hashCode values of the discrete items it represents. * When two NumberRange's are equal they will have the same canonicalHashCode value. * Numerical values which Groovy deems equal have the same hashCode during this calculation. * So currently (0..3).equals(0.0..3.0) yet they have different hashCode values. This breaks * the normal equals/hashCode contract which is a weakness in Groovy's '==' operator. However * the contract isn't broken between equals and canonicalHashCode. * * @return the hashCode value */ // public int canonicalHashCode() { // if (canonicalHashCodeCache == null) { // int hashCode = 1; // for (Comparable e : this) { // int value; // if (e == null) { // value = 0; // } else { // BigDecimal next = new BigDecimal(e.toString()); // if (next.compareTo(BigDecimal.ZERO) == 0) { // // workaround on pre-Java8 for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6480539 // value = BigDecimal.ZERO.hashCode(); // } else { // value = next.stripTrailingZeros().hashCode(); // } // } // hashCode = 31 * hashCode + value; // } // canonicalHashCodeCache = hashCode; // } // return canonicalHashCodeCache; // } /** * Compares a {@link NumberRange} to another {@link NumberRange} using only a strict comparison * of the NumberRange properties. This won't return true for some ranges which represent the same * discrete items, use equals instead for that but will be much faster for large lists. * * @param that the NumberRange to check equality with * @return <code>true</code> if the ranges are equal */ public boolean fastEquals(NumberRange that) { return that != null && reverse == that.reverse && inclusiveLeft == that.inclusiveLeft && inclusiveRight == that.inclusiveRight && compareEqual(from, that.from) && compareEqual(to, that.to) && compareEqual(stepSize, that.stepSize); } /* * NOTE: as per the class javadoc, this class doesn't obey the normal equals/hashCode contract. * The following field and method could assist some scenarios which required a similar sort of contract * (but between fastEquals and the custom fastHashCode). Currently commented out since we haven't * found a real need. We will likely remove this commented out code if no usage is identified soon. */ /* * The cached fast hashCode (once calculated) */ // private Integer fastHashCodeCache = null; /* * A hashCode function that pairs with fastEquals, following the normal equals/hashCode contract. * * @return the calculated hash code */ // public int fastHashCode() { // if (fastHashCodeCache == null) { // int result = 17; // result = result * 31 + (reverse ? 1 : 0); // result = result * 31 + (inclusive ? 1 : 0); // result = result * 31 + new BigDecimal(from.toString()).stripTrailingZeros().hashCode(); // result = result * 31 + new BigDecimal(to.toString()).stripTrailingZeros().hashCode(); // result = result * 31 + new BigDecimal(stepSize.toString()).stripTrailingZeros().hashCode(); // fastHashCodeCache = result; // } // return fastHashCodeCache; // } @Override public Comparable getFrom() { return from; } @Override public Comparable getTo() { return to; } public Comparable getStepSize() { return (Comparable) stepSize; } @Override public boolean isReverse() { return reverse; } @Override public Comparable get(int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index: " + index + " should not be negative"); } final Iterator<Comparable> iter = new StepIterator(this, stepSize); Comparable value = iter.next(); for (int i = 0; i < index; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + index + " is too big for range: " + this); } value = iter.next(); } return value; } /** * Checks whether a value is between the from and to values of a Range * * @param value the value of interest * @return true if the value is within the bounds */ @Override public boolean containsWithinBounds(Object value) { final int result = compareTo(from, value); return result == 0 || result < 0 && compareTo(to, value) >= 0; } /** * protection against calls from Groovy */ @SuppressWarnings("unused") private void setSize(int size) { throw new UnsupportedOperationException("size must not be changed"); } @Override public int size() { if (size == -1) { calcSize(from, to, stepSize); } return size; } void calcSize(Comparable from, Comparable to, Number stepSize) { int tempsize = 0; boolean shortcut = false; if (isIntegral(stepSize)) { if ((from instanceof Integer || from instanceof Long) && (to instanceof Integer || to instanceof Long)) { // let's fast calculate the size final BigInteger fromTemp = new BigInteger(from.toString()); final BigInteger fromNum = inclusiveLeft ? fromTemp : fromTemp.add(BigInteger.ONE); final BigInteger toTemp = new BigInteger(to.toString()); final BigInteger toNum = inclusiveRight ? toTemp : toTemp.subtract(BigInteger.ONE); final BigInteger sizeNum = new BigDecimal(toNum.subtract(fromNum)).divide(BigDecimal.valueOf(stepSize.longValue()), RoundingMode.DOWN).toBigInteger().add(BigInteger.ONE); tempsize = sizeNum.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) < 0 ? sizeNum.intValue() : Integer.MAX_VALUE; shortcut = true; } else if (((from instanceof BigDecimal || from instanceof BigInteger) && to instanceof Number) || ((to instanceof BigDecimal || to instanceof BigInteger) && from instanceof Number)) { // let's fast calculate the size final BigDecimal fromTemp = NumberMath.toBigDecimal((Number) from); final BigDecimal fromNum = inclusiveLeft ? fromTemp : fromTemp.add(BigDecimal.ONE); final BigDecimal toTemp = NumberMath.toBigDecimal((Number) to); final BigDecimal toNum = inclusiveRight ? toTemp : toTemp.subtract(BigDecimal.ONE); final BigInteger sizeNum = toNum.subtract(fromNum).divide(BigDecimal.valueOf(stepSize.longValue()), RoundingMode.DOWN).toBigInteger().add(BigInteger.ONE); tempsize = sizeNum.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) < 0 ? sizeNum.intValue() : Integer.MAX_VALUE; shortcut = true; } } if (!shortcut) { // let's brute-force calculate the size by iterating start to end final Iterator iter = new StepIterator(this, stepSize); while (iter.hasNext()) { tempsize++; // integer overflow if (tempsize < 0) { break; } iter.next(); } // integer overflow if (tempsize < 0) { tempsize = Integer.MAX_VALUE; } } size = tempsize; } private boolean isIntegral(Number stepSize) { BigDecimal tempStepSize = NumberMath.toBigDecimal(stepSize); return tempStepSize.equals(new BigDecimal(tempStepSize.toBigInteger())); } @Override public List<Comparable> subList(int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); } if (fromIndex > toIndex) { throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex == toIndex) { return new EmptyRange<Comparable>(from); } // Performance detail: // not using get(fromIndex), get(toIndex) in the following to avoid stepping over elements twice final Iterator<Comparable> iter = new StepIterator(this, stepSize); Comparable value = iter.next(); int i = 0; for (; i < fromIndex; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } value = iter.next(); } final Comparable fromValue = value; for (; i < toIndex - 1; i++) { if (!iter.hasNext()) { throw new IndexOutOfBoundsException("Index: " + i + " is too big for range: " + this); } value = iter.next(); } final Comparable toValue = value; return new NumberRange(comparableNumber(fromValue), comparableNumber(toValue), comparableNumber(stepSize), true); } @Override public String toString() { return getToString(to.toString(), from.toString()); } @Override public String inspect() { return getToString(InvokerHelper.inspect(to), InvokerHelper.inspect(from)); } private String getToString(String toText, String fromText) { String sepLeft = inclusiveLeft ? ".." : "<.."; String sep = inclusiveRight ? sepLeft : sepLeft + "<"; String base = reverse ? "" + toText + sep + fromText : "" + fromText + sep + toText; return Integer.valueOf(1).equals(stepSize) ? base : base + ".by(" + stepSize + ")"; } /** * iterates over all values and returns true if one value matches. * Also see containsWithinBounds. */ @Override public boolean contains(Object value) { if (value == null) { return false; } final Iterator it = new StepIterator(this, stepSize); while (it.hasNext()) { if (compareEqual(value, it.next())) { return true; } } return false; } /** * {@inheritDoc} */ @Override public void step(int numSteps, Closure closure) { if (numSteps == 0 && compareTo(from, to) == 0) { return; // from == to and step == 0, nothing to do, so return } final StepIterator iter = new StepIterator(this, multiply(numSteps, stepSize)); while (iter.hasNext()) { closure.call(iter.next()); } } /** * {@inheritDoc} */ @Override public Iterator<Comparable> iterator() { return new StepIterator(this, stepSize); } /** * convenience class to serve in other methods. * It's not thread-safe, and lazily produces the next element only on calls of hasNext() or next() */ private class StepIterator implements Iterator<Comparable> { private final NumberRange range; private final Number step; private final boolean isAscending; private boolean isNextFetched = false; private Comparable next = null; StepIterator(NumberRange range, Number step) { if (compareEqual(step, 0) && compareNotEqual(range.getFrom(), range.getTo())) { throw new GroovyRuntimeException("Infinite loop detected due to step size of 0"); } this.range = range; if (compareLessThan(step, 0)) { this.step = multiply(step, -1); isAscending = range.isReverse(); } else { this.step = step; isAscending = !range.isReverse(); } } @Override public boolean hasNext() { fetchNextIfNeeded(); return (next != null) && (isAscending ? (range.inclusiveRight ? compareLessThanEqual(next, range.getTo()) : compareLessThan(next, range.getTo())) : (range.inclusiveRight ? compareGreaterThanEqual(next, range.getFrom()) : compareGreaterThan(next, range.getFrom()))); } @Override public Comparable next() { if (!hasNext()) { throw new NoSuchElementException(); } fetchNextIfNeeded(); isNextFetched = false; return next; } private void fetchNextIfNeeded() { if (!isNextFetched) { isNextFetched = true; if (next == null) { // make the first fetch lazy too next = isAscending ? range.getFrom() : range.getTo(); if (!range.inclusiveLeft) { next = next(); } } else { next = isAscending ? increment(next, step) : decrement(next, step); } } } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public List<Comparable> step(int numSteps) { final IteratorClosureAdapter<Comparable> adapter = new IteratorClosureAdapter<Comparable>(this); step(numSteps, adapter); return adapter.asList(); } /** * Increments by given step * * @param value the value to increment * @param step the amount to increment * @return the incremented value */ @SuppressWarnings("unchecked") private Comparable increment(Object value, Number step) { return (Comparable) plus((Number) value, step); } /** * Decrements by given step * * @param value the value to decrement * @param step the amount to decrement * @return the decremented value */ @SuppressWarnings("unchecked") private Comparable decrement(Object value, Number step) { return (Comparable) minus((Number) value, step); } }
GROOVY-9649: Fixed NumberRange.get not throwing at certain conditions With ranges like 0G<..<1G, the get method would erroneously return 1G instead of throwing an exception. This commit fixes that by directly incrementing the current value in the iterator instead of next() call.
src/main/java/groovy/lang/NumberRange.java
GROOVY-9649: Fixed NumberRange.get not throwing at certain conditions
<ide><path>rc/main/java/groovy/lang/NumberRange.java <ide> // make the first fetch lazy too <ide> next = isAscending ? range.getFrom() : range.getTo(); <ide> if (!range.inclusiveLeft) { <del> next = next(); <add> next = isAscending ? increment(next, step) : decrement(next, step); <ide> } <ide> } else { <ide> next = isAscending ? increment(next, step) : decrement(next, step);
JavaScript
lgpl-2.1
842de7302f33f28b55fcb592028c3f3cfff56a90
0
christinedt/p5.js,sakshamsaxena/p5.js,wufengyi/p5.js,charneykaye/p5.js,indefinit/p5.js,limzykenneth/p5.js,shiffman/p5.js,johnpasquarello/p5.js,spasmsaps/p5.js,Real-Currents/p5.js,therewasaguy/p5.js,Mohammed90/p5.js,dieface/p5.js,plural/p5.js,workergnome/p5.js,workergnome/p5.js,RomainRouphael/p5.js,kennethdmiller3/p5.js,poemusica/p5.js,bartuspan/p5.js,davidnunez/p5.js,limzykenneth/p5.js,bomoko/p5.js,laurenbenichou/p5.js,therewasaguy/p5.js,mayaman/p5.js,milrob/p5.js,bartuspan/p5.js,g-rocket/p5.js,indefinit/p5.js,Mohammed90/p5.js,FreeSchoolHackers/p5.js,GoToLoop/p5.js,yupa884/p5.js,poemusica/p5.js,xyfeng/p5.js,kennethdmiller3/p5.js,maxkolyanov/p5.js,mayaman/p5.js,nucliweb/p5.js,charneykaye/p5.js,kyoungchinseo/p5.js,mwcz/p5.js,antiboredom/p5.js,mlarghydracept/p5.js,picxenk/p5.js,rsbballguy/p5.js,christinedt/p5.js,Jared-Sprague/p5.js,sarahgp/p5.js,Jared-Sprague/p5.js,dhowe/p5.js,jefarrell/p5.js,spasmsaps/p5.js,mwcz/p5.js,processing/p5.js,sarahgp/p5.js,bomoko/p5.js,luisaph/p5.js,eozinche/p5.js,futuremarc/p5.js,FreeSchoolHackers/p5.js,beni55/p5.js,johnpasquarello/p5.js,crhallberg/p5.js,eozinche/p5.js,antiboredom/p5.js,luisaph/p5.js,kadamwhite/p5.js,111t8e/p5.js,rsbballguy/p5.js,spasmsaps/p5.js,OhJia/p5.js,rolka/p5.js,sakshamsaxena/p5.js,maxkolyanov/p5.js,sarahgp/p5.js,black-kite/p5.js,beni55/p5.js,yupa884/p5.js,christinedt/p5.js,laurenbenichou/p5.js,GoToLoop/p5.js,zenozeng/p5.js,Real-Currents/p5.js,wufengyi/p5.js,picxenk/p5.js,mlarghydracept/p5.js,PeterDaveHello/p5.js,111t8e/p5.js,xyfeng/p5.js,karenpeng/p5.js,shiffman/p5.js,OhJia/p5.js,milrob/p5.js,mayaman/p5.js,jefarrell/p5.js,processing/p5.js,nucliweb/p5.js,davidnunez/p5.js,crhallberg/p5.js,g-rocket/p5.js,plural/p5.js,PeterDaveHello/p5.js,joecridge/p5.js,joecridge/p5.js,jshaw/p5.js,rolka/p5.js,dhowe/p5.js,black-kite/p5.js,karenpeng/p5.js,dieface/p5.js,kadamwhite/p5.js,RomainRouphael/p5.js,futuremarc/p5.js,jshaw/p5.js,kyoungchinseo/p5.js,luisaph/p5.js,zenozeng/p5.js
(function(exports) { ////////////////////////////////////// //// //// CURRENT PROCESSING API //// ////////////////////////////////////// ////////////////////////////////////// //// STRUCTURE ////////////////////////////////////// exports.draw; // needed? exports.setup; // needed? function noLoop() { if (pLoop) { pLoop = false; } } function loop() { if (!pLoop) { pLoop = true; } } function redraw() { pDraw(); } ////////////////////////////////////// //// ENVIRONMENT ////////////////////////////////////// exports.frameCount = 0; exports.frameRate = 30; exports.height = 100; exports.width = 100; // exports.focused exports.cursor = function(type) { var cursor = 'auto'; if (type == CROSS || type == HAND || type == MOVE || type == TEXT || type == WAIT) { cursor = type; } document.getElementsByTagName('body')[0].style.cursor = cursor; } exports.displayHeight = screen.height; exports.displayWidth = screen.width; exports.getFrameRate = function() { return frameRate; } exports.setFrameRate = function(fps) { frameRate = fps; clearInterval(pUpdateInterval); pUpdateInterval = setInterval(pUpdate, 1000/frameRate); } exports.noCursor = function() { document.getElementsByTagName('body')[0].style.cursor = 'none'; } ////////////////////////////////////// //// DATA ////////////////////////////////////// //// STRING FUNCTIONS //////////////// exports.join = function(list, separator) { return list.join(separator); } exports.match = function(str, reg) { return str.match(reg); } exports.matchAll = function(str, reg) { // TODO } exports.nf = function(num, a, b) { var neg = (num < 0); var n = neg ? num.toString().substring(1) : num; var str = neg ? '-' : ''; if (typeof b !== 'undefined') { for (var i=0; i<a; i++) { str += '0'; } str += n; str += '.'; for (var i=0; i<b; i++) { str += '0'; } return str; } else { for (var i=0; i<max(a-n.toString().length, 0); i++) { str += '0'; } return str+n; } } exports.nfc = function(num, right) { var dec = num.indexOf('.'); var rem = dec != -1 ? num.substring(dec) : ''; var n = dec != -1 ? num.substring(0, dec) : num; n = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); if (typeof right !== 'undefined') rem = rem.substring(0, right+1); return n+rem; } exports.nfp = function(num, a, b) { return num >= 0 ? '+'+nf(num, a, b) : nf(num, a, b); } exports.nfs = function(num, a, b) { return num >= 0 ? ' '+nf(num, a, b) : nf(num, a, b); } exports.split = function(str, delim) { return str.split(delim); } exports.splitTokens = function(str, delim) { var d = delim ? delim : /\s/g; return str.split(d).filter(function(n){return n}); } exports.trim = function(str) { if (str instanceof Array) { var strps = []; for (var i=0; i<str.length; i++) { stps.push(str[i].trim()); } return strps; } else return str.trim(); } //// ARRAY FUNCTIONS ///////////////// exports.append = function(array, value) { array.push(value); return array; } exports.arrayCopy = function(src, a, b, c, d) { //src, srcPosition, dst, dstPosition, length if (typeof d !== 'undefined') { for (var i=a; i<min(a+d, srpCurCanvas.length); i++) { b[dstPosition+i] = src[i]; } } else if (typeof b !== 'undefined') { //src, dst, length a = srpCurCanvas.slice(0, min(b, srpCurCanvas.length)); } else { //src, dst a = srpCurCanvas.slice(0); } } exports.concat = function(list0, list1) { return list0.concat(list1); } exports.reverse = function(list) { return list.reverse(); } exports.shorten = function(list) { list.pop(); return list; } exports.sort = function(list, count) { var arr = count ? list.slice(0, min(count, list.length)) : list; var rest = count ? list.slice(min(count, list.length)) : []; if (typeof arr[0] === 'string') { arr = arr.sort(); } else { arr = arr.sort(function(a,b){return a-b}); } return arr.concat(rest); } exports.splice = function(list, value, index) { return list.splice(index,0,value); } exports.subset = function(list, start, count) { if (typeof count !== 'undefined') return list.slice(start, start+count); else return list.slice(start, list.length-1); } ////////////////////////////////////// //// SHAPE ////////////////////////////////////// //// 2D PRIMITIVES /////////////////// exports.arc = function(a, b, c, d, start, stop, mode) { } exports.ellipse = function(a, b, c, d) { var vals = pModeAdjust(a, b, c, d, pEllipseMode); var kappa = .5522848, ox = (vals.w / 2) * kappa, // control point offset horizontal oy = (vals.h / 2) * kappa, // control point offset vertical xe = vals.x + vals.w, // x-end ye = vals.y + vals.h, // y-end xm = vals.x + vals.w / 2, // x-middle ym = vals.y + vals.h / 2; // y-middle pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(vals.x, ym); pCurCanvas.context.bezierCurveTo(vals.x, ym - oy, xm - ox, vals.y, xm, vals.y); pCurCanvas.context.bezierCurveTo(xm + ox, vals.y, xe, ym - oy, xe, ym); pCurCanvas.context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); pCurCanvas.context.bezierCurveTo(xm - ox, ye, vals.x, ym + oy, vals.x, ym); pCurCanvas.context.closePath(); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } exports.line = function(x1, y1, x2, y2) { if (pCurCanvas.context.strokeStyle === 'none') { return; } pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.lineTo(x2, y2); pCurCanvas.context.stroke(); } exports.point = function(x, y) { var s = pCurCanvas.context.strokeStyle; var f = pCurCanvas.context.fillStyle; if (s === 'none') { return; } x = Math.round(x); y = Math.round(y); pCurCanvas.context.fillStyle = s; if (pCurCanvas.context.lineWidth > 1) { pCurCanvas.context.beginPath(); pCurCanvas.context.arc(x, y, pCurCanvas.context.lineWidth / 2, 0, TWO_PI, false); pCurCanvas.context.fill(); } else { pCurCanvas.context.fillRect(x, y, 1, 1); } pCurCanvas.context.fillStyle = f; } exports.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.lineTo(x2, y2); pCurCanvas.context.lineTo(x3, y3); pCurCanvas.context.lineTo(x4, y4); pCurCanvas.context.closePath(); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } exports.rect = function(a, b, c, d) { var vals = pModeAdjust(a, b, c, d, pRectMode); pCurCanvas.context.beginPath(); pCurCanvas.context.rect(vals.x, vals.y, vals.w, vals.h); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } exports.triangle = function(x1, y1, x2, y2, x3, y3) { pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.lineTo(x2, y2); pCurCanvas.context.lineTo(x3, y3); pCurCanvas.context.closePath(); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } //// CURVES ////////////////////////// exports.bezier = function(x1, y1, x2, y2, x3, y3, x4, y4) { pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.bezierCurveTo(x2, y2, x3, y3, x4, y4); pCurCanvas.context.stroke(); } exports.bezierDetail = function() { // TODO } exports.bezierPoint = function() { // TODO } exports.bezierTangent = function() { // TODO } exports.curve = function() { // TODO } exports.curveDetail = function() { // TODO } exports.curvePoint = function() { // TODO } exports.curveTangent = function() { // TODO } exports.curveTightness = function() { // TODO } //// ATTRIBUTES ////////////////////// exports.ellipseMode = function(m) { if (m == CORNER || m == CORNERS || m == RADIUS || m == CENTER) { pEllipseMode = m; } } exports.noSmooth = function() { pCurCanvas.context.mozImageSmoothingEnabled = false; pCurCanvas.context.webkitImageSmoothingEnabled = false; } exports.rectMode = function(m) { if (m == CORNER || m == CORNERS || m == RADIUS || m == CENTER) { pRectMode = m; } } exports.smooth = function() { pCurCanvas.context.mozImageSmoothingEnabled = true; pCurCanvas.context.webkitImageSmoothingEnabled = true; } exports.strokeCap = function(cap) { if (cap == ROUND || cap == SQUARE || cap == PROJECT) { pCurCanvas.context.lineCap=cap; } } exports.strokeJoin = function(join) { if (join == ROUND || join == BEVEL || join == MITER) { pCurCanvas.context.lineJoin = join; } } exports.strokeWeight = function(w) { pCurCanvas.context.lineWidth = w; if (typeof w === 'undefined') noStroke(); } //// VERTEX ////////////////////////// exports.beginContour = function() { // TODO } exports.beginShape = function(kind) { if (kind == POINTS || kind == LINES || kind == TRIANGLES || kind == TRIANGLE_FAN || kind == TRIANGLE_STRIP || kind == QUADS || kind == QUAD_STRIP) pShapeKind = kind; else pShapeKind = null; pShapeInited = true; pCurCanvas.context.beginPath(); } exports.bezierVertex = function(x1, y1, x2, y2, x3, y3) { pCurCanvas.context.bezierCurveTo(x1, y1, x2, y2, x3, y3); } exports.curveVertex = function() { // TODO } exports.endContour = function() { // TODO } exports.endShape = function(mode) { if (mode == CLOSE) { pCurCanvas.context.closePath(); pCurCanvas.context.fill(); } pCurCanvas.context.stroke(); } exports.quadraticVertex = function(cx, cy, x3, y3) { pCurCanvas.context.quadraticCurveTo(cx, cy, x3, y3); } exports.vertex = function(x, y) { if (pShapeInited) { pCurCanvas.context.moveTo(x, y); } else { pCurCanvas.context.lineTo(x, y); // pend this is where check for kind and do other stuff } pShapeInited = false; } ////////////////////////////////////// //// INPUT ////////////////////////////////////// //// MOUSE /////////////////////////// exports.mouseX = 0; exports.mouseY = 0; var pMousePressed = false; var pmouseX = 0; var pmouseY = 0; exports.isMousePressed = function() { return pMousePressed; } exports.pUpdateMouseCoords = function(e) { pmouseX = exports.mouseX; pmouseY = exports.mouseY; exports.mouseX = e.clientX;// - parseInt(pCurCanvas.elt.style.left, 10); exports.mouseY = e.clientY;// - parseInt(pCurCanvas.elt.style.top, 10); // console.log(mouseX+' '+mouseY); // console.log('mx = '+mouseX+' my = '+mouseY); } //// KEYBOARD //////////////////////// exports.key = ''; exports.keyCode = 0; var pKeyPressed = false; exports.isKeyPressed = function() { return pKeyPressed; } function pSetupInput() { document.body.onmousemove=function(e){ pUpdateMouseCoords(e); if (typeof mouseMoved === 'function') mouseMoved(e); } document.body.onmousedown=function(e){ pMousePressed = true; if (typeof mousePressed === 'function') mousePressed(e); } document.body.onmouseup=function(e){ pMousePressed = false; if (typeof mouseReleased === 'function') mouseReleased(e); } document.body.onmouseclick=function(e){ if (typeof mouseClicked === 'function') mouseClicked(e); } document.body.onkeydown=function(e){ pKeyPressed = true; if (typeof keyPressed === 'function') keyPressed(e); } document.body.onkeyup=function(e){ pKeyPressed = false; if (typeof keyReleased === 'function') keyReleased(e); } document.body.onkeypress=function(e){ keyCode = e.keyCode; if (typeof keyTyped === 'function') keyTyped(e); } } //// FILES /////////////////////////// //BufferedReader exports.createInput = function() { // TODO } exports.createReader = function() { // TODO } exports.loadBytes = function() { // TODO } exports.loadJSON = function(file, callback) { var req = new XMLHttpRequest(); req.overrideMimeType('application/json'); req.open('GET', 'data/'+file); req.onreadystatechange = function () { if(req.readyState === 4) { if(req.status === 200 || req.status == 0) { if (typeof callback !== 'undefined') callback(); return JSON.parse(req.responseText); } } } req.send(null); } exports.loadStrings = function(file, callback) { var req = new XMLHttpRequest(); req.open('GET', 'data/'+file, true); req.onreadystatechange = function () { if(req.readyState === 4) { if(req.status === 200 || req.status == 0) { if (typeof callback !== 'undefined') callback(); return req.responseText.match(/[^\r\n]+/g); } } } req.send(null); } exports.loadTable = function () { // TODO } /*exports.loadXML = function() { var req = new XMLHttpRequest(); req.overrideMimeType('application/json'); req.overrideMimeType('text/xml'); req.open('GET', 'data/'+file, false); req.onreadystatechange = function () { if(req.readyState === 4) { if(req.status === 200 || req.status == 0) { console.log(JSON.parse(req.responseXML)); return JSON.parse(req.responseXML); } } } req.send(null); }*/ exports.open = function() { // TODO } exports.parseXML = function() { // TODO } exports.saveTable = function() { // TODO } exports.selectFolder = function() { // TODO } exports.selectInput = function() { // TODO } //// TIME & DATE ///////////////////// exports.day = function() { return new Date().getDate(); } exports.hour = function() { return new Date().getHours(); } exports.millis = function() { return new Date().getTime() - pStartTime; } exports.month = function() { return new Date().getMonth(); } exports.second = function() { return new Date().getSeconds(); } exports.year = function() { return new Date().getFullYear(); } ////////////////////////////////////// //// OUTPUT ////////////////////////////////////// //// TEXT AREA /////////////////////// exports.print = function(s) { console.log(s); } exports.println = function(s) { console.log(s); } //// IMAGE /////////////////////////// exports.save = function() { exports.open(pCurCanvas.toDataURL()); } //// FILES /////////////////////////// exports.pWriters = []; exports.beginRaw = function() { // TODO } exports.beginRecord = function() { // TODO } exports.createOutput = function() { // TODO } exports.createWriter = function(name) { if (pWriters.indexOf(name) == -1) { // check it doesn't already exist pWriters['name'] = new PrintWriter(name); } } exports.endRaw = function() { // TODO } exports.endRecord = function() { // TODO } exports.PrintWriter = function(name) { this.name = name; this.content = ''; this.print = function(data) { this.content += data; }; this.println = function(data) { this.content += data + '\n'; }; this.flush = function() { this.content = ''; }; this.close = function() { writeFile(this.content); }; } exports.saveBytes = function() { // TODO } exports.saveJSONArray = function() { // TODO } exports.saveJSONObject = function() { // TODO } exports.saveStream = function() { // TODO } exports.saveStrings = function(list) { writeFile(list.join('\n')); } exports.saveXML = function() { // TODO } exports.selectOutput = function() { // TODO } exports.writeFile = function(content) { exports.open('data:text/json;charset=utf-8,' + escape(content), 'download'); } ////////////////////////////////////// //// TRANSFORM ////////////////////////////////////// exports.applyMatrix = function(n00, n01, n02, n10, n11, n12) { pCurCanvas.context.transform(n00, n01, n02, n10, n11, n12); var m = pMatrices[pMatrices.length-1]; m = pMultiplyMatrix(m, [n00, n01, n02, n10, n11, n12]); } exports.popMatrix = function() { pCurCanvas.context.restore(); pMatrices.pop(); } exports.printMatrix = function() { console.log(pMatrices[pMatrices.length-1]); } exports.pushMatrix = function() { pCurCanvas.context.save(); pMatrices.push([1,0,0,1,0,0]); } exports.resetMatrix = function() { pCurCanvas.context.setTransform(); pMatrices[pMatrices.length-1] = [1,0,0,1,0,0]; } exports.rotate = function(r) { pCurCanvas.context.rotate(r); var m = pMatrices[pMatrices.length-1]; var c = Math.cos(r); var s = Math.sin(r); var m11 = m[0] * c + m[2] * s; var m12 = m[1] * c + m[3] * s; var m21 = m[0] * -s + m[2] * c; var m22 = m[1] * -s + m[3] * c; m[0] = m11; m[1] = m12; m[2] = m21; m[3] = m22; } exports.scale = function(x, y) { pCurCanvas.context.scale(x, y); var m = pMatrices[pMatrices.length-1]; m[0] *= x; m[1] *= x; m[2] *= y; m[3] *= y; } exports.shearX = function(angle) { pCurCanvas.context.transform(1, 0, tan(angle), 1, 0, 0); var m = pMatrices[pMatrices.length-1]; m = pMultiplyMatrix(m, [1, 0, tan(angle), 1, 0, 0]); } exports.shearY = function(angle) { pCurCanvas.context.transform(1, tan(angle), 0, 1, 0, 0); var m = pMatrices[pMatrices.length-1]; m = pMultiplyMatrix(m, [1, tan(angle), 0, 1, 0, 0]); } exports.translate = function(x, y) { pCurCanvas.context.translate(x, y); var m = pMatrices[pMatrices.length-1]; m[4] += m[0] * x + m[2] * y; m[5] += m[1] * x + m[3] * y; } ////////////////////////////////////// //// COLOR ////////////////////////////////////// //// SETTING ///////////////////////// exports.background = function(v1, v2, v3) { var c = processColorArgs(v1, v2, v3); // save out the fill var curFill = pCurCanvas.context.fillStyle; // create background rect pCurCanvas.context.fillStyle = rgbToHex(c[0], c[1], c[2]); pCurCanvas.context.fillRect(0, 0, width, height); // reset fill pCurCanvas.context.fillStyle = curFill; } exports.clear = function() { // TODO } exports.colorMode = function(mode) { if (mode == RGB || mode == HSB) pColorMode = mode; } exports.fill = function(v1, v2, v3, a) { var c = processColorArgs(v1, v2, v3, a); if (typeof c[3] !== 'undefined') { pCurCanvas.context.fillStyle = 'rgba('+c[0]+','+c[1]+','+c[2]+','+(parseInt(c[3], 10)/255.0)+')'; } else { pCurCanvas.context.fillStyle = 'rgb('+c[0]+','+c[1]+','+c[2]+')'; } } exports.noFill = function() { pCurCanvas.context.fillStyle = 'none'; } exports.noStroke = function() { pCurCanvas.context.strokeStyle = 'none'; } exports.stroke = function(v1, v2, v3, a) { var c = processColorArgs(v1, v2, v3, a); if (typeof c[3] !== 'undefined') { pCurCanvas.context.strokeStyle = 'rgba('+c[0]+','+c[1]+','+c[2]+','+(parseInt(c[3], 10)/255.0)+')'; } else { pCurCanvas.context.strokeStyle = 'rgb('+c[0]+','+c[1]+','+c[2]+')'; } } function processColorArgs(v1, v2, v3, a) { var c = []; if (typeof v2 === 'undefined' || typeof v3 === 'undefined') { if (typeof v1 === 'object') { if (v1.length == 2) { c = [v1[0], v1[0], v1[0], v1[1]]; } else { c = [v1[0], v1[1], v1[2], v1[3]]; } } else { c = [v1, v1, v1, v2]; } } else { if (typeof a !== 'undefined') { c = [v1, v2, v3, a]; } else { c = [v1, v2, v3]; } } if (pColorMode == HSB) { c = hsv2rgb(c[0], c[1], c[2]); } return c; } //// CREATING & READING ////////////// exports.alpha = function(rgb) { if (rgb.length > 3) return rgb[3]; else return 255; } exports.blue = function(rgb) { if (rgb.length > 2) return rgb[2]; else return 0; } exports.brightness = function(hsv) { if (rgb.length > 2) return rgb[2]; else return 0; } exports.color = function(gray) { return [gray, gray, gray]; } exports.color = function(gray, alpha) { return [gray, gray, gray, alpha]; } exports.color = function(v1, v2, v3) { return [v1, v2, v3]; } exports.color = function(v1, v2, v3, alpha) { return [v1, v2, v3, alpha]; } exports.green = function(rgb) { if (rgb.length > 2) return rgb[1]; else return 0; } exports.hue = function(hsv) { if (rgb.length > 2) return rgb[0]; else return 0; } exports.lerpColor = function(c1, c2, amt) { var c = []; for (var i=0; i<c1.length; i++) { c.push(lerp(c1[i], c2[i], amt)); } return c; } exports.red = function(rgb) { if (rgb.length > 2) return rgb[0]; else return 0; } exports.saturation = function(hsv) { if (rgb.length > 2) return rgb[1]; else return 0; } ////////////////////////////////////// //// IMAGE ////////////////////////////////////// //// PIMAGE ////////////////////////// exports.createImage = function(w, h, format) { return new PImage(w, h); } //pend format? function PImage(w, h) { this.image = pCurCanvas.context.createImageData(w,h); this.pixels = []; this.updatePixelArray(); } PImage.prototype.loadPixels = function() { this.image = context.createImageData(imageData); this.updatePixelArray(); }; PImage.prototype.updatePixelArray = function() { for (var i=0; i<this.data.length; i+=4) { this.pixels.push([this.data[i], this.data[i+1], this.data[i+2], this.data[i+3]]); } } PImage.prototype.updatePixels = function() { for (var i=0; i<this.pixels; i+=4) { for (var j=0; j<4; j++) { this.data[4*i+j] = this.pixels[i][j]; } } }; PImage.prototype.resize = function() { // TODO }; PImage.prototype.get = function(x, y, w, h) { var wp = w ? w : 1; var hp = h ? h : 1; var vals = []; for (var j=y; j<y+hp; j++) { for (var i=x; i<x+wp; i++) { vals.push(this.pixels[j*this.width+i]); } } } PImage.prototype.set = function() { // TODO // writes a color to any pixel or writes an image into another }; PImage.prototype.mask = function() { // TODO // Masks part of an image with another image as an alpha channel }; PImage.prototype.filter = function() { // TODO // Converts the image to grayscale or black and white }; PImage.prototype.copy = function() { // TODO // Copies the entire image }; PImage.prototype.blend = function() { // TODO // Copies a pixel or rectangle of pixels using different blending modes }; PImage.prototype.save = function() { // TODO // Saves the image to a TIFF, TARGA, PNG, or JPEG file*/ }; exports.PImage = PImage; //// LOADING & DISPLAYING ////////////////// exports.image = function(img, a, b, c, d) { if (typeof c !== 'undefined' && typeof d !== 'undefined') { var vals = pModeAdjust(a, b, c, d, pImageMode); pCurCanvas.context.drawImage(img, vals.x, vals.y, vals.w, vals.h); } else { pCurCanvas.context.drawImage(img, a, b); } } exports.imageMode = function(m) { if (m == CORNER || m == CORNERS || m == CENTER) pImageMode = m; } exports.loadImage = function(path, callback) { var imgObj = new Image(); imgObj.onload = function() { if (typeof callback !== 'undefined') callback(); } imgObj.src = path; return imgObj; } //// PIXELS //////////////////////////////// exports.pixels = []; exports.blend = function() { // TODO } exports.copy = function() { // TODO } exports.filter = function() { // TODO } exports.get = function(x, y, w, h) { var pix = pCurCanvas.context.getImageData(0, 0, width, height).data.slice(0); if (typeof w !== 'undefined' && typeof h !== 'undefined') { var region = []; for (var j=0; j<h; j++) { for (var i=0; i<w; i++) { region[i*w+j] = pix[(y+j)*width+(x+i)]; } } return region; } else if (typeof x !== 'undefined' && typeof y !== 'undefined') { if (x >= 0 && x < width && y >= 0 && y < height) { return pix[y*width+x].data; } else { return [0, 0, 0, 255]; } } else { return pix; } } exports.loadPixels = function() { pixels = pCurCanvas.context.getImageData(0, 0, width, height).data.slice(0); // pend should this be 0,0 or pCurCanvas.offsetLeft,pCurCanvas.offsetTop? } exports.set = function() { // TODO } exports.updatePixels = function() { if (typeof pixels !== 'undefined') { var imgd = pCurCanvas.context.getImageData(x, y, width, height); imgd = pixels; context.putImageData(imgd, 0, 0); } } ////////////////////////////////////// //// TYPOGRAPHY ////////////////////////////////////// //// LOADING & DISPLAYING //////////// exports.text = function(s, x, y) { pCurCanvas.context.font=pTextSize+'px Verdana'; pCurCanvas.context.fillText(s, x, y); } //// ATTRIBUTES ////////////////////// exports.textAlign = function(a) { if (a == LEFT || a == RIGHT || a == CENTER) pCurCanvas.context.textAlign = a; } exports.textSize = function(s) { pTextSize = s; } exports.textWidth = function(s) { return pCurCanvas.context.measureText(s).width; } exports.textHeight = function(s) { return pCurCanvas.context.measureText(s).height; } ////////////////////////////////////// //// MATH ////////////////////////////////////// //// CALCULATION ///////////////////// /** @module Math */ /** returns abs value */ exports.abs = function(n) { return Math.abs(n); } exports.ceil = function(n) { return Math.ceil(n); } exports.constrain = function(n, l, h) { return max(min(n, h), l); } exports.dist = function(x1, y1, x2, y2) { var xs = x2-x1; var ys = y2-y1; return Math.sqrt( xs*xs + ys*ys ); } exports.exp = function(n) { return Math.exp(n); } exports.floor = function(n) { return Math.floor(n); } exports.lerp = function(start, stop, amt) { return amt*(stop-start)+start; } exports.log = function(n) { return Math.log(n); } exports.mag = function(x, y) { return Math.sqrt(x*x+y*y); } exports.map = function(n, start1, stop1, start2, stop2) { return ((n-start1)/(stop1-start1))*(stop2-start2)+start2; } exports.max = function(a, b) { return Math.max(a, b); } exports.min = function(a, b) { return Math.min(a, b); } exports.norm = function(n, start, stop) { return map(n, start, stop, 0, 1); } exports.pow = function(n, e) { return Math.pow(n, e); } exports.sq = function(n) { return n*n; } exports.sqrt = function(n) { return Math.sqrt(n); } //// TRIGONOMETRY //////////////////// exports.acos = function(x) { return Math.acos(x); } exports.asin = function(x) { return Math.asin(x); } exports.atan = function(x) { return Math.atan(x); } exports.atan2 = function(y, x) { return Math.atan2(y, x); } exports.cos = function(x) { return Math.cos(x); } exports.degrees = function(x) { return 360.0*x/(2*Math.PI); } exports.radians = function(x) { return 2*Math.PI*x/360.0; } exports.sin = function(x) { return Math.sin(x); } exports.tan = function(x) { return Math.tan(x); } //// RANDOM ////////////////////////// exports.random = function(x, y) { // might want to use this kind of check instead: // if (arguments.length === 0) { if (typeof x !== 'undefined' && typeof y !== 'undefined') { return (y-x)*Math.random()+x; } else if (typeof x !== 'undefined') { return x*Math.random(); } else { return Math.random(); } } ////////////////////////////////////// //// //// CONSTANTS //// ////////////////////////////////////// exports.HALF_PI = Math.PI*0.5; exports.PI = Math.PI; exports.QUARTER_PI = Math.PI*0.25; exports.TAU = Math.PI*2.0; exports.TWO_PI = Math.PI*2.0; exports.CORNER = 'corner', CORNERS = 'corners', RADIUS = 'radius'; exports.RIGHT = 'right', LEFT = 'left', CENTER = 'center'; exports.POINTS = 'points', LINES = 'lines', TRIANGLES = 'triangles', TRIANGLE_FAN = 'triangles_fan', TRIANGLE_STRIP = 'triangles_strip', QUADS = 'quads', QUAD_STRIP = 'quad_strip'; exports.CLOSE = 'close'; exports.OPEN = 'open', CHORD = 'chord', PIE = 'pie'; exports.SQUARE = 'butt', ROUND = 'round', PROJECT = 'square'; // PEND: careful this is counterintuitive exports.BEVEL = 'bevel', MITER = 'miter'; exports.RGB = 'rgb', HSB = 'hsb'; exports.AUTO = 'auto'; exports.CROSS = 'crosshair', HAND = 'pointer', MOVE = 'move', TEXT = 'text', WAIT = 'wait'; ////////////////////////////////////// //// //// EXTENSIONS //// ////////////////////////////////////// //// MISC //////////////////////////// //// PElement //////////////////////// function PElement(elt, w, h) { this.elt = elt; this.width = w; this.height = h; this.elt.style.position = 'absolute'; this.x = 0; this.y = 0; this.elt.style.left = this.x+ 'px'; this.elt.style.top = this.y+ 'px'; if (elt instanceof HTMLCanvasElement) { this.context = elt.getContext('2d'); } } PElement.prototype.html = function(html) { this.elt.innerHTML = html; }; PElement.prototype.position = function(x, y) { this.x = x; this.y = y; this.elt.style.left = x+'px'; this.elt.style.top = y+'px'; }; PElement.prototype.size = function(w, h) { var aW = w, aH = h; if (aW != AUTO || aH != AUTO) { if (aW == AUTO) aW = h * this.elt.width / this.elt.height; else if (aH == AUTO) aH = w * this.elt.height / this.elt.width; this.width = aW; this.height = aH; this.elt.width = aW; this.elt.height = aH; } }; PElement.prototype.style = function(s) { this.elt.style.cssText += s; }; PElement.prototype.id = function(id) { this.elt.id = id; }; PElement.prototype.class = function(c) { this.elt.className = c; }; PElement.prototype.show = function() { this.elt.display = 'block'; } PElement.prototype.hide = function() { this.elt.style.display = 'none'; } PElement.prototype.mousePressed = function(fxn) { var _this = this; this.elt.addEventListener('click', function(e){fxn(e, _this);}, false); }; // pend false? PElement.prototype.mouseOver = function(fxn) { var _this = this; this.elt.addEventListener('mouseover', function(e){fxn(e, _this);}, false); }; PElement.prototype.mouseOut = function(fxn) { var _this = this; this.elt.addEventListener('mouseout', function(e){fxn(e, _this);}, false); }; exports.PElement = PElement; //// CREATE ////////////////////////// exports.createGraphics = function(w, h, isDefault) { //console.log('create canvas'); var c = document.createElement('canvas'); width = w; height = h; c.setAttribute('width', width); c.setAttribute('height', height); if (isDefault) { c.id = 'defaultCanvas'; } else { // remove the default canvas if new one is created var defaultCanvas = document.getElementById('defaultCanvas'); if (defaultCanvas) { defaultCanvas.parentNode.removeChild(defaultCanvas); } } document.body.appendChild(c); pCurCanvas = new PElement(c, w, h); pApplyDefaults(); pSetupInput(); context(pCurCanvas); return pCurCanvas; } exports.createElement = function(html) { var c = document.createElement('div'); c.innerHTML = html; document.body.appendChild(c); return new PElement(c); } exports.createDOMImage = function(src, alt) { var c = document.createElement('img'); c.src = src; if (typeof alt !== 'undefined') { c.alt = alt; } document.body.appendChild(c); return new PElement(c); } //// CONTEXT ///////////////////////// exports.context = function(e) { var obj = (typeof e == 'string' || e instanceof String) ? document.getElementById(id) : e; if (typeof obj !== 'undefined') { pCurCanvas = obj; width = parseInt(obj.elt.getAttribute('width'), 10); height = parseInt(obj.elt.getAttribute('height'), 10); pCurCanvas.context.setTransform(1, 0, 0, 1, 0, 0); } } //// ACCESS ////////////////////////// exports.get = function(e) { } ////////////////////////////////////// //// //// CORE PJS STUFF //// ////////////////////////////////////// var pCurCanvas; var pShapeKind = null, pShapeInited = false; var pFill = false; var pLoop = true; var pStartTime; var pUpdateInterval; var pRectMode = CORNER, pImageMode = CORNER; var pEllipseMode = CENTER; var pMatrices = [[1,0,0,1,0,0]]; var pTextSize = 12; var pColorMode = RGB; exports.onload = function() { pCreate(); }; function pCreate() { exports.createGraphics(800, 600, true); // default canvas pStartTime = new Date().getTime(); if (typeof setup === 'function') setup(); else console.log("sketch must include a setup function") pUpdateInterval = setInterval(pUpdate, 1000/frameRate); pDraw(); } function pApplyDefaults() { pCurCanvas.context.fillStyle = '#FFFFFF'; pCurCanvas.context.strokeStyle = '#000000'; pCurCanvas.context.lineCap=ROUND; } function pUpdate() { frameCount++; } function pDraw() { if (pLoop) { setTimeout(function() { requestAnimationFrame(pDraw); }, 1000 / frameRate); } // call draw if (typeof draw === 'function') draw(); pCurCanvas.context.setTransform(1, 0, 0, 1, 0, 0); } function pModeAdjust(a, b, c, d, mode) { if (mode == CORNER) { return { x: a, y: b, w: c, h: d }; } else if (mode == CORNERS) { return { x: a, y: b, w: c-a, h: d-b }; } else if (mode == RADIUS) { return { x: a-c, y: b-d, w: 2*c, h: 2*d }; } else if (mode == CENTER) { return { x: a-c*0.5, y: b-d*0.5, w: c, h: d }; } } function pMultiplyMatrix(m1, m2) { var result = []; for(var j = 0; j < m2.length; j++) { result[j] = []; for(var k = 0; k < m1[0].length; k++) { var sum = 0; for(var i = 0; i < m1.length; i++) { sum += m1[i][k] * m2[j][i]; } result[j].push(sum); } } return result; } function rgbToHex(r,g,b) { return toHex(r)+toHex(g)+toHex(b); } function toHex(n) { n = parseInt(n,10); if (isNaN(n)) return '00'; n = Math.max(0,Math.min(n,255)); return '0123456789ABCDEF'.charAt((n-n%16)/16) + '0123456789ABCDEF'.charAt(n%16); } ////////////////////////////////////// //// //// MISC HELPER FXNS //// ////////////////////////////////////// function rgb2hsv(r,g,b) { var computedH = 0; var computedS = 0; var computedV = 0; //remove spaces from input RGB values, convert to int var r = parseInt( (''+r).replace(/\s/g,''),10 ); var g = parseInt( (''+g).replace(/\s/g,''),10 ); var b = parseInt( (''+b).replace(/\s/g,''),10 ); if ( r==null || g==null || b==null || isNaN(r) || isNaN(g)|| isNaN(b) ) { alert ('Please enter numeric RGB values!'); return; } if (r<0 || g<0 || b<0 || r>255 || g>255 || b>255) { alert ('RGB values must be in the range 0 to 255.'); return; } r=r/255; g=g/255; b=b/255; var minRGB = Math.min(r,Math.min(g,b)); var maxRGB = Math.max(r,Math.max(g,b)); // Black-gray-white if (minRGB==maxRGB) { computedV = minRGB; return [0,0,computedV]; } // Colors other than black-gray-white: var d = (r==minRGB) ? g-b : ((b==minRGB) ? r-g : b-r); var h = (r==minRGB) ? 3 : ((b==minRGB) ? 1 : 5); computedH = 60*(h - d/(maxRGB - minRGB)); computedS = (maxRGB - minRGB)/maxRGB; computedV = maxRGB; return [computedH,computedS,computedV]; } function hsv2rgb(h,s,v) { // Adapted from http://www.easyrgb.com/math.html // hsv values = 0 - 1, rgb values = 0 - 255 var r, g, b; var RGB = new Array(); if(s==0){ RGB = [Math.round(v*255), Math.round(v*255), Math.round(v*255)]; }else{ // h must be < 1 var var_h = h * 6; if (var_h==6) var_h = 0; //Or ... var_i = floor( var_h ) var var_i = Math.floor( var_h ); var var_1 = v*(1-s); var var_2 = v*(1-s*(var_h-var_i)); var var_3 = v*(1-s*(1-(var_h-var_i))); if(var_i==0){ var_r = v; var_g = var_3; var_b = var_1; }else if(var_i==1){ var_r = var_2; var_g = v; var_b = var_1; }else if(var_i==2){ var_r = var_1; var_g = v; var_b = var_3 }else if(var_i==3){ var_r = var_1; var_g = var_2; var_b = v; }else if (var_i==4){ var_r = var_3; var_g = var_1; var_b = v; }else{ var_r = v; var_g = var_1; var_b = var_2 } //rgb results = 0 ÷ 255 RGB= [Math.round(var_r * 255), Math.round(var_g * 255), Math.round(var_b * 255)]; } return RGB; }; }(window));
lib/pjs.js
(function(exports) { ////////////////////////////////////// //// //// CURRENT PROCESSING API //// ////////////////////////////////////// ////////////////////////////////////// //// STRUCTURE ////////////////////////////////////// exports.draw; // needed? exports.setup; // needed? function noLoop() { if (pLoop) { pLoop = false; } } function loop() { if (!pLoop) { pLoop = true; } } function redraw() { pDraw(); } ////////////////////////////////////// //// ENVIRONMENT ////////////////////////////////////// exports.frameCount = 0; exports.frameRate = 30; exports.height = 100; exports.width = 100; // exports.focused exports.cursor = function(type) { var cursor = 'auto'; if (type == CROSS || type == HAND || type == MOVE || type == TEXT || type == WAIT) { cursor = type; } document.getElementsByTagName('body')[0].style.cursor = cursor; } exports.displayHeight = screen.height; exports.displayWidth = screen.width; exports.getFrameRate = function() { return frameRate; } exports.setFrameRate = function(fps) { frameRate = fps; clearInterval(pUpdateInterval); pUpdateInterval = setInterval(pUpdate, 1000/frameRate); } exports.noCursor = function() { document.getElementsByTagName('body')[0].style.cursor = 'none'; } ////////////////////////////////////// //// DATA ////////////////////////////////////// //// STRING FUNCTIONS //////////////// exports.join = function(list, separator) { return list.join(separator); } exports.match = function(str, reg) { return str.match(reg); } exports.matchAll = function(str, reg) { // TODO } exports.nf = function(num, a, b) { var neg = (num < 0); var n = neg ? num.toString().substring(1) : num; var str = neg ? '-' : ''; if (typeof b !== 'undefined') { for (var i=0; i<a; i++) { str += '0'; } str += n; str += '.'; for (var i=0; i<b; i++) { str += '0'; } return str; } else { for (var i=0; i<max(a-n.toString().length, 0); i++) { str += '0'; } return str+n; } } exports.nfc = function(num, right) { var dec = num.indexOf('.'); var rem = dec != -1 ? num.substring(dec) : ''; var n = dec != -1 ? num.substring(0, dec) : num; n = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); if (typeof right !== 'undefined') rem = rem.substring(0, right+1); return n+rem; } exports.nfp = function(num, a, b) { return num >= 0 ? '+'+nf(num, a, b) : nf(num, a, b); } exports.nfs = function(num, a, b) { return num >= 0 ? ' '+nf(num, a, b) : nf(num, a, b); } exports.split = function(str, delim) { return str.split(delim); } exports.splitTokens = function(str, delim) { var d = delim ? delim : /\s/g; return str.split(d).filter(function(n){return n}); } exports.trim = function(str) { if (str instanceof Array) { var strps = []; for (var i=0; i<str.length; i++) { stps.push(str[i].trim()); } return strps; } else return str.trim(); } //// ARRAY FUNCTIONS ///////////////// exports.append = function(array, value) { array.push(value); return array; } exports.arrayCopy = function(src, a, b, c, d) { //src, srcPosition, dst, dstPosition, length if (typeof d !== 'undefined') { for (var i=a; i<min(a+d, srpCurCanvas.length); i++) { b[dstPosition+i] = src[i]; } } else if (typeof b !== 'undefined') { //src, dst, length a = srpCurCanvas.slice(0, min(b, srpCurCanvas.length)); } else { //src, dst a = srpCurCanvas.slice(0); } } exports.concat = function(list0, list1) { return list0.concat(list1); } exports.reverse = function(list) { return list.reverse(); } exports.shorten = function(list) { list.pop(); return list; } exports.sort = function(list, count) { var arr = count ? list.slice(0, min(count, list.length)) : list; var rest = count ? list.slice(min(count, list.length)) : []; if (typeof arr[0] === 'string') { arr = arr.sort(); } else { arr = arr.sort(function(a,b){return a-b}); } return arr.concat(rest); } exports.splice = function(list, value, index) { return list.splice(index,0,value); } exports.subset = function(list, start, count) { if (typeof count !== 'undefined') return list.slice(start, start+count); else return list.slice(start, list.length-1); } ////////////////////////////////////// //// SHAPE ////////////////////////////////////// //// 2D PRIMITIVES /////////////////// exports.arc = function(a, b, c, d, start, stop, mode) { } exports.ellipse = function(a, b, c, d) { var vals = pModeAdjust(a, b, c, d, pEllipseMode); var kappa = .5522848, ox = (vals.w / 2) * kappa, // control point offset horizontal oy = (vals.h / 2) * kappa, // control point offset vertical xe = vals.x + vals.w, // x-end ye = vals.y + vals.h, // y-end xm = vals.x + vals.w / 2, // x-middle ym = vals.y + vals.h / 2; // y-middle pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(vals.x, ym); pCurCanvas.context.bezierCurveTo(vals.x, ym - oy, xm - ox, vals.y, xm, vals.y); pCurCanvas.context.bezierCurveTo(xm + ox, vals.y, xe, ym - oy, xe, ym); pCurCanvas.context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); pCurCanvas.context.bezierCurveTo(xm - ox, ye, vals.x, ym + oy, vals.x, ym); pCurCanvas.context.closePath(); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } exports.line = function(x1, y1, x2, y2) { if (pCurCanvas.context.strokeStyle === 'none') { return; } pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.lineTo(x2, y2); pCurCanvas.context.stroke(); } exports.point = function(x, y) { var s = pCurCanvas.context.strokeStyle; var f = pCurCanvas.context.fillStyle; if (s === 'none') { return; } x = Math.round(x); y = Math.round(y); pCurCanvas.context.fillStyle = s; if (pCurCanvas.context.lineWidth > 1) { pCurCanvas.context.beginPath(); pCurCanvas.context.arc(x, y, pCurCanvas.context.lineWidth / 2, 0, TWO_PI, false); pCurCanvas.context.fill(); } else { pCurCanvas.context.fillRect(x, y, 1, 1); } pCurCanvas.context.fillStyle = f; } exports.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.lineTo(x2, y2); pCurCanvas.context.lineTo(x3, y3); pCurCanvas.context.lineTo(x4, y4); pCurCanvas.context.closePath(); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } exports.rect = function(a, b, c, d) { var vals = pModeAdjust(a, b, c, d, pRectMode); pCurCanvas.context.beginPath(); pCurCanvas.context.rect(vals.x, vals.y, vals.w, vals.h); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } exports.triangle = function(x1, y1, x2, y2, x3, y3) { pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.lineTo(x2, y2); pCurCanvas.context.lineTo(x3, y3); pCurCanvas.context.closePath(); pCurCanvas.context.fill(); pCurCanvas.context.stroke(); } //// CURVES ////////////////////////// exports.bezier = function(x1, y1, x2, y2, x3, y3, x4, y4) { pCurCanvas.context.beginPath(); pCurCanvas.context.moveTo(x1, y1); pCurCanvas.context.bezierCurveTo(x2, y2, x3, y3, x4, y4); pCurCanvas.context.stroke(); } exports.bezierDetail = function() { // TODO } exports.bezierPoint = function() { // TODO } exports.bezierTangent = function() { // TODO } exports.curve = function() { // TODO } exports.curveDetail = function() { // TODO } exports.curvePoint = function() { // TODO } exports.curveTangent = function() { // TODO } exports.curveTightness = function() { // TODO } //// ATTRIBUTES ////////////////////// exports.ellipseMode = function(m) { if (m == CORNER || m == CORNERS || m == RADIUS || m == CENTER) { pEllipseMode = m; } } exports.noSmooth = function() { pCurCanvas.context.mozImageSmoothingEnabled = false; pCurCanvas.context.webkitImageSmoothingEnabled = false; } exports.rectMode = function(m) { if (m == CORNER || m == CORNERS || m == RADIUS || m == CENTER) { pRectMode = m; } } exports.smooth = function() { pCurCanvas.context.mozImageSmoothingEnabled = true; pCurCanvas.context.webkitImageSmoothingEnabled = true; } exports.strokeCap = function(cap) { if (cap == ROUND || cap == SQUARE || cap == PROJECT) { pCurCanvas.context.lineCap=cap; } } exports.strokeJoin = function(join) { if (join == ROUND || join == BEVEL || join == MITER) { pCurCanvas.context.lineJoin = join; } } exports.strokeWeight = function(w) { pCurCanvas.context.lineWidth = w; if (typeof w === 'undefined') noStroke(); } //// VERTEX ////////////////////////// exports.beginContour = function() { // TODO } exports.beginShape = function(kind) { if (kind == POINTS || kind == LINES || kind == TRIANGLES || kind == TRIANGLE_FAN || kind == TRIANGLE_STRIP || kind == QUADS || kind == QUAD_STRIP) pShapeKind = kind; else pShapeKind = null; pShapeInited = true; pCurCanvas.context.beginPath(); } exports.bezierVertex = function(x1, y1, x2, y2, x3, y3) { pCurCanvas.context.bezierCurveTo(x1, y1, x2, y2, x3, y3); } exports.curveVertex = function() { // TODO } exports.endContour = function() { // TODO } exports.endShape = function(mode) { if (mode == CLOSE) { pCurCanvas.context.closePath(); pCurCanvas.context.fill(); } pCurCanvas.context.stroke(); } exports.quadraticVertex = function(cx, cy, x3, y3) { pCurCanvas.context.quadraticCurveTo(cx, cy, x3, y3); } exports.vertex = function(x, y) { if (pShapeInited) { pCurCanvas.context.moveTo(x, y); } else { pCurCanvas.context.lineTo(x, y); // pend this is where check for kind and do other stuff } pShapeInited = false; } ////////////////////////////////////// //// INPUT ////////////////////////////////////// //// MOUSE /////////////////////////// exports.mouseX = 0; exports.mouseY = 0; var pMousePressed = false; var pmouseX = 0; var pmouseY = 0; exports.isMousePressed = function() { return pMousePressed; } exports.pUpdateMouseCoords = function(e) { pmouseX = exports.mouseX; pmouseY = exports.mouseY; exports.mouseX = e.clientX;// - parseInt(pCurCanvas.elt.style.left, 10); exports.mouseY = e.clientY;// - parseInt(pCurCanvas.elt.style.top, 10); // console.log(mouseX+' '+mouseY); // console.log('mx = '+mouseX+' my = '+mouseY); } //// KEYBOARD //////////////////////// exports.key = ''; exports.keyCode = 0; var pKeyPressed = false; exports.isKeyPressed = function() { return pKeyPressed; } function pSetupInput() { document.body.onmousemove=function(e){ pUpdateMouseCoords(e); if (typeof mouseMoved === 'function') mouseMoved(e); } document.body.onmousedown=function(e){ pMousePressed = true; if (typeof mousePressed === 'function') mousePressed(e); } document.body.onmouseup=function(e){ pMousePressed = false; if (typeof mouseReleased === 'function') mouseReleased(e); } document.body.onmouseclick=function(e){ if (typeof mouseClicked === 'function') mouseClicked(e); } document.body.onkeydown=function(e){ pKeyPressed = true; if (typeof keyPressed === 'function') keyPressed(e); } document.body.onkeyup=function(e){ pKeyPressed = false; if (typeof keyReleased === 'function') keyReleased(e); } document.body.onkeypress=function(e){ keyCode = e.keyCode; if (typeof keyTyped === 'function') keyTyped(e); } } //// FILES /////////////////////////// //BufferedReader exports.createInput = function() { // TODO } exports.createReader = function() { // TODO } exports.loadBytes = function() { // TODO } exports.loadJSON = function(file, callback) { var req = new XMLHttpRequest(); req.overrideMimeType('application/json'); req.open('GET', 'data/'+file); req.onreadystatechange = function () { if(req.readyState === 4) { if(req.status === 200 || req.status == 0) { if (typeof callback !== 'undefined') callback(); return JSON.parse(req.responseText); } } } req.send(null); } exports.loadStrings = function(file, callback) { var req = new XMLHttpRequest(); req.open('GET', 'data/'+file, true); req.onreadystatechange = function () { if(req.readyState === 4) { if(req.status === 200 || req.status == 0) { if (typeof callback !== 'undefined') callback(); return req.responseText.match(/[^\r\n]+/g); } } } req.send(null); } exports.loadTable = function () { // TODO } /*exports.loadXML = function() { var req = new XMLHttpRequest(); req.overrideMimeType('application/json'); req.overrideMimeType('text/xml'); req.open('GET', 'data/'+file, false); req.onreadystatechange = function () { if(req.readyState === 4) { if(req.status === 200 || req.status == 0) { console.log(JSON.parse(req.responseXML)); return JSON.parse(req.responseXML); } } } req.send(null); }*/ exports.open = function() { // TODO } exports.parseXML = function() { // TODO } exports.saveTable = function() { // TODO } exports.selectFolder = function() { // TODO } exports.selectInput = function() { // TODO } //// TIME & DATE ///////////////////// exports.day = function() { return new Date().getDate(); } exports.hour = function() { return new Date().getHours(); } exports.millis = function() { return new Date().getTime() - pStartTime; } exports.month = function() { return new Date().getMonth(); } exports.second = function() { return new Date().getSeconds(); } exports.year = function() { return new Date().getFullYear(); } ////////////////////////////////////// //// OUTPUT ////////////////////////////////////// //// TEXT AREA /////////////////////// exports.println = function(s) { console.log(s); } //// IMAGE /////////////////////////// exports.save = function() { exports.open(pCurCanvas.toDataURL()); } //// FILES /////////////////////////// exports.pWriters = []; exports.beginRaw = function() { // TODO } exports.beginRecord = function() { // TODO } exports.createOutput = function() { // TODO } exports.createWriter = function(name) { if (pWriters.indexOf(name) == -1) { // check it doesn't already exist pWriters['name'] = new PrintWriter(name); } } exports.endRaw = function() { // TODO } exports.endRecord = function() { // TODO } exports.PrintWriter = function(name) { this.name = name; this.content = ''; this.print = function(data) { this.content += data; }; this.println = function(data) { this.content += data + '\n'; }; this.flush = function() { this.content = ''; }; this.close = function() { writeFile(this.content); }; } exports.saveBytes = function() { // TODO } exports.saveJSONArray = function() { // TODO } exports.saveJSONObject = function() { // TODO } exports.saveStream = function() { // TODO } exports.saveStrings = function(list) { writeFile(list.join('\n')); } exports.saveXML = function() { // TODO } exports.selectOutput = function() { // TODO } exports.writeFile = function(content) { exports.open('data:text/json;charset=utf-8,' + escape(content), 'download'); } ////////////////////////////////////// //// TRANSFORM ////////////////////////////////////// exports.applyMatrix = function(n00, n01, n02, n10, n11, n12) { pCurCanvas.context.transform(n00, n01, n02, n10, n11, n12); var m = pMatrices[pMatrices.length-1]; m = pMultiplyMatrix(m, [n00, n01, n02, n10, n11, n12]); } exports.popMatrix = function() { pCurCanvas.context.restore(); pMatrices.pop(); } exports.printMatrix = function() { console.log(pMatrices[pMatrices.length-1]); } exports.pushMatrix = function() { pCurCanvas.context.save(); pMatrices.push([1,0,0,1,0,0]); } exports.resetMatrix = function() { pCurCanvas.context.setTransform(); pMatrices[pMatrices.length-1] = [1,0,0,1,0,0]; } exports.rotate = function(r) { pCurCanvas.context.rotate(r); var m = pMatrices[pMatrices.length-1]; var c = Math.cos(r); var s = Math.sin(r); var m11 = m[0] * c + m[2] * s; var m12 = m[1] * c + m[3] * s; var m21 = m[0] * -s + m[2] * c; var m22 = m[1] * -s + m[3] * c; m[0] = m11; m[1] = m12; m[2] = m21; m[3] = m22; } exports.scale = function(x, y) { pCurCanvas.context.scale(x, y); var m = pMatrices[pMatrices.length-1]; m[0] *= x; m[1] *= x; m[2] *= y; m[3] *= y; } exports.shearX = function(angle) { pCurCanvas.context.transform(1, 0, tan(angle), 1, 0, 0); var m = pMatrices[pMatrices.length-1]; m = pMultiplyMatrix(m, [1, 0, tan(angle), 1, 0, 0]); } exports.shearY = function(angle) { pCurCanvas.context.transform(1, tan(angle), 0, 1, 0, 0); var m = pMatrices[pMatrices.length-1]; m = pMultiplyMatrix(m, [1, tan(angle), 0, 1, 0, 0]); } exports.translate = function(x, y) { pCurCanvas.context.translate(x, y); var m = pMatrices[pMatrices.length-1]; m[4] += m[0] * x + m[2] * y; m[5] += m[1] * x + m[3] * y; } ////////////////////////////////////// //// COLOR ////////////////////////////////////// //// SETTING ///////////////////////// exports.background = function(v1, v2, v3) { var c = processColorArgs(v1, v2, v3); // save out the fill var curFill = pCurCanvas.context.fillStyle; // create background rect pCurCanvas.context.fillStyle = rgbToHex(c[0], c[1], c[2]); pCurCanvas.context.fillRect(0, 0, width, height); // reset fill pCurCanvas.context.fillStyle = curFill; } exports.clear = function() { // TODO } exports.colorMode = function(mode) { if (mode == RGB || mode == HSB) pColorMode = mode; } exports.fill = function(v1, v2, v3, a) { var c = processColorArgs(v1, v2, v3, a); if (typeof c[3] !== 'undefined') { pCurCanvas.context.fillStyle = 'rgba('+c[0]+','+c[1]+','+c[2]+','+(parseInt(c[3], 10)/255.0)+')'; } else { pCurCanvas.context.fillStyle = 'rgb('+c[0]+','+c[1]+','+c[2]+')'; } } exports.noFill = function() { pCurCanvas.context.fillStyle = 'none'; } exports.noStroke = function() { pCurCanvas.context.strokeStyle = 'none'; } exports.stroke = function(v1, v2, v3, a) { var c = processColorArgs(v1, v2, v3, a); if (typeof c[3] !== 'undefined') { pCurCanvas.context.strokeStyle = 'rgba('+c[0]+','+c[1]+','+c[2]+','+(parseInt(c[3], 10)/255.0)+')'; } else { pCurCanvas.context.strokeStyle = 'rgb('+c[0]+','+c[1]+','+c[2]+')'; } } function processColorArgs(v1, v2, v3, a) { var c = []; if (typeof v2 === 'undefined' || typeof v3 === 'undefined') { if (typeof v1 === 'object') { if (v1.length == 2) { c = [v1[0], v1[0], v1[0], v1[1]]; } else { c = [v1[0], v1[1], v1[2], v1[3]]; } } else { c = [v1, v1, v1, v2]; } } else { if (typeof a !== 'undefined') { c = [v1, v2, v3, a]; } else { c = [v1, v2, v3]; } } if (pColorMode == HSB) { c = hsv2rgb(c[0], c[1], c[2]); } return c; } //// CREATING & READING ////////////// exports.alpha = function(rgb) { if (rgb.length > 3) return rgb[3]; else return 255; } exports.blue = function(rgb) { if (rgb.length > 2) return rgb[2]; else return 0; } exports.brightness = function(hsv) { if (rgb.length > 2) return rgb[2]; else return 0; } exports.color = function(gray) { return [gray, gray, gray]; } exports.color = function(gray, alpha) { return [gray, gray, gray, alpha]; } exports.color = function(v1, v2, v3) { return [v1, v2, v3]; } exports.color = function(v1, v2, v3, alpha) { return [v1, v2, v3, alpha]; } exports.green = function(rgb) { if (rgb.length > 2) return rgb[1]; else return 0; } exports.hue = function(hsv) { if (rgb.length > 2) return rgb[0]; else return 0; } exports.lerpColor = function(c1, c2, amt) { var c = []; for (var i=0; i<c1.length; i++) { c.push(lerp(c1[i], c2[i], amt)); } return c; } exports.red = function(rgb) { if (rgb.length > 2) return rgb[0]; else return 0; } exports.saturation = function(hsv) { if (rgb.length > 2) return rgb[1]; else return 0; } ////////////////////////////////////// //// IMAGE ////////////////////////////////////// //// PIMAGE ////////////////////////// exports.createImage = function(w, h, format) { return new PImage(w, h); } //pend format? function PImage(w, h) { this.image = pCurCanvas.context.createImageData(w,h); this.pixels = []; this.updatePixelArray(); } PImage.prototype.updatePixelArray = function() { for (var i=0; i<this.data.length; i+=4) { this.pixels.push([this.data[i], this.data[i+1], this.data[i+2], this.data[i+3]]); } } PImage.prototype.loadPixels = function() { this.image = context.createImageData(imageData); this.updatePixelArray(); }; PImage.prototype.updatePixels = function() { for (var i=0; i<this.pixels; i+=4) { for (var j=0; j<4; j++) { this.data[4*i+j] = this.pixels[i][j]; } } }; PImage.prototype.resize = function() { // TODO }; PImage.prototype.set = function() { // TODO // writes a color to any pixel or writes an image into another }; PImage.prototype.mask = function() { // TODO // Masks part of an image with another image as an alpha channel }; PImage.prototype.filter = function() { // TODO // Converts the image to grayscale or black and white }; PImage.prototype.copy = function() { // TODO // Copies the entire image }; PImage.prototype.blend = function() { // TODO // Copies a pixel or rectangle of pixels using different blending modes }; PImage.prototype.save = function() { // TODO // Saves the image to a TIFF, TARGA, PNG, or JPEG file*/ }; PImage.prototype.get = function(x, y, w, h) { var wp = w ? w : 1; var hp = h ? h : 1; var vals = []; for (var j=y; j<y+hp; j++) { for (var i=x; i<x+wp; i++) { vals.push(this.pixels[j*this.width+i]); } } } exports.PImage = PImage; //// LOADING & DISPLAYING ////////////////// exports.image = function(img, a, b, c, d) { if (typeof c !== 'undefined' && typeof d !== 'undefined') { var vals = pModeAdjust(a, b, c, d, pImageMode); pCurCanvas.context.drawImage(img, vals.x, vals.y, vals.w, vals.h); } else { pCurCanvas.context.drawImage(img, a, b); } } exports.imageMode = function(m) { if (m == CORNER || m == CORNERS || m == CENTER) pImageMode = m; } exports.loadImage = function(path, callback) { var imgObj = new Image(); imgObj.onload = function() { if (typeof callback !== 'undefined') callback(); } imgObj.src = path; return imgObj; } //// PIXELS //////////////////////////////// exports.pixels = []; exports.blend = function() { // TODO } exports.copy = function() { // TODO } exports.filter = function() { // TODO } exports.get = function(x, y, w, h) { var pix = pCurCanvas.context.getImageData(0, 0, width, height).data.slice(0); if (typeof w !== 'undefined' && typeof h !== 'undefined') { var region = []; for (var j=0; j<h; j++) { for (var i=0; i<w; i++) { region[i*w+j] = pix[(y+j)*width+(x+i)]; } } return region; } else if (typeof x !== 'undefined' && typeof y !== 'undefined') { if (x >= 0 && x < width && y >= 0 && y < height) { return pix[y*width+x].data; } else { return [0, 0, 0, 255]; } } else { return pix; } } exports.loadPixels = function() { pixels = pCurCanvas.context.getImageData(0, 0, width, height).data.slice(0); // pend should this be 0,0 or pCurCanvas.offsetLeft,pCurCanvas.offsetTop? } exports.set = function() { // TODO } exports.updatePixels = function() { if (typeof pixels !== 'undefined') { var imgd = pCurCanvas.context.getImageData(x, y, width, height); imgd = pixels; context.putImageData(imgd, 0, 0); } } ////////////////////////////////////// //// TYPOGRAPHY ////////////////////////////////////// //// LOADING & DISPLAYING //////////// exports.text = function(s, x, y) { pCurCanvas.context.font=pTextSize+'px Verdana'; pCurCanvas.context.fillText(s, x, y); } //// ATTRIBUTES ////////////////////// exports.textAlign = function(a) { if (a == LEFT || a == RIGHT || a == CENTER) pCurCanvas.context.textAlign = a; } exports.textSize = function(s) { pTextSize = s; } exports.textWidth = function(s) { return pCurCanvas.context.measureText(s).width; } exports.textHeight = function(s) { return pCurCanvas.context.measureText(s).height; } ////////////////////////////////////// //// MATH ////////////////////////////////////// //// CALCULATION ///////////////////// /** @module Math */ /** returns abs value */ exports.abs = function(n) { return Math.abs(n); } exports.ceil = function(n) { return Math.ceil(n); } exports.constrain = function(n, l, h) { return max(min(n, h), l); } exports.dist = function(x1, y1, x2, y2) { var xs = x2-x1; var ys = y2-y1; return Math.sqrt( xs*xs + ys*ys ); } exports.exp = function(n) { return Math.exp(n); } exports.floor = function(n) { return Math.floor(n); } exports.lerp = function(start, stop, amt) { return amt*(stop-start)+start; } exports.log = function(n) { return Math.log(n); } exports.mag = function(x, y) { return Math.sqrt(x*x+y*y); } exports.map = function(n, start1, stop1, start2, stop2) { return ((n-start1)/(stop1-start1))*(stop2-start2)+start2; } exports.max = function(a, b) { return Math.max(a, b); } exports.min = function(a, b) { return Math.min(a, b); } exports.norm = function(n, start, stop) { return map(n, start, stop, 0, 1); } exports.pow = function(n, e) { return Math.pow(n, e); } exports.sq = function(n) { return n*n; } exports.sqrt = function(n) { return Math.sqrt(n); } //// TRIGONOMETRY //////////////////// exports.acos = function(x) { return Math.acos(x); } exports.asin = function(x) { return Math.asin(x); } exports.atan = function(x) { return Math.atan(x); } exports.atan2 = function(y, x) { return Math.atan2(y, x); } exports.cos = function(x) { return Math.cos(x); } exports.degrees = function(x) { return 360.0*x/(2*Math.PI); } exports.radians = function(x) { return 2*Math.PI*x/360.0; } exports.sin = function(x) { return Math.sin(x); } exports.tan = function(x) { return Math.tan(x); } //// RANDOM ////////////////////////// exports.random = function(x, y) { // might want to use this kind of check instead: // if (arguments.length === 0) { if (typeof x !== 'undefined' && typeof y !== 'undefined') { return (y-x)*Math.random()+x; } else if (typeof x !== 'undefined') { return x*Math.random(); } else { return Math.random(); } } ////////////////////////////////////// //// //// CONSTANTS //// ////////////////////////////////////// exports.HALF_PI = Math.PI*0.5; exports.PI = Math.PI; exports.QUARTER_PI = Math.PI*0.25; exports.TAU = Math.PI*2.0; exports.TWO_PI = Math.PI*2.0; exports.CORNER = 'corner', CORNERS = 'corners', RADIUS = 'radius'; exports.RIGHT = 'right', LEFT = 'left', CENTER = 'center'; exports.POINTS = 'points', LINES = 'lines', TRIANGLES = 'triangles', TRIANGLE_FAN = 'triangles_fan', TRIANGLE_STRIP = 'triangles_strip', QUADS = 'quads', QUAD_STRIP = 'quad_strip'; exports.CLOSE = 'close'; exports.OPEN = 'open', CHORD = 'chord', PIE = 'pie'; exports.SQUARE = 'butt', ROUND = 'round', PROJECT = 'square'; // PEND: careful this is counterintuitive exports.BEVEL = 'bevel', MITER = 'miter'; exports.RGB = 'rgb', HSB = 'hsb'; exports.AUTO = 'auto'; exports.CROSS = 'crosshair', HAND = 'pointer', MOVE = 'move', TEXT = 'text', WAIT = 'wait'; ////////////////////////////////////// //// //// EXTENSIONS //// ////////////////////////////////////// //// MISC //////////////////////////// //// PElement //////////////////////// function PElement(elt, w, h) { this.elt = elt; this.width = w; this.height = h; this.elt.style.position = 'absolute'; this.x = 0; this.y = 0; this.elt.style.left = this.x+ 'px'; this.elt.style.top = this.y+ 'px'; if (elt instanceof HTMLCanvasElement) { this.context = elt.getContext('2d'); } } PElement.prototype.html = function(html) { this.elt.innerHTML = html; }; PElement.prototype.position = function(x, y) { this.x = x; this.y = y; this.elt.style.left = x+'px'; this.elt.style.top = y+'px'; }; PElement.prototype.size = function(w, h) { var aW = w, aH = h; if (aW != AUTO || aH != AUTO) { if (aW == AUTO) aW = h * this.elt.width / this.elt.height; else if (aH == AUTO) aH = w * this.elt.height / this.elt.width; this.width = aW; this.height = aH; this.elt.width = aW; this.elt.height = aH; } }; PElement.prototype.style = function(s) { this.elt.style.cssText += s; }; PElement.prototype.id = function(id) { this.elt.id = id; }; PElement.prototype.class = function(c) { this.elt.className = c; }; PElement.prototype.show = function() { this.elt.display = 'block'; } PElement.prototype.hide = function() { this.elt.style.display = 'none'; } PElement.prototype.mousePressed = function(fxn) { var _this = this; this.elt.addEventListener('click', function(e){fxn(e, _this);}, false); }; // pend false? PElement.prototype.mouseOver = function(fxn) { var _this = this; this.elt.addEventListener('mouseover', function(e){fxn(e, _this);}, false); }; PElement.prototype.mouseOut = function(fxn) { var _this = this; this.elt.addEventListener('mouseout', function(e){fxn(e, _this);}, false); }; exports.PElement = PElement; //// CREATE ////////////////////////// exports.createGraphics = function(w, h, isDefault) { //console.log('create canvas'); var c = document.createElement('canvas'); width = w; height = h; c.setAttribute('width', width); c.setAttribute('height', height); if (isDefault) { c.id = 'defaultCanvas'; } else { // remove the default canvas if new one is created var defaultCanvas = document.getElementById('defaultCanvas'); if (defaultCanvas) { defaultCanvas.parentNode.removeChild(defaultCanvas); } } document.body.appendChild(c); pCurCanvas = new PElement(c, w, h); pApplyDefaults(); pSetupInput(); context(pCurCanvas); return pCurCanvas; } exports.createElement = function(html) { var c = document.createElement('div'); c.innerHTML = html; document.body.appendChild(c); return new PElement(c); } exports.createImage = function(src, alt) { var c = document.createElement('img'); c.src = src; if (typeof alt !== 'undefined') { c.alt = alt; } document.body.appendChild(c); return new PElement(c); } //// CONTEXT ///////////////////////// exports.context = function(e) { var obj = (typeof e == 'string' || e instanceof String) ? document.getElementById(id) : e; if (typeof obj !== 'undefined') { pCurCanvas = obj; width = parseInt(obj.elt.getAttribute('width'), 10); height = parseInt(obj.elt.getAttribute('height'), 10); pCurCanvas.context.setTransform(1, 0, 0, 1, 0, 0); } } //// ACCESS ////////////////////////// exports.get = function(e) { } ////////////////////////////////////// //// //// CORE PJS STUFF //// ////////////////////////////////////// var pCurCanvas; var pShapeKind = null, pShapeInited = false; var pFill = false; var pLoop = true; var pStartTime; var pUpdateInterval; var pRectMode = CORNER, pImageMode = CORNER; var pEllipseMode = CENTER; var pMatrices = [[1,0,0,1,0,0]]; var pTextSize = 12; var pColorMode = RGB; exports.onload = function() { pCreate(); }; function pCreate() { exports.createGraphics(800, 600, true); // default canvas pStartTime = new Date().getTime(); if (typeof setup === 'function') setup(); else console.log("sketch must include a setup function") pUpdateInterval = setInterval(pUpdate, 1000/frameRate); pDraw(); } function pApplyDefaults() { pCurCanvas.context.fillStyle = '#FFFFFF'; pCurCanvas.context.strokeStyle = '#000000'; pCurCanvas.context.lineCap=ROUND; } function pUpdate() { frameCount++; } function pDraw() { if (pLoop) { setTimeout(function() { requestAnimationFrame(pDraw); }, 1000 / frameRate); } // call draw if (typeof draw === 'function') draw(); pCurCanvas.context.setTransform(1, 0, 0, 1, 0, 0); } function pModeAdjust(a, b, c, d, mode) { if (mode == CORNER) { return { x: a, y: b, w: c, h: d }; } else if (mode == CORNERS) { return { x: a, y: b, w: c-a, h: d-b }; } else if (mode == RADIUS) { return { x: a-c, y: b-d, w: 2*c, h: 2*d }; } else if (mode == CENTER) { return { x: a-c*0.5, y: b-d*0.5, w: c, h: d }; } } function pMultiplyMatrix(m1, m2) { var result = []; for(var j = 0; j < m2.length; j++) { result[j] = []; for(var k = 0; k < m1[0].length; k++) { var sum = 0; for(var i = 0; i < m1.length; i++) { sum += m1[i][k] * m2[j][i]; } result[j].push(sum); } } return result; } function rgbToHex(r,g,b) { return toHex(r)+toHex(g)+toHex(b); } function toHex(n) { n = parseInt(n,10); if (isNaN(n)) return '00'; n = Math.max(0,Math.min(n,255)); return '0123456789ABCDEF'.charAt((n-n%16)/16) + '0123456789ABCDEF'.charAt(n%16); } ////////////////////////////////////// //// //// MISC HELPER FXNS //// ////////////////////////////////////// function rgb2hsv(r,g,b) { var computedH = 0; var computedS = 0; var computedV = 0; //remove spaces from input RGB values, convert to int var r = parseInt( (''+r).replace(/\s/g,''),10 ); var g = parseInt( (''+g).replace(/\s/g,''),10 ); var b = parseInt( (''+b).replace(/\s/g,''),10 ); if ( r==null || g==null || b==null || isNaN(r) || isNaN(g)|| isNaN(b) ) { alert ('Please enter numeric RGB values!'); return; } if (r<0 || g<0 || b<0 || r>255 || g>255 || b>255) { alert ('RGB values must be in the range 0 to 255.'); return; } r=r/255; g=g/255; b=b/255; var minRGB = Math.min(r,Math.min(g,b)); var maxRGB = Math.max(r,Math.max(g,b)); // Black-gray-white if (minRGB==maxRGB) { computedV = minRGB; return [0,0,computedV]; } // Colors other than black-gray-white: var d = (r==minRGB) ? g-b : ((b==minRGB) ? r-g : b-r); var h = (r==minRGB) ? 3 : ((b==minRGB) ? 1 : 5); computedH = 60*(h - d/(maxRGB - minRGB)); computedS = (maxRGB - minRGB)/maxRGB; computedV = maxRGB; return [computedH,computedS,computedV]; } function hsv2rgb(h,s,v) { // Adapted from http://www.easyrgb.com/math.html // hsv values = 0 - 1, rgb values = 0 - 255 var r, g, b; var RGB = new Array(); if(s==0){ RGB = [Math.round(v*255), Math.round(v*255), Math.round(v*255)]; }else{ // h must be < 1 var var_h = h * 6; if (var_h==6) var_h = 0; //Or ... var_i = floor( var_h ) var var_i = Math.floor( var_h ); var var_1 = v*(1-s); var var_2 = v*(1-s*(var_h-var_i)); var var_3 = v*(1-s*(1-(var_h-var_i))); if(var_i==0){ var_r = v; var_g = var_3; var_b = var_1; }else if(var_i==1){ var_r = var_2; var_g = v; var_b = var_1; }else if(var_i==2){ var_r = var_1; var_g = v; var_b = var_3 }else if(var_i==3){ var_r = var_1; var_g = var_2; var_b = v; }else if (var_i==4){ var_r = var_3; var_g = var_1; var_b = v; }else{ var_r = v; var_g = var_1; var_b = var_2 } //rgb results = 0 ÷ 255 RGB= [Math.round(var_r * 255), Math.round(var_g * 255), Math.round(var_b * 255)]; } return RGB; }; }(window));
changing createImage (for dom elt) to createDOMImage to avoid overlap with canvas / PGraphics createImage
lib/pjs.js
changing createImage (for dom elt) to createDOMImage to avoid overlap with canvas / PGraphics createImage
<ide><path>ib/pjs.js <ide> ////////////////////////////////////// <ide> <ide> //// TEXT AREA /////////////////////// <del> <add> exports.print = function(s) { <add> console.log(s); <add> } <ide> exports.println = function(s) { <ide> console.log(s); <ide> } <ide> this.pixels = []; <ide> this.updatePixelArray(); <ide> } <add> PImage.prototype.loadPixels = function() { <add> this.image = context.createImageData(imageData); <add> this.updatePixelArray(); <add> }; <ide> PImage.prototype.updatePixelArray = function() { <ide> for (var i=0; i<this.data.length; i+=4) { <ide> this.pixels.push([this.data[i], this.data[i+1], this.data[i+2], this.data[i+3]]); <ide> } <ide> } <del> PImage.prototype.loadPixels = function() { <del> this.image = context.createImageData(imageData); <del> this.updatePixelArray(); <del> }; <ide> PImage.prototype.updatePixels = function() { <ide> for (var i=0; i<this.pixels; i+=4) { <ide> for (var j=0; j<4; j++) { <ide> }; <ide> PImage.prototype.resize = function() { <ide> // TODO <del> }; <del> PImage.prototype.set = function() { <del> // TODO <del> // writes a color to any pixel or writes an image into another <del> }; <del> PImage.prototype.mask = function() { <del> // TODO <del> // Masks part of an image with another image as an alpha channel <del> }; <del> PImage.prototype.filter = function() { <del> // TODO <del> // Converts the image to grayscale or black and white <del> }; <del> PImage.prototype.copy = function() { <del> // TODO <del> // Copies the entire image <del> }; <del> PImage.prototype.blend = function() { <del> // TODO <del> // Copies a pixel or rectangle of pixels using different blending modes <del> }; <del> PImage.prototype.save = function() { <del> // TODO <del> // Saves the image to a TIFF, TARGA, PNG, or JPEG file*/ <ide> }; <ide> PImage.prototype.get = function(x, y, w, h) { <ide> var wp = w ? w : 1; <ide> } <ide> } <ide> } <add> PImage.prototype.set = function() { <add> // TODO <add> // writes a color to any pixel or writes an image into another <add> }; <add> PImage.prototype.mask = function() { <add> // TODO <add> // Masks part of an image with another image as an alpha channel <add> }; <add> PImage.prototype.filter = function() { <add> // TODO <add> // Converts the image to grayscale or black and white <add> }; <add> PImage.prototype.copy = function() { <add> // TODO <add> // Copies the entire image <add> }; <add> PImage.prototype.blend = function() { <add> // TODO <add> // Copies a pixel or rectangle of pixels using different blending modes <add> }; <add> PImage.prototype.save = function() { <add> // TODO <add> // Saves the image to a TIFF, TARGA, PNG, or JPEG file*/ <add> }; <ide> exports.PImage = PImage; <ide> <ide> //// LOADING & DISPLAYING ////////////////// <ide> <ide> return new PElement(c); <ide> } <del> exports.createImage = function(src, alt) { <add> exports.createDOMImage = function(src, alt) { <ide> var c = document.createElement('img'); <ide> c.src = src; <ide> if (typeof alt !== 'undefined') {
Java
apache-2.0
04adea3e049cdef9da9c0e70a801833b2850ffc2
0
thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck
/* * Copyright (C) 2003 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck.testcase.generic; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; /** * Base class to compare a certain set of things (e.g. biotypes, xrefs) from one database with the equivalent things in the previous * database. * * Extending classes should implement the description, threshold and getCounts() methods. See individual Javadocs for details. */ public abstract class ComparePreviousVersionBase extends SingleDatabaseTestCase { /** * Run the test. * * @param dbre * The database to use. * @return true if the test passed. * */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; if (System.getProperty("ignore.previous.checks") != null) { logger.finest("ignore.previous.checks is set in database.properties, skipping this test"); return true; } DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre); if (sec == null) { logger.warning("Can't get equivalent database for " + dbre.getName()); return true; } logger.finest("Equivalent database on secondary server is " + sec.getName()); Map currentCounts = getCounts(dbre); Map secondaryCounts = getCounts(sec); // compare each of the secondary (previous release, probably) with current Set externalDBs = secondaryCounts.keySet(); Iterator it = externalDBs.iterator(); String successText = ""; // show % tolerance here? double tolerance = (100 - ((threshold() / 1) * 100)); if (testUpperThreshold()) { successText = " - within tolerance +/-" + tolerance + "%"; } else { successText = " - greater or within tolerance"; } while (it.hasNext()) { String key = (String) it.next(); int secondaryCount = ((Integer) (secondaryCounts.get(key))).intValue(); if (secondaryCount == 0) { continue; } // check it exists at all if (currentCounts.containsKey(key)) { int currentCount = ((Integer) (currentCounts.get(key))).intValue(); if (((double) currentCount / (double) secondaryCount) < threshold()) { ReportManager.problem(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " only has " + currentCount); result = false; } else if (testUpperThreshold() && // ((1 -(double) secondaryCount / (double) currentCount)) > threshold()) { (((double) currentCount / (double) secondaryCount)) > (1 / threshold())) { ReportManager.problem(this, dbre.getConnection(), sec.getName() + " only has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " has " + currentCount); result = false; } } else { ReportManager.problem(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " has none"); result = false; } } return result; } // run // ---------------------------------------------------------------------- protected Map<String, Integer> getCountsBySQL(DatabaseRegistryEntry dbre, String sql) { Map<String, Integer> result = new HashMap<String, Integer>(); try { Statement stmt = dbre.getConnection().createStatement(); logger.finest("Getting " + entityDescription() + " counts for " + dbre.getName()); ResultSet rs = stmt.executeQuery(sql); while (rs != null && rs.next()) { result.put(rs.getString(1), rs.getInt(2)); logger.finest(rs.getString(1) + " " + rs.getInt(2)); } stmt.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } // ---------------------------------------------------------------------- /** * Should return a map where the keys are the names of the entities being tested (e.g. biotypes) and the values are the counts of * each type. */ protected abstract Map getCounts(DatabaseRegistryEntry dbre); // ------------------------------------------------------------------------ /** * Should return a description of what's being tested. */ protected abstract String entityDescription(); // ------------------------------------------------------------------------ /** * Should return the fraction (0-1) of old/new below which a warning is generated. */ protected abstract double threshold(); // ------------------------------------------------------------------------ protected boolean testUpperThreshold() { return false; } } // ComparePreviousVersionBase
src/org/ensembl/healthcheck/testcase/generic/ComparePreviousVersionBase.java
/* * Copyright (C) 2003 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck.testcase.generic; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; /** * Base class to compare a certain set of things (e.g. biotypes, xrefs) from one database with the equivalent things in the previous * database. * * Extending classes should implement the description, threshold and getCounts() methods. See individual Javadocs for details. */ public abstract class ComparePreviousVersionBase extends SingleDatabaseTestCase { /** * Run the test. * * @param dbre * The database to use. * @return true if the test passed. * */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; if (System.getProperty("ignore.previous.checks") != null) { logger.finest("ignore.previous.checks is set in database.properties, skipping this test"); return true; } DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre); if (sec == null) { logger.warning("Can't get equivalent database for " + dbre.getName()); return true; } logger.finest("Equivalent database on secondary server is " + sec.getName()); Map currentCounts = getCounts(dbre); Map secondaryCounts = getCounts(sec); // compare each of the secondary (previous release, probably) with current Set externalDBs = secondaryCounts.keySet(); Iterator it = externalDBs.iterator(); String successText = ""; // show % tolerance here? double tolerance = (100 - ((threshold() / 1) * 100)); if (testUpperThreshold()) { successText = " - within tolerance +/-" + tolerance + "%"; } else { successText = " - greater or within tolerance"; } while (it.hasNext()) { String key = (String) it.next(); int secondaryCount = ((Integer) (secondaryCounts.get(key))).intValue(); if (secondaryCount == 0) { continue; } // check it exists at all if (currentCounts.containsKey(key)) { int currentCount = ((Integer) (currentCounts.get(key))).intValue(); if (((double) currentCount / (double) secondaryCount) < threshold()) { ReportManager.problem(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " only has " + currentCount); result = false; } else if (testUpperThreshold() && // ((1 -(double) secondaryCount / (double) currentCount)) > threshold()) { (((double) currentCount / (double) secondaryCount)) > (1 / threshold())) { ReportManager.problem(this, dbre.getConnection(), sec.getName() + " only has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " has " + currentCount); result = false; } else { ReportManager.correct(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " and " + dbre.getName() + " has " + currentCount + successText); } } else { ReportManager.problem(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " has none"); result = false; } } return result; } // run // ---------------------------------------------------------------------- protected Map<String, Integer> getCountsBySQL(DatabaseRegistryEntry dbre, String sql) { Map<String, Integer> result = new HashMap<String, Integer>(); try { Statement stmt = dbre.getConnection().createStatement(); logger.finest("Getting " + entityDescription() + " counts for " + dbre.getName()); ResultSet rs = stmt.executeQuery(sql); while (rs != null && rs.next()) { result.put(rs.getString(1), rs.getInt(2)); logger.finest(rs.getString(1) + " " + rs.getInt(2)); } stmt.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } // ---------------------------------------------------------------------- /** * Should return a map where the keys are the names of the entities being tested (e.g. biotypes) and the values are the counts of * each type. */ protected abstract Map getCounts(DatabaseRegistryEntry dbre); // ------------------------------------------------------------------------ /** * Should return a description of what's being tested. */ protected abstract String entityDescription(); // ------------------------------------------------------------------------ /** * Should return the fraction (0-1) of old/new below which a warning is generated. */ protected abstract double threshold(); // ------------------------------------------------------------------------ protected boolean testUpperThreshold() { return false; } } // ComparePreviousVersionBase
no need to report every single region which did not change in a relevant fashion
src/org/ensembl/healthcheck/testcase/generic/ComparePreviousVersionBase.java
no need to report every single region which did not change in a relevant fashion
<ide><path>rc/org/ensembl/healthcheck/testcase/generic/ComparePreviousVersionBase.java <ide> (((double) currentCount / (double) secondaryCount)) > (1 / threshold())) { <ide> ReportManager.problem(this, dbre.getConnection(), sec.getName() + " only has " + secondaryCount + " " + entityDescription() + " " + key + " but " + dbre.getName() + " has " + currentCount); <ide> result = false; <del> } else { <del> ReportManager.correct(this, dbre.getConnection(), sec.getName() + " has " + secondaryCount + " " + entityDescription() + " " + key + " and " + dbre.getName() + " has " + currentCount <del> + successText); <del> <ide> } <ide> <ide> } else {
Java
bsd-3-clause
811cb6706e4e316a01cf635c48393bf9ad529a59
0
edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon
/* Copyright (c) 2000-2012 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.igiglobal; import java.io.ByteArrayInputStream; import java.util.Iterator; import java.util.Stack; import java.util.regex.Pattern; import org.lockss.config.ConfigManager; import org.lockss.config.Configuration; import org.lockss.daemon.ConfigParamDescr; import org.lockss.extractor.MetadataTarget; import org.lockss.plugin.*; import org.lockss.plugin.simulated.SimulatedArchivalUnit; import org.lockss.plugin.simulated.SimulatedContentGenerator; import org.lockss.test.*; import org.lockss.util.*; /* * PDF Full Text: http://www.igi-global.com/viewtitle.aspx?titleid=55656 * HTML Abstract: http://www.igi-global.com/gateway/contentowned/article.aspx?titleid=55656 */ public class TestIgiGlobalArticleIteratorFactory extends ArticleIteratorTestCase { private SimulatedArchivalUnit sau; // Simulated AU to generate content private final String ARTICLE_FAIL_MSG = "Article files not created properly"; private final String PATTERN_FAIL_MSG = "Article file URL pattern changed or incorrect"; private final String PLUGIN_NAME = "org.lockss.plugin.igiglobal.IgiGlobalPlugin"; static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey(); static final String JOURNAL_ISSN_KEY = ConfigParamDescr.JOURNAL_ISSN.getKey(); static final String VOLUME_NUMBER_KEY = ConfigParamDescr.VOLUME_NUMBER.getKey(); private final String BASE_URL = "http://www.example.com/"; private final String VOLUME_NUMBER = "352"; private final String JOURNAL_ISSN = "nejm"; private final Configuration AU_CONFIG = ConfigurationUtil.fromArgs( BASE_URL_KEY, BASE_URL, VOLUME_NUMBER_KEY, VOLUME_NUMBER, JOURNAL_ISSN_KEY, JOURNAL_ISSN); private static final int DEFAULT_FILESIZE = 3000; public void setUp() throws Exception { super.setUp(); String tempDirPath = setUpDiskSpace(); au = createAu(); sau = PluginTestUtil.createAndStartSimAu(simAuConfig(tempDirPath)); } public void tearDown() throws Exception { sau.deleteContentTree(); super.tearDown(); } protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException { return PluginTestUtil.createAndStartAu(PLUGIN_NAME, AU_CONFIG); } Configuration simAuConfig(String rootPath) { Configuration conf = ConfigManager.newConfiguration(); conf.put("root", rootPath); conf.put(BASE_URL_KEY, BASE_URL); conf.put("depth", "1"); conf.put("branch", "2"); conf.put("numFiles", "6"); conf.put("fileTypes", "" + ( SimulatedContentGenerator.FILE_TYPE_HTML | SimulatedContentGenerator.FILE_TYPE_PDF)); conf.put("binFileSize", ""+DEFAULT_FILESIZE); return conf; } public void testRoots() throws Exception { SubTreeArticleIterator artIter = createSubTreeIter(); assertEquals("Article file root URL pattern changed or incorrect", ListUtil.list(BASE_URL + "gateway/article/", BASE_URL + "gateway/chapter/"), getRootUrls(artIter)); } public void testUrlsWithPrefixes() throws Exception { SubTreeArticleIterator artIter = createSubTreeIter(); Pattern pat = getPattern(artIter); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, "http://www.wrong.com/article/55656"); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/articles/55656"); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/article/full"); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "/gateway/article/55656"); assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/article/55656"); assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/article/1"); } /* * PDF Full Text: http://www.igi-global.com/gateway/contentowned/article.aspx?titleid=55656 * HTML Abstract: http://www.igi-global.com/viewtitle.aspx?titleid=55656 */ public void testCreateArticleFiles() throws Exception { PluginTestUtil.crawlSimAu(sau); String[] urls = { BASE_URL + "pdf.aspx", BASE_URL + "pdf.aspx?tid%3d20212%26ptid%3d464%26ctid%3d3%26t%3dArticle+Title", BASE_URL + "gateway/article/full-text-html/11111", BASE_URL + "gateway/article/full-text-pdf/2222", BASE_URL + "gateway/article/full-text-html/55656", BASE_URL + "gateway/article/full-text-pdf/55656", BASE_URL + "gateway/article/full-text-pdf/12345", BASE_URL + "gateway/article/11111", BASE_URL + "gateway/article/55656", BASE_URL + "gateway/article/54321", BASE_URL + "gateway/articles/full-text-pdf/12345", BASE_URL + "gateway/issue/54321", BASE_URL + "gateway/issue/12345", BASE_URL, BASE_URL + "gateway" }; Iterator<CachedUrlSetNode> cuIter = sau.getAuCachedUrlSet().contentHashIterator(); if(cuIter.hasNext()){ CachedUrlSetNode cusn = cuIter.next(); CachedUrl cuPdf = null; CachedUrl cuHtml = null; UrlCacher uc; while(cuIter.hasNext() && (cuPdf == null || cuHtml == null)) { if(cusn.getType() == CachedUrlSetNode.TYPE_CACHED_URL && cusn.hasContent()) { CachedUrl cu = (CachedUrl)cusn; if (cuPdf == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_PDF)) { cuPdf = cu; } else if (cuHtml == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_HTML)) { cuHtml = cu; } } cusn = cuIter.next(); } byte[] b = new byte [512]; cuHtml.getUnfilteredInputStream().read(b, 0, 350); String landingPage = new String(b); landingPage = landingPage.replace("</BODY>", "xxxx <iframe random=\"stuff\" " + "src=\"/pdf.aspx?tid%3d20212%26ptid%3d464%26ctid%3d3%26t%3dArticle+Title\">" + "xxxx\n</BODY>"); for (String url : urls) { uc = au.makeUrlCacher(url); if (url.contains("full-text-html")) { uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); } else if (url.contains("articles/full-text-pdf")) { uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); url = url.replace("full-text-pdf", "pdf"); uc = au.makeUrlCacher(url); uc.storeContent(cuPdf.getUnfilteredInputStream(), cuPdf.getProperties()); } else if (url.contains("full-text-pdf")) { uc.storeContent(new ByteArrayInputStream(landingPage.getBytes()), cuHtml.getProperties()); } else if (url.contains("/pdf.aspx")) { uc.storeContent(cuPdf.getUnfilteredInputStream(), cuPdf.getProperties()); } else if (url.matches(".*gateway/article/[0-9]+$")) { uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); } } } Stack<String[]> expStack = new Stack<String[]>(); String [] af1 = {BASE_URL + "gateway/article/full-text-html/11111", null, null, BASE_URL + "gateway/article/11111"}; String [] af2 = {null, null, null, BASE_URL + "gateway/article/54321"}; String [] af3 = {BASE_URL + "gateway/article/full-text-html/55656", BASE_URL + "gateway/article/full-text-pdf/55656", BASE_URL + "pdf.aspx?tid%3d20212%26ptid%3d464%26ctid%3d3%26t%3dArticle+Title", BASE_URL + "gateway/article/55656"}; expStack.push(af3); expStack.push(af2); expStack.push(af1); SubTreeArticleIterator artIter = null; Iterator<ArticleFiles> iter = au.getArticleIterator(MetadataTarget.Article()); assertNotNull("ArticleIterator is null", iter); assert(iter instanceof SubTreeArticleIterator); artIter = (SubTreeArticleIterator)iter; // artIter = createSubTreeIter(); while (artIter.hasNext()) { ArticleFiles af = artIter.next(); String[] act = { af.getFullTextUrl(), af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE), af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF), af.getRoleUrl(ArticleFiles.ROLE_ABSTRACT) }; String[] exp = expStack.pop(); if(act.length == exp.length){ for(int i = 0;i< act.length; i++){ assertEquals(ARTICLE_FAIL_MSG + " Expected: " + exp[i] + " Actual: " + act[i], exp[i],act[i]); } } else fail(ARTICLE_FAIL_MSG + " length of expected and actual ArticleFiles content not the same:" + exp.length + "!=" + act.length); } } }
plugins/test/src/org/lockss/plugin/igiglobal/TestIgiGlobalArticleIteratorFactory.java
/* Copyright (c) 2000-2012 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.igiglobal; import java.util.Iterator; import java.util.Stack; import java.util.regex.Pattern; import org.lockss.config.ConfigManager; import org.lockss.config.Configuration; import org.lockss.daemon.ConfigParamDescr; import org.lockss.plugin.*; import org.lockss.plugin.simulated.SimulatedArchivalUnit; import org.lockss.plugin.simulated.SimulatedContentGenerator; import org.lockss.test.*; import org.lockss.util.*; /* * PDF Full Text: http://www.igi-global.com/viewtitle.aspx?titleid=55656 * HTML Abstract: http://www.igi-global.com/gateway/contentowned/article.aspx?titleid=55656 */ public class TestIgiGlobalArticleIteratorFactory extends ArticleIteratorTestCase { private SimulatedArchivalUnit sau; // Simulated AU to generate content private final String ARTICLE_FAIL_MSG = "Article files not created properly"; private final String PATTERN_FAIL_MSG = "Article file URL pattern changed or incorrect"; private final String PLUGIN_NAME = "org.lockss.plugin.igiglobal.IgiGlobalPlugin"; static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey(); static final String JOURNAL_ISSN_KEY = ConfigParamDescr.JOURNAL_ISSN.getKey(); static final String VOLUME_NUMBER_KEY = ConfigParamDescr.VOLUME_NUMBER.getKey(); private final String BASE_URL = "http://www.example.com/"; private final String VOLUME_NUMBER = "352"; private final String JOURNAL_ISSN = "nejm"; private final Configuration AU_CONFIG = ConfigurationUtil.fromArgs( BASE_URL_KEY, BASE_URL, VOLUME_NUMBER_KEY, VOLUME_NUMBER, JOURNAL_ISSN_KEY, JOURNAL_ISSN); private static final int DEFAULT_FILESIZE = 3000; public void setUp() throws Exception { super.setUp(); String tempDirPath = setUpDiskSpace(); au = createAu(); sau = PluginTestUtil.createAndStartSimAu(simAuConfig(tempDirPath)); } public void tearDown() throws Exception { sau.deleteContentTree(); super.tearDown(); } protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException { return PluginTestUtil.createAndStartAu(PLUGIN_NAME, AU_CONFIG); } Configuration simAuConfig(String rootPath) { Configuration conf = ConfigManager.newConfiguration(); conf.put("root", rootPath); conf.put(BASE_URL_KEY, BASE_URL); conf.put("depth", "1"); conf.put("branch", "2"); conf.put("numFiles", "6"); conf.put("fileTypes", "" + ( SimulatedContentGenerator.FILE_TYPE_HTML | SimulatedContentGenerator.FILE_TYPE_PDF)); conf.put("binFileSize", ""+DEFAULT_FILESIZE); return conf; } public void testRoots() throws Exception { SubTreeArticleIterator artIter = createSubTreeIter(); assertEquals("Article file root URL pattern changed or incorrect", ListUtil.list(BASE_URL + "gateway/article/", BASE_URL + "gateway/chapter/"), getRootUrls(artIter)); } public void testUrlsWithPrefixes() throws Exception { SubTreeArticleIterator artIter = createSubTreeIter(); Pattern pat = getPattern(artIter); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, "http://www.wrong.com/article/55656"); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/articles/55656"); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/article/full"); assertNotMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "/gateway/article/55656"); assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/article/55656"); assertMatchesRE(PATTERN_FAIL_MSG, pat, BASE_URL + "gateway/article/1"); } /* * PDF Full Text: http://www.igi-global.com/gateway/contentowned/article.aspx?titleid=55656 * HTML Abstract: http://www.igi-global.com/viewtitle.aspx?titleid=55656 */ public void testCreateArticleFiles() throws Exception { PluginTestUtil.crawlSimAu(sau); String[] urls = { BASE_URL + "gateway/article/full-text-html/11111", BASE_URL + "gateway/article/full-text-pdf/2222", BASE_URL + "gateway/article/full-text-html/55656", BASE_URL + "gateway/article/full-text-pdf/55656", BASE_URL + "gateway/article/full-text-pdf/12345", BASE_URL + "gateway/article/11111", BASE_URL + "gateway/article/55656", BASE_URL + "gateway/article/54321", BASE_URL + "gateway/articles/full-text-pdf/12345", BASE_URL + "gateway/issue/54321", BASE_URL + "gateway/issue/12345", BASE_URL, BASE_URL + "gateway" }; Iterator<CachedUrlSetNode> cuIter = sau.getAuCachedUrlSet().contentHashIterator(); if(cuIter.hasNext()){ CachedUrlSetNode cusn = cuIter.next(); CachedUrl cuPdf = null; CachedUrl cuHtml = null; UrlCacher uc; while(cuIter.hasNext() && (cuPdf == null || cuHtml == null)) { if(cusn.getType() == CachedUrlSetNode.TYPE_CACHED_URL && cusn.hasContent()) { CachedUrl cu = (CachedUrl)cusn; if (cuPdf == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_PDF)) { cuPdf = cu; } else if (cuHtml == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_HTML)) { cuHtml = cu; } } cusn = cuIter.next(); } byte[] b = new byte [1024]; cuHtml.getUnfilteredInputStream().read(b, 0, 1024); String landingPage = new String(b); landingPage = landingPage.replace("</BODY>", "xxxx <iframe random=\"stuff\" " + "src=\"/pdf.aspx?tid%3d20212%26ptid%3d464%26ctid%3d3%26t%3dArticle+Title\">" + "xxxx\n</BODY>"); for (String url : urls) { uc = au.makeUrlCacher(url); if (url.contains("full-text-html")) { uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); } else if (url.contains("full-text-pdf")) { uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); url = url.replace("full-text-pdf", "pdf"); uc = au.makeUrlCacher(url); uc.storeContent(cuPdf.getUnfilteredInputStream(), cuPdf.getProperties()); } } } Stack<String[]> expStack = new Stack<String[]>(); String [] af1 = {BASE_URL + "gateway/article/full-text-html/11111", null, BASE_URL + "gateway/article/11111"}; String [] af2 = {null, null, BASE_URL + "gateway/article/54321"}; String [] af3 = {BASE_URL + "gateway/article/full-text-html/55656", BASE_URL + "gateway/article/full-text-pdf/55656", BASE_URL + "gateway/article/55656"}; expStack.push(af3); expStack.push(af2); expStack.push(af1); for ( SubTreeArticleIterator artIter = createSubTreeIter(); artIter.hasNext(); ) { ArticleFiles af = artIter.next(); String[] act = { af.getFullTextUrl(), af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE), af.getRoleUrl(ArticleFiles.ROLE_ABSTRACT) }; String[] exp = expStack.pop(); if(act.length == exp.length){ for(int i = 0;i< act.length; i++){ assertEquals(ARTICLE_FAIL_MSG + " Expected: " + exp[i] + " Actual: " + act[i], exp[i],act[i]); } } else fail(ARTICLE_FAIL_MSG + " length of expected and actual ArticleFiles content not the same:" + exp.length + "!=" + act.length); } } }
Add files to test, insert text to scrape, use iterator for articles to test pdf filename scraping code git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@30188 4f837ed2-42f5-46e7-a7a5-fa17313484d4
plugins/test/src/org/lockss/plugin/igiglobal/TestIgiGlobalArticleIteratorFactory.java
Add files to test, insert text to scrape, use iterator for articles to test pdf filename scraping code
<ide><path>lugins/test/src/org/lockss/plugin/igiglobal/TestIgiGlobalArticleIteratorFactory.java <ide> <ide> package org.lockss.plugin.igiglobal; <ide> <add>import java.io.ByteArrayInputStream; <ide> import java.util.Iterator; <ide> import java.util.Stack; <ide> import java.util.regex.Pattern; <ide> import org.lockss.config.ConfigManager; <ide> import org.lockss.config.Configuration; <ide> import org.lockss.daemon.ConfigParamDescr; <add>import org.lockss.extractor.MetadataTarget; <ide> import org.lockss.plugin.*; <ide> import org.lockss.plugin.simulated.SimulatedArchivalUnit; <ide> import org.lockss.plugin.simulated.SimulatedContentGenerator; <ide> public void testCreateArticleFiles() throws Exception { <ide> PluginTestUtil.crawlSimAu(sau); <ide> String[] urls = { <add> BASE_URL + "pdf.aspx", <add> BASE_URL + "pdf.aspx?tid%3d20212%26ptid%3d464%26ctid%3d3%26t%3dArticle+Title", <ide> BASE_URL + "gateway/article/full-text-html/11111", <ide> BASE_URL + "gateway/article/full-text-pdf/2222", <ide> BASE_URL + "gateway/article/full-text-html/55656", <ide> } <ide> cusn = cuIter.next(); <ide> } <del> byte[] b = new byte [1024]; <del> cuHtml.getUnfilteredInputStream().read(b, 0, 1024); <add> byte[] b = new byte [512]; <add> cuHtml.getUnfilteredInputStream().read(b, 0, 350); <ide> String landingPage = new String(b); <ide> landingPage = landingPage.replace("</BODY>", "xxxx <iframe random=\"stuff\" " + <ide> "src=\"/pdf.aspx?tid%3d20212%26ptid%3d464%26ctid%3d3%26t%3dArticle+Title\">" + <ide> if (url.contains("full-text-html")) { <ide> uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); <ide> } <del> else if (url.contains("full-text-pdf")) { <add> else if (url.contains("articles/full-text-pdf")) { <ide> uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); <ide> url = url.replace("full-text-pdf", "pdf"); <ide> uc = au.makeUrlCacher(url); <ide> uc.storeContent(cuPdf.getUnfilteredInputStream(), cuPdf.getProperties()); <ide> } <add> else if (url.contains("full-text-pdf")) { <add> uc.storeContent(new ByteArrayInputStream(landingPage.getBytes()), <add> cuHtml.getProperties()); <add> } <add> else if (url.contains("/pdf.aspx")) { <add> uc.storeContent(cuPdf.getUnfilteredInputStream(), cuPdf.getProperties()); <add> } <add> else if (url.matches(".*gateway/article/[0-9]+$")) { <add> uc.storeContent(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties()); <add> } <ide> } <ide> } <ide> <ide> Stack<String[]> expStack = new Stack<String[]>(); <ide> String [] af1 = {BASE_URL + "gateway/article/full-text-html/11111", <ide> null, <add> null, <ide> BASE_URL + "gateway/article/11111"}; <ide> <ide> String [] af2 = {null, <add> null, <ide> null, <ide> BASE_URL + "gateway/article/54321"}; <ide> <ide> String [] af3 = {BASE_URL + "gateway/article/full-text-html/55656", <ide> BASE_URL + "gateway/article/full-text-pdf/55656", <add> BASE_URL + "pdf.aspx?tid%3d20212%26ptid%3d464%26ctid%3d3%26t%3dArticle+Title", <ide> BASE_URL + "gateway/article/55656"}; <ide> <ide> expStack.push(af3); <ide> expStack.push(af2); <ide> expStack.push(af1); <ide> <del> for ( SubTreeArticleIterator artIter = createSubTreeIter(); artIter.hasNext(); ) <add> SubTreeArticleIterator artIter = null; <add> Iterator<ArticleFiles> iter = au.getArticleIterator(MetadataTarget.Article()); <add> assertNotNull("ArticleIterator is null", iter); <add> assert(iter instanceof SubTreeArticleIterator); <add> artIter = (SubTreeArticleIterator)iter; <add> // artIter = createSubTreeIter(); <add> <add> while (artIter.hasNext()) <ide> { <ide> ArticleFiles af = artIter.next(); <ide> String[] act = { <ide> af.getFullTextUrl(), <ide> af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE), <add> af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF), <ide> af.getRoleUrl(ArticleFiles.ROLE_ABSTRACT) <ide> }; <ide> String[] exp = expStack.pop();
Java
agpl-3.0
3eff78ff3879ed231bf81b8d05950d7b999802aa
0
cinquin/mutinack,cinquin/mutinack,cinquin/mutinack,cinquin/mutinack,cinquin/mutinack
/** * Mutinack mutation detection program. * Copyright (C) 2014-2016 Olivier Cinquin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.org.cinquin.mutinack; import static contrib.uk.org.lidalia.slf4jext.Level.TRACE; import static uk.org.cinquin.mutinack.MutationType.INSERTION; import static uk.org.cinquin.mutinack.MutationType.SUBSTITUTION; import static uk.org.cinquin.mutinack.MutationType.WILDTYPE; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.DISAGREEMENT; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.MISSING_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.N_READS_PER_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.QUALITY_AT_POSITION; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.FRACTION_WRONG_PAIRS_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_DPLX_Q_IGNORING_DISAG; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_Q_FOR_ALL_DUPLEXES; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_CANDIDATE_PHRED; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_PHRED_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.NO_DUPLEXES; import static uk.org.cinquin.mutinack.misc_util.DebugLogControl.NONTRIVIAL_ASSERTIONS; import static uk.org.cinquin.mutinack.misc_util.Util.basesEqual; import static uk.org.cinquin.mutinack.qualities.Quality.ATROCIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.DUBIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.GOOD; import static uk.org.cinquin.mutinack.qualities.Quality.MINIMUM; import static uk.org.cinquin.mutinack.qualities.Quality.POOR; import static uk.org.cinquin.mutinack.qualities.Quality.max; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.eclipse.collections.api.RichIterable; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.list.primitive.MutableFloatList; import org.eclipse.collections.api.multimap.set.MutableSetMultimap; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.set.MutableSet; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.list.mutable.FastList; import org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import contrib.net.sf.picard.reference.ReferenceSequence; import contrib.net.sf.samtools.CigarOperator; import contrib.net.sf.samtools.SAMRecord; import contrib.net.sf.samtools.SamPairUtil; import contrib.net.sf.samtools.SamPairUtil.PairOrientation; import contrib.net.sf.samtools.util.StringUtil; import contrib.uk.org.lidalia.slf4jext.Logger; import contrib.uk.org.lidalia.slf4jext.LoggerFactory; import gnu.trove.list.array.TByteArrayList; import gnu.trove.map.TByteObjectMap; import gnu.trove.map.hash.TByteObjectHashMap; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.set.hash.TCustomHashSet; import gnu.trove.set.hash.THashSet; import uk.org.cinquin.mutinack.candidate_sequences.CandidateBuilder; import uk.org.cinquin.mutinack.candidate_sequences.CandidateCounter; import uk.org.cinquin.mutinack.candidate_sequences.CandidateDeletion; import uk.org.cinquin.mutinack.candidate_sequences.CandidateSequence; import uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay; import uk.org.cinquin.mutinack.candidate_sequences.ExtendedAlignmentBlock; import uk.org.cinquin.mutinack.candidate_sequences.PositionAssay; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.ComparablePair; import uk.org.cinquin.mutinack.misc_util.DebugLogControl; import uk.org.cinquin.mutinack.misc_util.Handle; import uk.org.cinquin.mutinack.misc_util.Pair; import uk.org.cinquin.mutinack.misc_util.SettableDouble; import uk.org.cinquin.mutinack.misc_util.SettableInteger; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.collections.HashingStrategies; import uk.org.cinquin.mutinack.misc_util.collections.InterningSet; import uk.org.cinquin.mutinack.misc_util.collections.duplex_keeper.DuplexArrayListKeeper; import uk.org.cinquin.mutinack.misc_util.collections.duplex_keeper.DuplexHashMapKeeper; import uk.org.cinquin.mutinack.misc_util.collections.duplex_keeper.DuplexKeeper; import uk.org.cinquin.mutinack.misc_util.exceptions.AssertionFailedException; import uk.org.cinquin.mutinack.output.LocationExaminationResults; import uk.org.cinquin.mutinack.qualities.DetailedPositionQualities; import uk.org.cinquin.mutinack.qualities.DetailedQualities; import uk.org.cinquin.mutinack.qualities.Quality; import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter; import uk.org.cinquin.mutinack.statistics.Histogram; import uk.org.cinquin.mutinack.statistics.MultiCounter; public final class SubAnalyzer { private static final Logger logger = LoggerFactory.getLogger(SubAnalyzer.class); //For assertion and debugging purposes public boolean incrementednPosDuplexQualityQ2OthersQ1Q2, processed, c1, c2, c3, c4; public final @NonNull Mutinack analyzer; @NonNull Parameters param; @NonNull public AnalysisStats stats;//Will in fact be null until set in SubAnalyzerPhaser but that's OK final @NonNull SettableInteger lastProcessablePosition = new SettableInteger(-1); final @NonNull THashMap<SequenceLocation, THashSet<CandidateSequence>> candidateSequences = new THashMap<>(1_000); int truncateProcessingAt = Integer.MAX_VALUE; int startProcessingAt = 0; MutableList<@NonNull Duplex> analyzedDuplexes; float[] averageClipping; int averageClippingOffset = Integer.MAX_VALUE; final @NonNull THashMap<String, @NonNull ExtendedSAMRecord> extSAMCache = new THashMap<>(10_000, 0.5f); private final AtomicInteger threadCount = new AtomicInteger(); @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") @NonNull Map<@NonNull ExtendedSAMRecord, @NonNull SAMRecord> readsToWrite = new THashMap<>(); private final Random random; public static final @NonNull Set<@NonNull DuplexAssay> ASSAYS_TO_IGNORE_FOR_DISAGREEMENT_QUALITY = Collections.unmodifiableSet(EnumSet.of(DISAGREEMENT)), ASSAYS_TO_IGNORE_FOR_DUPLEX_NSTRANDS = Collections.unmodifiableSet(EnumSet.of(N_READS_PER_STRAND, MISSING_STRAND, DuplexAssay.TOTAL_N_READS_Q2)); static final @NonNull TByteObjectMap<@NonNull String> byteMap; static { byteMap = new TByteObjectHashMap<>(); Assert.isNull(byteMap.put((byte) 'A', "A")); Assert.isNull(byteMap.put((byte) 'a', "A")); Assert.isNull(byteMap.put((byte) 'T', "T")); Assert.isNull(byteMap.put((byte) 't', "T")); Assert.isNull(byteMap.put((byte) 'G', "G")); Assert.isNull(byteMap.put((byte) 'g', "G")); Assert.isNull(byteMap.put((byte) 'C', "C")); Assert.isNull(byteMap.put((byte) 'c', "C")); Assert.isNull(byteMap.put((byte) 'N', "N")); Assert.isNull(byteMap.put((byte) 'n', "N")); Assert.isNull(byteMap.put((byte) 'W', "W")); Assert.isNull(byteMap.put((byte) 'w', "W")); Assert.isNull(byteMap.put((byte) 'S', "S")); Assert.isNull(byteMap.put((byte) 's', "S")); Assert.isNull(byteMap.put((byte) 'Y', "Y")); Assert.isNull(byteMap.put((byte) 'y', "Y")); Assert.isNull(byteMap.put((byte) 'R', "R")); Assert.isNull(byteMap.put((byte) 'r', "R")); Assert.isNull(byteMap.put((byte) 'B', "B")); Assert.isNull(byteMap.put((byte) 'b', "B")); Assert.isNull(byteMap.put((byte) 'D', "D")); Assert.isNull(byteMap.put((byte) 'd', "D")); Assert.isNull(byteMap.put((byte) 'H', "H")); Assert.isNull(byteMap.put((byte) 'h', "H")); Assert.isNull(byteMap.put((byte) 'K', "K")); Assert.isNull(byteMap.put((byte) 'k', "K")); Assert.isNull(byteMap.put((byte) 'M', "M")); Assert.isNull(byteMap.put((byte) 'm', "M")); Assert.isNull(byteMap.put((byte) 'V', "V")); Assert.isNull(byteMap.put((byte) 'v', "V")); } static final @NonNull TByteObjectMap<byte @NonNull[]> byteArrayMap; static { byteArrayMap = new TByteObjectHashMap<>(); Assert.isNull(byteArrayMap.put((byte) 'A', new byte[] {'A'})); Assert.isNull(byteArrayMap.put((byte) 'a', new byte[] {'a'})); Assert.isNull(byteArrayMap.put((byte) 'T', new byte[] {'T'})); Assert.isNull(byteArrayMap.put((byte) 't', new byte[] {'t'})); Assert.isNull(byteArrayMap.put((byte) 'G', new byte[] {'G'})); Assert.isNull(byteArrayMap.put((byte) 'g', new byte[] {'g'})); Assert.isNull(byteArrayMap.put((byte) 'C', new byte[] {'C'})); Assert.isNull(byteArrayMap.put((byte) 'c', new byte[] {'c'})); Assert.isNull(byteArrayMap.put((byte) 'N', new byte[] {'N'})); Assert.isNull(byteArrayMap.put((byte) 'n', new byte[] {'n'})); Assert.isNull(byteArrayMap.put((byte) 'W', new byte[] {'W'})); Assert.isNull(byteArrayMap.put((byte) 'w', new byte[] {'w'})); Assert.isNull(byteArrayMap.put((byte) 'S', new byte[] {'S'})); Assert.isNull(byteArrayMap.put((byte) 's', new byte[] {'s'})); Assert.isNull(byteArrayMap.put((byte) 'Y', new byte[] {'Y'})); Assert.isNull(byteArrayMap.put((byte) 'y', new byte[] {'y'})); Assert.isNull(byteArrayMap.put((byte) 'R', new byte[] {'R'})); Assert.isNull(byteArrayMap.put((byte) 'r', new byte[] {'r'})); Assert.isNull(byteArrayMap.put((byte) 'B', new byte[] {'B'})); Assert.isNull(byteArrayMap.put((byte) 'D', new byte[] {'D'})); Assert.isNull(byteArrayMap.put((byte) 'H', new byte[] {'H'})); Assert.isNull(byteArrayMap.put((byte) 'K', new byte[] {'K'})); Assert.isNull(byteArrayMap.put((byte) 'M', new byte[] {'M'})); Assert.isNull(byteArrayMap.put((byte) 'V', new byte[] {'V'})); Assert.isNull(byteArrayMap.put((byte) 'b', new byte[] {'b'})); Assert.isNull(byteArrayMap.put((byte) 'd', new byte[] {'d'})); Assert.isNull(byteArrayMap.put((byte) 'h', new byte[] {'h'})); Assert.isNull(byteArrayMap.put((byte) 'k', new byte[] {'k'})); Assert.isNull(byteArrayMap.put((byte) 'm', new byte[] {'m'})); Assert.isNull(byteArrayMap.put((byte) 'v', new byte[] {'v'})); } private volatile boolean writing = false; synchronized void queueOutputRead(@NonNull ExtendedSAMRecord e, @NonNull SAMRecord r, boolean mayAlreadyBeQueued) { Assert.isFalse(writing); final SAMRecord previous; if ((previous = readsToWrite.put(e, r)) != null && !mayAlreadyBeQueued) { throw new IllegalStateException("Read " + e.getFullName() + " already queued for writing; new: " + r.toString() + "; previous: " + previous.toString()); } } void writeOutputReads() { Assert.isFalse(writing); writing = true; try { synchronized(analyzer.outputAlignmentWriter) { for (SAMRecord samRecord: readsToWrite.values()) { Objects.requireNonNull(analyzer.outputAlignmentWriter).addAlignment(samRecord); } } readsToWrite.clear(); } finally { writing = false; } } @SuppressWarnings("null")//Stats not initialized straight away SubAnalyzer(@NonNull Mutinack analyzer) { this.analyzer = analyzer; this.param = analyzer.param; useHashMap = param.alignmentPositionMismatchAllowed == 0; random = new Random(param.randomSeed); } private boolean meetsQ2Thresholds(@NonNull ExtendedSAMRecord extendedRec) { return !extendedRec.formsWrongPair() && extendedRec.getnClipped() <= param.maxAverageBasesClipped && extendedRec.getMappingQuality() >= param.minMappingQualityQ2 && Math.abs(extendedRec.getInsertSize()) <= param.maxInsertSize; } /** * Make sure that concurring reads get associated with a unique candidate. * We should *not* insert candidates directly into candidateSequences. * Get interning as a small, beneficial side effect. * @param candidate * @param location * @return */ private @NonNull CandidateSequence insertCandidateAtPosition(@NonNull CandidateSequence candidate, @NonNull SequenceLocation location) { //No need for synchronization since we should not be //concurrently inserting two candidates at the same position THashSet<CandidateSequence> candidates = candidateSequences.computeIfAbsent(location, k -> new THashSet<>(2, 0.2f)); CandidateSequence candidateMapValue = candidates.get(candidate); if (candidateMapValue == null) { boolean added = candidates.add(candidate); Assert.isTrue(added); } else { candidateMapValue.mergeWith(candidate); candidate = candidateMapValue; } return candidate; } /** * Load all reads currently referred to by candidate sequences and group them into DuplexReads * @param toPosition * @param fromPosition */ void load(int fromPosition, int toPosition) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { if (toPosition < fromPosition) { throw new IllegalArgumentException("Going from " + fromPosition + " to " + toPosition); } final MutableList<@NonNull Duplex> resultDuplexes = new FastList<>(3_000); loadAll(fromPosition, toPosition, resultDuplexes); analyzedDuplexes = resultDuplexes; } finally { if (NONTRIVIAL_ASSERTIONS) { threadCount.decrementAndGet(); } } } void checkAllDone() { if (!candidateSequences.isEmpty()) { final SettableInteger nLeftBehind = new SettableInteger(-1); candidateSequences.forEach((k,v) -> { Assert.isTrue(v.isEmpty() || (v.iterator().next().getLocation().equals(k)), "Mismatched locations"); String s = v.stream(). filter(c -> c.getLocation().position > truncateProcessingAt + param.maxInsertSize && c.getLocation().position < startProcessingAt - param.maxInsertSize). flatMap(v0 -> v0.getNonMutableConcurringReads().keySet().stream()). map(read -> { if (nLeftBehind.incrementAndGet() == 0) { logger.error("Sequences left behind before " + truncateProcessingAt); } return Integer.toString(read.getAlignmentStart()) + '-' + Integer.toString(read.getAlignmentEnd()); }) .collect(Collectors.joining("; ")); if (!s.equals("")) { logger.error(s); } }); Assert.isFalse(nLeftBehind.get() > 0); } } private final boolean useHashMap; private @NonNull DuplexKeeper getDuplexKeeper(boolean fallBackOnIntervalTree) { final @NonNull DuplexKeeper result; if (MutinackGroup.forceKeeperType != null) { switch(MutinackGroup.forceKeeperType) { case "DuplexHashMapKeeper": if (useHashMap) { result = new DuplexHashMapKeeper(); } else { result = new DuplexArrayListKeeper(5_000); } break; //case "DuplexITKeeper": // result = new DuplexITKeeper(); // break; case "DuplexArrayListKeeper": result = new DuplexArrayListKeeper(5_000); break; default: throw new AssertionFailedException(); } } else { if (useHashMap) { result = new DuplexHashMapKeeper(); } else /*if (fallBackOnIntervalTree) { result = new DuplexITKeeper(); } else */{ result = new DuplexArrayListKeeper(5_000); } } return result; } /** * Group reads into duplexes. * @param toPosition * @param fromPosition * @param finalResult */ private void loadAll( final int fromPosition, final int toPosition, final @NonNull List<Duplex> finalResult) { /** * Use a custom hash map type to keep track of duplexes when * alignmentPositionMismatchAllowed is 0. * This provides by far the highest performance. * When alignmentPositionMismatchAllowed is greater than 0, use * either an interval tree or a plain list. The use of an interval * tree instead of a plain list provides a speed benefit only when * there is large number of local duplexes, so switch dynamically * based on that number. The threshold was optimized empirically * and at a gross level. */ final boolean fallBackOnIntervalTree = extSAMCache.size() > 5_000; @NonNull DuplexKeeper duplexKeeper = getDuplexKeeper(fallBackOnIntervalTree); InterningSet<SequenceLocation> sequenceLocationCache = new InterningSet<>(500); final AlignmentExtremetiesDistance ed = new AlignmentExtremetiesDistance( analyzer.groupSettings, param); final SettableInteger nReadsExcludedFromDuplexes = new SettableInteger(0); final TObjectProcedure<@NonNull ExtendedSAMRecord> callLoadRead = rExtended -> { loadRead(rExtended, duplexKeeper, ed, sequenceLocationCache, nReadsExcludedFromDuplexes); return true; }; if (param.jiggle) { List<@NonNull ExtendedSAMRecord> reorderedReads = new ArrayList<>(extSAMCache.values()); Collections.shuffle(reorderedReads, random); reorderedReads.forEach(callLoadRead::execute); } else { extSAMCache.forEachValue(callLoadRead); } sequenceLocationCache.clear();//Not strictly necessary, but might as well release the //memory now if (param.randomizeStrand) { duplexKeeper.forEach(dr -> dr.randomizeStrands(random)); } duplexKeeper.forEach(Duplex::computeGlobalProperties); Pair<Duplex, Duplex> pair; if (param.enableCostlyAssertions && (pair = Duplex.checkNoEqualDuplexes(duplexKeeper)) != null) { throw new AssertionFailedException("Equal duplexes: " + pair.fst + " and " + pair.snd); } if (param.enableCostlyAssertions) { Assert.isTrue(checkReadsOccurOnceInDuplexes(extSAMCache.values(), duplexKeeper, nReadsExcludedFromDuplexes.get())); } //Group duplexes that have alignment positions that differ by at most //param.alignmentPositionMismatchAllowed //and left/right consensus that differ by at most //param.nVariableBarcodeMismatchesAllowed final DuplexKeeper cleanedUpDuplexes; if (param.nVariableBarcodeMismatchesAllowed > 0 /*&& duplexKeeper.size() < analyzer.maxNDuplexes*/) { cleanedUpDuplexes = Duplex.groupDuplexes( duplexKeeper, duplex -> duplex.computeConsensus(false, param.variableBarcodeLength), () -> getDuplexKeeper(fallBackOnIntervalTree), param, stats, 0); } else { cleanedUpDuplexes = duplexKeeper; cleanedUpDuplexes.forEach(Duplex::computeGlobalProperties); } if (param.nVariableBarcodeMismatchesAllowed == 0) { cleanedUpDuplexes.forEach(d -> d.computeConsensus(true, param.variableBarcodeLength)); } if (param.variableBarcodeLength == 0) { //Group duplexes by alignment start (or equivalent) TIntObjectHashMap<List<Duplex>> duplexPositions = new TIntObjectHashMap<> (1_000, 0.5f, -999); cleanedUpDuplexes.forEach(dr -> { List<Duplex> list = duplexPositions.computeIfAbsent(dr.leftAlignmentStart.position, (Supplier<List<Duplex>>) ArrayList::new); list.add(dr); }); final double @NonNull[] insertSizeProb = Objects.requireNonNull(analyzer.insertSizeProbSmooth); duplexPositions.forEachValue(list -> { for (Duplex dr: list) { double sizeP = insertSizeProb[ Math.min(insertSizeProb.length - 1, dr.maxInsertSize)]; Assert.isTrue(Double.isNaN(sizeP) || sizeP >= 0, () -> "Insert size problem: " + Arrays.toString(insertSizeProb)); dr.probAtLeastOneCollision = 1 - Math.pow(1 - sizeP, list.size()); } return true; }); } cleanedUpDuplexes.forEach(duplexRead -> duplexRead.analyzeForStats(param, stats)); cleanedUpDuplexes.forEach(finalResult::add); averageClippingOffset = fromPosition; final int arrayLength = toPosition - fromPosition + 1; averageClipping = new float[arrayLength]; int[] duplexNumber = new int[arrayLength]; cleanedUpDuplexes.forEach(duplexRead -> { int start = duplexRead.getUnclippedAlignmentStart() - fromPosition; int stop = duplexRead.getUnclippedAlignmentEnd() - fromPosition; start = Math.min(Math.max(0, start), toPosition - fromPosition); stop = Math.min(Math.max(0, stop), toPosition - fromPosition); for (int i = start; i <= stop; i++) { averageClipping[i] += duplexRead.averageNClipped; duplexNumber[i]++; } }); insertDuplexGroupSizeStats(cleanedUpDuplexes, 0, stats.duplexLocalGroupSize); insertDuplexGroupSizeStats(cleanedUpDuplexes, 15, stats.duplexLocalShiftedGroupSize); if (param.computeDuplexDistances && cleanedUpDuplexes.size() < analyzer.maxNDuplexes) { cleanedUpDuplexes.forEach(d1 -> cleanedUpDuplexes.forEach(d2 -> stats.duplexDistance.insert(d1.euclideanDistanceTo(d2)))); } for (int i = 0; i < averageClipping.length; i++) { int n = duplexNumber[i]; if (n == 0) { Assert.isTrue(averageClipping[i] == 0); } else { averageClipping[i] /= n; } } }//End loadAll private static void insertDuplexGroupSizeStats(DuplexKeeper keeper, int offset, Histogram stats) { keeper.forEach(duplexRead -> { duplexRead.assignedToLocalGroup = duplexRead.leftAlignmentStart.position == ExtendedSAMRecord.NO_MATE_POSITION || duplexRead.rightAlignmentEnd.position == ExtendedSAMRecord.NO_MATE_POSITION;//Ignore duplexes from reads that //have a missing mate }); keeper.forEach(duplexRead -> { if (!duplexRead.assignedToLocalGroup) { int groupSize = countDuplexesInWindow(duplexRead, keeper, offset, 5); stats.insert(groupSize); duplexRead.assignedToLocalGroup = true; } }); } private static int countDuplexesInWindow(Duplex d, DuplexKeeper dk, int offset, int windowWidth) { SettableInteger result = new SettableInteger(0); dk.getOverlappingWithSlop(d, offset, windowWidth).forEach(od -> { if (od.assignedToLocalGroup) { return; } int distance1 = od.rightAlignmentEnd.position - (d.rightAlignmentEnd.position + offset); if (Math.abs(distance1) <= windowWidth) { Assert.isTrue(Math.abs(distance1) <= windowWidth + Math.abs(offset)); int distance2 = od.leftAlignmentStart.position - (d.leftAlignmentStart.position + offset); if (Math.abs(distance2) <= windowWidth) { od.assignedToLocalGroup = true; if (distance1 != 0 && distance2 != 0) { result.incrementAndGet(); } } } }); return result.get(); } private void loadRead(@NonNull ExtendedSAMRecord rExtended, @NonNull DuplexKeeper duplexKeeper, AlignmentExtremetiesDistance ed, InterningSet<SequenceLocation> sequenceLocationCache, SettableInteger nReadsExcludedFromDuplexes) { final @NonNull SequenceLocation location = rExtended.getLocation(); final byte @NonNull[] barcode = rExtended.variableBarcode; final byte @NonNull[] mateBarcode = rExtended.getMateVariableBarcode(); final @NonNull SAMRecord r = rExtended.record; if (rExtended.getMate() == null) { stats.nMateOutOfReach.add(location, 1); } if (r.getMateUnmappedFlag()) { //It is not trivial to tell whether the mate is unmapped because //e.g. it did not sequence properly, or because all of the reads //from the duplex just do not map to the genome. To avoid //artificially inflating local duplex number, do not allow the //read to contribute to computed duplexes. Note that the rest of //the duplex-handling code could technically handle an unmapped //mate, and that the read will still be able to contribute to //local statistics such as average clipping. nReadsExcludedFromDuplexes.incrementAndGet(); return; } boolean foundDuplexRead = false; final boolean matchToLeft = rExtended.duplexLeft(); ed.set(rExtended); for (final Duplex duplex: duplexKeeper.getOverlapping(ed.temp)) { //stats.nVariableBarcodeCandidateExaminations.increment(location); boolean forceGrouping = false; if (Util.nullableify(duplex.allRecords.detect(drRec -> drRec.record.getReadName().equals(r.getReadName()))) != null) { forceGrouping = true; } ed.set(duplex); if (!forceGrouping && ed.getMaxDistance() > param.alignmentPositionMismatchAllowed) { continue; } final boolean barcodeMatch; //During first pass, do not allow any barcode mismatches if (forceGrouping) { barcodeMatch = true; } else if (matchToLeft) { barcodeMatch = basesEqual(duplex.leftBarcode, barcode, param.acceptNInBarCode) && basesEqual(duplex.rightBarcode, mateBarcode, param.acceptNInBarCode); } else { barcodeMatch = basesEqual(duplex.leftBarcode, mateBarcode, param.acceptNInBarCode) && basesEqual(duplex.rightBarcode, barcode, param.acceptNInBarCode); } //noinspection StatementWithEmptyBody if (forceGrouping || barcodeMatch) { if (r.getInferredInsertSize() >= 0) { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.topStrandRecords.contains(rExtended)); } duplex.topStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.bottomStrandRecords.contains(rExtended)); } duplex.bottomStrandRecords.add(rExtended); } } else { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.bottomStrandRecords.contains(rExtended)); } duplex.bottomStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.topStrandRecords.contains(rExtended)); } duplex.topStrandRecords.add(rExtended); } } if (param.enableCostlyAssertions) {//XXX May fail if there was a barcode //read error and duplex grouping was forced for mate Assert.noException(duplex::assertAllBarcodesEqual); } rExtended.duplex = duplex; //stats.nVariableBarcodeMatchAfterPositionCheck.increment(location); foundDuplexRead = true; break; } else {//left and/or right barcodes do not match /* leftEqual = basesEqual(duplexRead.leftBarcode, barcode, true, 1); rightEqual = basesEqual(duplexRead.rightBarcode, barcode, true, 1); if (leftEqual || rightEqual) { stats.nVariableBarcodesCloseMisses.increment(location); }*/ } }//End loop over duplexReads if (!foundDuplexRead) { final Duplex duplex = matchToLeft ? new Duplex(analyzer.groupSettings, barcode, mateBarcode, !r.getReadNegativeStrandFlag(), r.getReadNegativeStrandFlag()) : new Duplex(analyzer.groupSettings, mateBarcode, barcode, r.getReadNegativeStrandFlag(), !r.getReadNegativeStrandFlag()); duplex.roughLocation = location; rExtended.duplex = duplex; if (!matchToLeft) { if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (!r.getFirstOfPairFlag()) { duplex.topStrandRecords.add(rExtended); } else { duplex.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplex::assertAllBarcodesEqual); } duplex.rightAlignmentStart = sequenceLocationCache.intern( rExtended.getOffsetUnclippedStartLoc()); duplex.rightAlignmentEnd = sequenceLocationCache.intern( rExtended.getOffsetUnclippedEndLoc()); duplex.leftAlignmentStart = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedStartLoc()); duplex.leftAlignmentEnd = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedEndLoc()); } else {//Read on positive strand if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size? stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (r.getFirstOfPairFlag()) { duplex.topStrandRecords.add(rExtended); } else { duplex.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplex::assertAllBarcodesEqual); } duplex.leftAlignmentStart = sequenceLocationCache.intern( rExtended.getOffsetUnclippedStartLoc()); duplex.leftAlignmentEnd = sequenceLocationCache.intern( rExtended.getOffsetUnclippedEndLoc()); duplex.rightAlignmentStart = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedStartLoc()); duplex.rightAlignmentEnd = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedEndLoc()); } duplexKeeper.add(duplex); if (false) //noinspection RedundantCast Assert.isFalse( /* There are funny alignments that can trigger this assert; but it should not hurt for alignment start and end to be switched, since it should happen in the same fashion for all reads in a duplex */ duplex.leftAlignmentEnd.contigIndex == duplex.leftAlignmentStart.contigIndex && duplex.leftAlignmentEnd.compareTo(duplex.leftAlignmentStart) < 0, (Supplier<Object>) duplex.leftAlignmentStart::toString, (Supplier<Object>) duplex.leftAlignmentEnd::toString, (Supplier<Object>) duplex::toString, (Supplier<Object>) rExtended::getFullName, "Misordered duplex: %s -- %s %s %s"); }//End new duplex creation if (param.enableCostlyAssertions) { Duplex.checkNoEqualDuplexes(duplexKeeper); } } private static boolean checkReadsOccurOnceInDuplexes( Collection<@NonNull ExtendedSAMRecord> reads, @NonNull Iterable<Duplex> duplexes, int nReadsExcludedFromDuplexes) { ExtendedSAMRecord lostRead = null; int nUnfoundReads = 0; for (final @NonNull ExtendedSAMRecord rExtended: reads) { boolean found = false; for (Duplex dr: duplexes) { if (dr.topStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } if (dr.bottomStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } } if (!found) { nUnfoundReads++; lostRead = rExtended; } } if (nUnfoundReads != nReadsExcludedFromDuplexes) { throw new AssertionFailedException("Lost " + nUnfoundReads + " but expected " + nReadsExcludedFromDuplexes + "; see perhaps " + lostRead); } return true; } @NonNull LocationExaminationResults examineLocation(final @NonNull SequenceLocation location) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { return examineLocation0(location); } finally { threadCount.decrementAndGet(); } } @SuppressWarnings({"null", "ReferenceEquality"}) /** * This method is *NOT* thread-safe (it modifies DuplexReads associated with location retrieved * from field candidateSequences) * @param location * @return */ @NonNull private LocationExaminationResults examineLocation0(final @NonNull SequenceLocation location) { final LocationExaminationResults result = new LocationExaminationResults(); final THashSet<CandidateSequence> candidateSet0 = candidateSequences.get(location); if (candidateSet0 == null) { stats.nPosUncovered.increment(location); result.analyzedCandidateSequences = Sets.immutable.empty(); return result; } final ImmutableSet<CandidateSequence> candidateSet = // DebugLogControl.COSTLY_ASSERTIONS ? // Collections.unmodifiableSet(candidateSet0) // : Sets.immutable.ofAll(candidateSet0); //Retrieve relevant duplex reads //It is necessary not to duplicate the duplex reads, hence the use of a set //Identity should be good enough (and is faster) because no two different duplex read //objects we use in this method should be equal according to the equals() method //(although when grouping duplexes we don't check equality for the inner ends of //the reads since they depend on read length) final TCustomHashSet<Duplex> duplexes = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); candidateSet.forEach(candidate -> { candidate.reset(); final Set<Duplex> candidateDuplexReads = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); List<ExtendedSAMRecord> discarded = Lists.mutable.empty(); candidate.getMutableConcurringReads().retainEntries((r, c) -> { if (r.discarded) { discarded.add(r); return false; } if (param.filterOpticalDuplicates) { if (r.isOpticalDuplicate()) { return false; } } @Nullable Duplex d = r.duplex; //noinspection StatementWithEmptyBody if (d != null) { candidateDuplexReads.add(d); } else { //throw new AssertionFailedException("Read without a duplex :" + r); } return true; }); discarded.forEach(candidate.getMutableConcurringReads()::remove); if (param.enableCostlyAssertions) { checkDuplexes(candidateDuplexReads); } duplexes.addAll(candidateDuplexReads); }); //Allocate here to avoid repeated allocation in DuplexRead::examineAtLoc final CandidateCounter topCounter = new CandidateCounter(candidateSet, location); final CandidateCounter bottomCounter = new CandidateCounter(candidateSet, location); int[] insertSizes = new int [duplexes.size()]; SettableDouble averageCollisionProbS = new SettableDouble(0d); SettableInteger index = new SettableInteger(0); duplexes.forEach(duplexRead -> { Assert.isFalse(duplexRead.invalid); Assert.isTrue(duplexRead.averageNClipped >= 0, () -> duplexRead.toString()); Assert.isTrue(param.variableBarcodeLength > 0 || Double.isNaN(duplexRead.probAtLeastOneCollision) || duplexRead.probAtLeastOneCollision >= 0); duplexRead.examineAtLoc( location, result, candidateSet, topCounter, bottomCounter, analyzer, param, stats); if (index.get() < insertSizes.length) { //Check in case array size was capped (for future use; it is //never capped currently) insertSizes[index.get()] = duplexRead.maxInsertSize; index.incrementAndGet(); } averageCollisionProbS.addAndGet(duplexRead.probAtLeastOneCollision); if (param.variableBarcodeLength == 0 && !duplexRead.missingStrand) { stats.duplexCollisionProbabilityWhen2Strands.insert((int) (1_000f * duplexRead.probAtLeastOneCollision)); } }); if (param.enableCostlyAssertions) { Assert.noException(() -> checkDuplexAndCandidates(duplexes, candidateSet)); candidateSet.forEach(candidate -> checkCandidateDupNoQ(candidate, location)); } if (index.get() > 0) { Arrays.parallelSort(insertSizes, 0, index.get()); result.duplexInsertSize10thP = insertSizes[(int) (index.get() * 0.1f)]; result.duplexInsertSize90thP = insertSizes[(int) (index.get() * 0.9f)]; } double averageCollisionProb = averageCollisionProbS.get(); averageCollisionProb /= duplexes.size(); if (param.variableBarcodeLength == 0) { stats.duplexCollisionProbability.insert((int) (1_000d * averageCollisionProb)); } result.probAtLeastOneCollision = averageCollisionProb; final DetailedQualities<PositionAssay> positionQualities = new DetailedPositionQualities(); if (averageClipping[location.position - averageClippingOffset] > param.maxAverageClippingOfAllCoveringDuplexes) { positionQualities.addUnique( MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS, DUBIOUS); } if (param.enableCostlyAssertions) { Assert.noException(() -> duplexes.forEach((Consumer<Duplex>) Duplex::checkReadOwnership)); } final int totalReadsAtPosition = (int) candidateSet.sumOfInt( c -> c.getNonMutableConcurringReads().size()); final TByteArrayList allPhredQualitiesAtPosition = new TByteArrayList(500); final SettableInteger nWrongPairsAtPosition = new SettableInteger(0); final SettableInteger nPairsAtPosition = new SettableInteger(0); candidateSet.forEach(candidate -> { candidate.addPhredScoresToList(allPhredQualitiesAtPosition); nPairsAtPosition.addAndGet(candidate.getNonMutableConcurringReads().size()); SettableInteger count = new SettableInteger(0); candidate.getNonMutableConcurringReads().forEachKey(r -> { if (r.formsWrongPair()) { count.incrementAndGet(); } return true; }); candidate.setnWrongPairs(count.get()); nWrongPairsAtPosition.addAndGet(candidate.getnWrongPairs()); }); final int nPhredQualities = allPhredQualitiesAtPosition.size(); allPhredQualitiesAtPosition.sort(); final byte positionMedianPhred = nPhredQualities == 0 ? 127 : allPhredQualitiesAtPosition.get(nPhredQualities / 2); if (positionMedianPhred < param.minMedianPhredScoreAtPosition) { positionQualities.addUnique(MEDIAN_PHRED_AT_POS, DUBIOUS); stats.nMedianPhredAtPositionTooLow.increment(location); } stats.medianPositionPhredQuality.insert(positionMedianPhred); if (nWrongPairsAtPosition.get() / ((float) nPairsAtPosition.get()) > param.maxFractionWrongPairsAtPosition) { positionQualities.addUnique(FRACTION_WRONG_PAIRS_AT_POS, DUBIOUS); stats.nFractionWrongPairsAtPositionTooHigh.increment(location); } Handle<Byte> wildtypeBase = new Handle<>((byte) 'X'); candidateSet.forEach(candidate -> { candidate.getQuality().addAllUnique(positionQualities); processCandidateQualityStep1(candidate, result, positionMedianPhred, positionQualities); if (candidate.getMutationType().isWildtype()) { wildtypeBase.set(candidate.getWildtypeSequence()); } }); Quality maxQuality; int totalGoodDuplexes, totalGoodOrDubiousDuplexes, totalGoodDuplexesIgnoringDisag, totalAllDuplexes; boolean leave = false; final boolean qualityOKBeforeTopAllele = Quality.nullableMax(positionQualities.getValue(true), GOOD).atLeast(GOOD); Quality topAlleleQuality = null; //noinspection UnnecessaryBoxing do { maxQuality = MINIMUM; totalAllDuplexes = 0; totalGoodDuplexes = 0; totalGoodOrDubiousDuplexes = 0; totalGoodDuplexesIgnoringDisag = 0; for (CandidateSequence candidate: candidateSet) { if (leave) { candidate.getQuality().addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, DUBIOUS); } @NonNull MutableSetMultimap<Quality, Duplex> map = candidate.getDuplexes(). groupBy(dr -> candidate.filterQuality(dr.localAndGlobalQuality)); if (param.enableCostlyAssertions) { map.forEachKeyMultiValues((k, v) -> Assert.isTrue(Util.getDuplicates(v).isEmpty())); Assert.isTrue(map.multiValuesView().collectInt(RichIterable::size).sum() == candidate.getDuplexes().size()); } @Nullable MutableSet<Duplex> gd = map.get(GOOD); candidate.setnGoodDuplexes(gd == null ? 0 : gd.size()); @Nullable MutableSet<Duplex> db = map.get(DUBIOUS); candidate.setnGoodOrDubiousDuplexes(candidate.getnGoodDuplexes() + (db == null ? 0 : db.size())); candidate.setnGoodDuplexesIgnoringDisag(candidate.getDuplexes(). count(dr -> dr.localAndGlobalQuality.getValueIgnoring(ASSAYS_TO_IGNORE_FOR_DISAGREEMENT_QUALITY).atLeast(GOOD))); maxQuality = max(candidate.getQuality().getValue(), maxQuality); totalAllDuplexes += candidate.getnDuplexes(); totalGoodDuplexes += candidate.getnGoodDuplexes(); totalGoodOrDubiousDuplexes += candidate.getnGoodOrDubiousDuplexes(); totalGoodDuplexesIgnoringDisag += candidate.getnGoodDuplexesIgnoringDisag(); processCandidateQualityStep2(candidate, location); } if (leave) { break; } else { result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; topAlleleQuality = getAlleleFrequencyQuality(candidateSet, result); if (topAlleleQuality == null) { break; } Assert.isTrue(topAlleleQuality == DUBIOUS); positionQualities.addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, topAlleleQuality); leave = true;//Just one more iteration //noinspection UnnecessaryContinue continue; } } while (Boolean.valueOf(null));//Assert never reached if (qualityOKBeforeTopAllele) { registerDuplexMinFracTopCandidate(duplexes, topAlleleQuality == null ? stats.minTopCandFreqQ2PosTopAlleleFreqOK : stats.minTopCandFreqQ2PosTopAlleleFreqKO ); } if (positionQualities.getValue(true) != null && positionQualities.getValue(true).lowerThan(GOOD)) { result.disagreements.clear(); } else { if (param.maxMutFreqForDisag < 1f) { final int finalTotalGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.disagreements.forEachKey(disag -> { Mutation m = disag.getSnd(); if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } m = disag.getFst(); if (m != null && m.mutationType != WILDTYPE) { if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } } return true; }); } stats.nPosDuplexCandidatesForDisagreementQ2.acceptSkip0(location, result.disagQ2Coverage); stats.nPosDuplexCandidatesForDisagreementQ1.acceptSkip0(location, result.disagOneStrandedCoverage); if (param.computeRawMismatches) { candidateSet.forEach(c -> result.rawMismatchesQ2.addAll(c.getRawMismatchesQ2())); candidateSet.forEach(c -> result.rawInsertionsQ2.addAll(c.getRawInsertionsQ2())); candidateSet.forEach(c -> result.rawDeletionsQ2.addAll(c.getRawDeletionsQ2())); } } for (CandidateSequence candidate: candidateSet) { candidate.setTotalAllDuplexes(totalAllDuplexes); candidate.setTotalGoodDuplexes(totalGoodDuplexes); candidate.setTotalGoodOrDubiousDuplexes(totalGoodOrDubiousDuplexes); candidate.setTotalReadsAtPosition(totalReadsAtPosition); final long topReads = candidate.getDuplexes().sumOfInt(d -> d.topStrandRecords.size()); final float bottomReads = candidate.getDuplexes().sumOfInt(d -> d.bottomStrandRecords.size()); candidate.setFractionTopStrandReads(topReads / (topReads + bottomReads)); candidate.setTopAndBottomStrandsPresent(topReads > 0 && bottomReads > 0); } result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.nGoodDuplexes = totalGoodDuplexes; result.nGoodDuplexesIgnoringDisag = totalGoodDuplexesIgnoringDisag; stats.Q1Q2DuplexCoverage.insert(result.nGoodOrDubiousDuplexes); stats.Q2DuplexCoverage.insert(result.nGoodDuplexes); if (result.nGoodOrDubiousDuplexes == 0) { stats.missingStrandsWhenNoUsableDuplex.insert(result.nMissingStrands); stats.strandCoverageImbalanceWhenNoUsableDuplex.insert(result.strandCoverageImbalance); } if (maxQuality.atMost(POOR)) { stats.nPosQualityPoor.increment(location); switch (wildtypeBase.get()) { case 'A' : stats.nPosQualityPoorA.increment(location); break; case 'T' : stats.nPosQualityPoorT.increment(location); break; case 'G' : stats.nPosQualityPoorG.increment(location); break; case 'C' : stats.nPosQualityPoorC.increment(location); break; case 'X' : case 'N' : break;//Ignore because we do not have a record of wildtype sequence default : throw new AssertionFailedException(); } } else if (maxQuality == DUBIOUS) { stats.nPosQualityQ1.increment(location); } else if (maxQuality == GOOD) { stats.nPosQualityQ2.increment(location); } else { throw new AssertionFailedException(); } result.analyzedCandidateSequences = candidateSet; return result; }//End examineLocation private static void registerDuplexMinFracTopCandidate(TCustomHashSet<Duplex> duplexes, Histogram hist) { duplexes.forEach(dr -> { if (dr.allRecords.size() < 2 || dr.minFracTopCandidate == Float.MAX_VALUE) { return true; } hist.insert((int) (dr.minFracTopCandidate * 10)); return true; }); } private boolean lowMutFreq(Mutation mut, ImmutableSet<CandidateSequence> candidateSet, int nGOrDDuplexes) { Objects.requireNonNull(mut); Handle<Boolean> result = new Handle<>(true); candidateSet.detect((CandidateSequence c) -> { Mutation cMut = c.getMutation(); if (cMut.equals(mut)) { if (c.getnGoodOrDubiousDuplexes() > param.maxMutFreqForDisag * nGOrDDuplexes) { result.set(false); } return true; } return false; }); return result.get(); } private static float divideWithNanToZero(float f1, float f2) { return f2 == 0f ? 0 : f1 / f2; } private @Nullable Quality getAlleleFrequencyQuality( ImmutableSet<CandidateSequence> candidateSet, LocationExaminationResults result) { MutableFloatList frequencyList = candidateSet.collectFloat(c -> divideWithNanToZero(c.getnGoodOrDubiousDuplexes(), result.nGoodOrDubiousDuplexes), new FloatArrayList(Math.max(2, candidateSet.size()))).//Need second argument to collectInt //to avoid collecting into a set sortThis(); result.alleleFrequencies = frequencyList; while (frequencyList.size() < 2) { frequencyList.addAtIndex(0, Float.NaN); } float topAlleleFrequency = frequencyList.getLast(); if (!(topAlleleFrequency >= param.minTopAlleleFreqQ2 && topAlleleFrequency <= param.maxTopAlleleFreqQ2)) { return DUBIOUS; } return null; } private static void checkCandidateDupNoQ(CandidateSequence candidate, SequenceLocation location) { candidate.getNonMutableConcurringReads().forEachKey(r -> { Duplex dr = r.duplex; if (dr != null) { if (dr.lastExaminedPosition != location.position) { throw new AssertionFailedException("Last examined position is " + dr.lastExaminedPosition + " instead of " + location.position + " for duplex " + dr); } if (r.discarded) { throw new AssertionFailedException("Discarded read " + r + " in duplex " + dr); } Assert.isTrue(dr.localAndGlobalQuality.getQuality(QUALITY_AT_POSITION) == null); Assert.isFalse(dr.invalid); } return true; }); } @SuppressWarnings("null") private void processCandidateQualityStep1( final CandidateSequence candidate, final LocationExaminationResults result, final byte positionMedianPhred, final @NonNull DetailedQualities<PositionAssay> positionQualities) { candidate.setMedianPhredAtPosition(positionMedianPhred); final byte candidateMedianPhred = candidate.getMedianPhredScore();//Will be -1 for insertions and deletions if (candidateMedianPhred != -1 && candidateMedianPhred < param.minCandidateMedianPhredScore) { candidate.getQuality().addUnique(MEDIAN_CANDIDATE_PHRED, DUBIOUS); } //TODO Should report min rather than average collision probability? candidate.setProbCollision((float) result.probAtLeastOneCollision); candidate.setInsertSizeAtPos10thP(result.duplexInsertSize10thP); candidate.setInsertSizeAtPos90thP(result.duplexInsertSize90thP); final MutableSet<Duplex> candidateDuplexes = candidate.computeSupportingDuplexes(); candidate.setDuplexes(candidateDuplexes); candidate.setnDuplexes(candidateDuplexes.size()); if (candidate.getnDuplexes() == 0) { candidate.getQuality().addUnique(NO_DUPLEXES, ATROCIOUS); } if (param.verbosity > 2) { candidateDuplexes.forEach(d -> candidate.getIssues().put(d, d.localAndGlobalQuality.toLong())); } final Quality posQMin = positionQualities.getValue(true); Handle<Quality> maxDuplexQHandle = new Handle<>(ATROCIOUS); candidateDuplexes.each(dr -> { if (posQMin != null) { dr.localAndGlobalQuality.addUnique(QUALITY_AT_POSITION, posQMin); } maxDuplexQHandle.set(max(maxDuplexQHandle.get(), candidate.filterQuality(dr.localAndGlobalQuality))); }); final @NonNull Quality maxDuplexQ = maxDuplexQHandle.get(); candidate.updateQualities(param); switch(param.candidateQ2Criterion) { case "1Q2Duplex": candidate.getQuality().addUnique(MAX_Q_FOR_ALL_DUPLEXES, maxDuplexQ); break; case "NQ1Duplexes": int duplexCount = candidateDuplexes.count(d -> d.localAndGlobalQuality.getValueIgnoring(ASSAYS_TO_IGNORE_FOR_DUPLEX_NSTRANDS).atLeast(GOOD) && d.allRecords.size() > 1 * 2); setNQ1DupQuality(candidate, duplexCount, param.minQ1Duplexes, param.minTotalReadsForNQ1Duplexes); break; default: throw new AssertionFailedException(); } if (PositionAssay.COMPUTE_MAX_DPLX_Q_IGNORING_DISAG) { candidateDuplexes.stream(). map(dr -> dr.localAndGlobalQuality.getValueIgnoring(ASSAYS_TO_IGNORE_FOR_DISAGREEMENT_QUALITY, true)). max(Quality::compareTo).ifPresent(q -> candidate.getQuality().addUnique(MAX_DPLX_Q_IGNORING_DISAG, q)); } if (maxDuplexQ.atLeast(DUBIOUS)) { candidateDuplexes.forEach(dr -> { if (dr.localAndGlobalQuality.getValue().atLeast(maxDuplexQ)) { candidate.acceptLigSiteDistance(dr.getMaxDistanceToLigSite()); } }); } } private static void setNQ1DupQuality(CandidateSequence candidate, int duplexCount, int minQ1Duplexes, int minTotalReads) { boolean good = duplexCount >= minQ1Duplexes && candidate.getNonMutableConcurringReads().size() >= minTotalReads; candidate.getQuality().addUnique(PositionAssay.N_Q1_DUPLEXES, good ? GOOD : DUBIOUS); } private void processCandidateQualityStep2( final CandidateSequence candidate, final @NonNull SequenceLocation location ) { if (false && !param.rnaSeq) { candidate.getNonMutableConcurringReads().forEachKey(r -> { final int refPosition = location.position; final int readPosition = r.referencePositionToReadPosition(refPosition); if (!r.formsWrongPair()) { final int distance = r.tooCloseToBarcode(readPosition, 0); if (Math.abs(distance) > 160) { throw new AssertionFailedException("Distance problem with candidate " + candidate + " read at read position " + readPosition + " and refPosition " + refPosition + ' ' + r.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance); } if (distance >= 0) { stats.singleAnalyzerQ2CandidateDistanceToLigationSite.insert(distance); } else { stats.Q2CandidateDistanceToLigationSiteN.insert(-distance); } } return true; }); } if (candidate.getMutationType().isWildtype()) { candidate.setSupplementalMessage(null); } else if (candidate.getQuality().getNonNullValue().greaterThan(POOR)) { final StringBuilder supplementalMessage = new StringBuilder(); final Map<String, Integer> stringCounts = new HashMap<>(100); candidate.getNonMutableConcurringReads().forEachKey(er -> { String other = er.record.getMateReferenceName(); if (!er.record.getReferenceName().equals(other)) { String s = other + ':' + er.getMateAlignmentStart(); int found = stringCounts.getOrDefault(s, 0); stringCounts.put(s, found + 1); } return true; }); final Optional<String> mates = stringCounts.entrySet().stream().map(entry -> entry.getKey() + ((entry.getValue() == 1) ? "" : (" (" + entry.getValue() + " repeats)")) + "; "). sorted().reduce(String::concat); final String hasMateOnOtherChromosome = mates.orElse(""); IntSummaryStatistics insertSizeStats = candidate.getConcurringReadSummaryStatistics(er -> Math.abs(er.getInsertSize())); final int localMaxInsertSize = insertSizeStats.getMax(); final int localMinInsertSize = insertSizeStats.getMin(); candidate.setMinInsertSize(insertSizeStats.getMin()); candidate.setMaxInsertSize(insertSizeStats.getMax()); if (localMaxInsertSize < param.minInsertSize || localMinInsertSize > param.maxInsertSize) { candidate.getQuality().add(PositionAssay.INSERT_SIZE, DUBIOUS); } final NumberFormat nf = DoubleAdderFormatter.nf.get(); @SuppressWarnings("null") final boolean hasNoMate = candidate.getNonMutableConcurringReads().forEachKey( er -> er.record.getMateReferenceName() != null); if (localMaxInsertSize > param.maxInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMaxInsertSize)).append("; "); } if (localMinInsertSize < param.minInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMinInsertSize)).append("; "); } IntSummaryStatistics mappingQualities = candidate.getConcurringReadSummaryStatistics(er -> er.record.getMappingQuality()); candidate.setAverageMappingQuality((int) mappingQualities.getAverage()); if (!"".equals(hasMateOnOtherChromosome)) { supplementalMessage.append("pair elements map to other chromosomes: " + hasMateOnOtherChromosome).append("; "); } if (hasNoMate) { supplementalMessage.append("at least one read has no mate nearby; "); } if ("".equals(hasMateOnOtherChromosome) && !hasNoMate && localMinInsertSize == 0) { supplementalMessage.append("at least one insert has 0 predicted size; "); } if (candidate.getnWrongPairs() > 0) { supplementalMessage.append(candidate.getnWrongPairs() + " wrong pairs; "); } candidate.setSupplementalMessage(supplementalMessage); } } @SuppressWarnings("ReferenceEquality") private static void checkDuplexes(Iterable<Duplex> duplexes) { for (Duplex duplex: duplexes) { duplex.allRecords.each(r -> { //noinspection ObjectEquality if (r.duplex != duplex) { throw new AssertionFailedException("Read " + r + " associated with duplexes " + r.duplex + " and " + duplex); } }); } @NonNull Set<Duplex> duplicates = Util.getDuplicates(duplexes); if (!duplicates.isEmpty()) { throw new AssertionFailedException("Duplicate duplexes: " + duplicates); } } @SuppressWarnings("ReferenceEquality") private static void checkDuplexAndCandidates(Set<Duplex> duplexes, ImmutableSet<CandidateSequence> candidateSet) { checkDuplexes(duplexes); candidateSet.each(c -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); Set<Duplex> duplexesSupportingC = c.computeSupportingDuplexes(); candidateSet.each(c2 -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); //noinspection ObjectEquality if (c2 == c) { return; } if (c2.equals(c)) { throw new AssertionFailedException(); } c2.getNonMutableConcurringReads().keySet().forEach(r -> { //if (r.isOpticalDuplicate()) { // return; //} Assert.isFalse(r.discarded); Duplex d = r.duplex; if (d != null && duplexesSupportingC.contains(d)) { boolean disowned = !d.allRecords.contains(r); throw new AssertionFailedException(disowned + " Duplex " + d + " associated with candidates " + c + " and " + c2); } }); }); }); } private boolean checkConstantBarcode(byte[] bases, boolean allowN, int nAllowableMismatches) { if (nAllowableMismatches == 0 && !allowN) { //noinspection ArrayEquality return bases == analyzer.constantBarcode;//OK because of interning } int nMismatches = 0; for (int i = 0; i < analyzer.constantBarcode.length; i++) { if (!basesEqual(analyzer.constantBarcode[i], bases[i], allowN)) { nMismatches ++; if (nMismatches > nAllowableMismatches) return false; } } return true; } @NonNull ExtendedSAMRecord getExtended(@NonNull SAMRecord record, @NonNull SequenceLocation location) { final @NonNull String readFullName = ExtendedSAMRecord.getReadFullName(record, false); return extSAMCache.computeIfAbsent(readFullName, s -> new ExtendedSAMRecord(record, readFullName, analyzer.stats, analyzer, location, extSAMCache)); } @SuppressWarnings("null") public static @NonNull ExtendedSAMRecord getExtendedNoCaching(@NonNull SAMRecord record, @NonNull SequenceLocation location, Mutinack analyzer) { final @NonNull String readFullName = ExtendedSAMRecord.getReadFullName(record, false); return new ExtendedSAMRecord(record, readFullName, Collections.emptyList(), analyzer, location, null); } /** * * @return the furthest position in the contig covered by the read */ int processRead( final @NonNull SequenceLocation location, final @NonNull InterningSet<SequenceLocation> locationInterningSet, final @NonNull ExtendedSAMRecord extendedRec, final @NonNull ReferenceSequence ref) { Assert.isFalse(extendedRec.processed, "Double processing of record %s"/*, extendedRec.getFullName()*/); extendedRec.processed = true; final SAMRecord rec = extendedRec.record; final int effectiveReadLength = extendedRec.effectiveLength; if (effectiveReadLength == 0) { return -1; } final CandidateBuilder readLocalCandidates = new CandidateBuilder(rec.getReadNegativeStrandFlag(), analyzer.codingStrandTester, param.enableCostlyAssertions ? null : (k, v) -> insertCandidateAtPosition(v, k)); final int insertSize = extendedRec.getInsertSize(); final int insertSizeAbs = Math.abs(insertSize); if (insertSizeAbs > param.maxInsertSize) { stats.nReadsInsertSizeAboveMaximum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } if (insertSizeAbs < param.minInsertSize) { stats.nReadsInsertSizeBelowMinimum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } final PairOrientation pairOrientation; if (rec.getReadPairedFlag() && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && rec.getReferenceIndex().equals(rec.getMateReferenceIndex()) && ((pairOrientation = SamPairUtil.getPairOrientation(rec)) == PairOrientation.TANDEM || pairOrientation == PairOrientation.RF)) { if (pairOrientation == PairOrientation.TANDEM) { stats.nReadsPairTandem.increment(location); } else if (pairOrientation == PairOrientation.RF) { stats.nReadsPairRF.increment(location); } if (param.ignoreTandemRFPairs) { return -1; } } final boolean readOnNegativeStrand = rec.getReadNegativeStrandFlag(); if (!checkConstantBarcode(extendedRec.constantBarcode, false, param.nConstantBarcodeMismatchesAllowed)) { if (checkConstantBarcode(extendedRec.constantBarcode, true, param.nConstantBarcodeMismatchesAllowed)) { if (readOnNegativeStrand) stats.nConstantBarcodeDodgyNStrand.increment(location); else stats.nConstantBarcodeDodgy.increment(location); if (!param.acceptNInBarCode) return -1; } else { stats.nConstantBarcodeMissing.increment(location); return -1; } } stats.nReadsConstantBarcodeOK.increment(location); if (extendedRec.medianPhred < param.minReadMedianPhredScore) { stats.nReadMedianPhredBelowThreshold.accept(location); return -1; } stats.mappingQualityKeptRecords.insert(rec.getMappingQuality()); SettableInteger refEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger readEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger returnValue = new SettableInteger(-1); if (insertSize == 0) { stats.nReadsInsertNoSize.increment(location); if (param.ignoreZeroInsertSizeReads) { return -1; } } if (rec.getMappingQuality() < param.minMappingQualityQ1) { return -1; } for (ExtendedAlignmentBlock block: extendedRec.getAlignmentBlocks()) { processAlignmentBlock( location, locationInterningSet, readLocalCandidates, ref, block, extendedRec, rec, readOnNegativeStrand, effectiveReadLength, refEndOfPreviousAlignment, readEndOfPreviousAlignment, returnValue); } if (param.enableCostlyAssertions) { readLocalCandidates.build().forEach((k, v) -> insertCandidateAtPosition(v, k)); } return returnValue.get(); } private void processAlignmentBlock( @NonNull SequenceLocation location, InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ReferenceSequence ref, final ExtendedAlignmentBlock block, final @NonNull ExtendedSAMRecord extendedRec, final SAMRecord rec, final boolean readOnNegativeStrand, final int effectiveReadLength, final SettableInteger refEndOfPreviousAlignment0, final SettableInteger readEndOfPreviousAlignment0, final SettableInteger returnValue) { @SuppressWarnings("AnonymousInnerClassMayBeStatic") final CandidateFiller fillInCandidateInfo = new CandidateFiller() { @Override public void accept(CandidateSequence candidate) { candidate.setInsertSize(extendedRec.getInsertSize()); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); } @Override public void fillInPhred(CandidateSequence candidate, SequenceLocation location1, int readPosition) { final byte quality = rec.getBaseQualities()[readPosition]; candidate.addBasePhredScore(quality); if (extendedRec.basePhredScores.put(location1, quality) != ExtendedSAMRecord.PHRED_NO_ENTRY) { logger.warn("Recording Phred score multiple times at same position " + location1); } } }; int refPosition = block.getReferenceStart() - 1; int readPosition = block.getReadStart() - 1; final int nBlockBases = block.getLength(); final int refEndOfPreviousAlignment = refEndOfPreviousAlignment0.get(); final int readEndOfPreviousAlignment = readEndOfPreviousAlignment0.get(); returnValue.set(Math.max(returnValue.get(), refPosition + nBlockBases)); /** * When adding an insertion candidate, make sure that a wildtype or * mismatch candidate is also inserted at the same position, even * if it normally would not have been (for example because of low Phred * quality). This should avoid awkward comparisons between e.g. an * insertion candidate and a combo insertion + wildtype candidate. */ boolean forceCandidateInsertion = false; if (refEndOfPreviousAlignment != -1) { final boolean insertion = refPosition == refEndOfPreviousAlignment + 1; final boolean tooLate = (readOnNegativeStrand ? (insertion ? readPosition <= param.ignoreLastNBases : readPosition < param.ignoreLastNBases) : readPosition > rec.getReadLength() - param.ignoreLastNBases) && !param.rnaSeq; if (tooLate) { if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring indel too close to end " + readPosition + (readOnNegativeStrand ? " neg strand " : " pos strand ") + readPosition + ' ' + (rec.getReadLength() - 1) + ' ' + extendedRec.getFullName()); } stats.nCandidateIndelAfterLastNBases.increment(location); } else { if (insertion) { stats.nCandidateInsertions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion at position " + readPosition + " for read " + rec.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand); } forceCandidateInsertion = processInsertion( fillInCandidateInfo, readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec, readOnNegativeStrand); } else if (refPosition < refEndOfPreviousAlignment + 1) { throw new AssertionFailedException("Alignment block misordering"); } else { processDeletion( fillInCandidateInfo, location, ref, block, readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec); }//End of deletion case }//End of case with accepted indel }//End of case where there was a previous alignment block refEndOfPreviousAlignment0.set(refPosition + (nBlockBases - 1)); readEndOfPreviousAlignment0.set(readPosition + (nBlockBases - 1)); final byte [] readBases = rec.getReadBases(); final byte [] baseQualities = rec.getBaseQualities(); for (int i = 0; i < nBlockBases; i++, readPosition++, refPosition++) { if (i == 1) { forceCandidateInsertion = false; } Handle<Boolean> insertCandidateAtRegularPosition = new Handle<>(true); final SequenceLocation locationPH = i < nBlockBases - 1 ? //No insertion or deletion; make a note of it SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refPosition, true) : null; location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refPosition); if (baseQualities[readPosition] < param.minBasePhredScoreQ1) { stats.nBasesBelowPhredScore.increment(location); if (forceCandidateInsertion) { insertCandidateAtRegularPosition.set(false); } else { continue; } } if (refPosition > ref.length() - 1) { logger.warn("Ignoring base mapped at " + refPosition + ", beyond the end of " + ref.getName()); continue; } stats.nCandidateSubstitutionsConsidered.increment(location); byte wildType = StringUtil.toUpperCase(ref.getBases()[refPosition]); if (isMutation(wildType, readBases[readPosition])) {/*Mismatch*/ final boolean tooLate = readOnNegativeStrand ? readPosition < param.ignoreLastNBases : readPosition > (rec.getReadLength() - 1) - param.ignoreLastNBases; boolean goodToInsert = checkSubstDistance( readPosition, location, tooLate, insertCandidateAtRegularPosition, extendedRec) && !tooLate; if (goodToInsert || forceCandidateInsertion) { processSubstitution( fillInCandidateInfo, location, locationPH, readPosition, readLocalCandidates, extendedRec, readOnNegativeStrand, wildType, effectiveReadLength, forceCandidateInsertion, insertCandidateAtRegularPosition); }//End of mismatched read case } else { processWildtypeBase( fillInCandidateInfo, location, locationPH, readPosition, refPosition, wildType, readLocalCandidates, extendedRec, readOnNegativeStrand, forceCandidateInsertion, insertCandidateAtRegularPosition); }//End of wildtype case }//End of loop over alignment bases } private static boolean isMutation(byte ucReferenceBase, byte ucReadBase) { Assert.isTrue(ucReferenceBase < 91);//Assert base is upper case Assert.isTrue(ucReadBase < 91); switch (ucReferenceBase) { case 'Y': return ucReadBase != 'C' && ucReadBase != 'T'; case 'R': return ucReadBase != 'G' && ucReadBase != 'A'; case 'W': return ucReadBase != 'A' && ucReadBase != 'T'; default: return ucReadBase != ucReferenceBase; } } private interface CandidateFiller { void accept(CandidateSequence candidate); void fillInPhred(CandidateSequence candidate, SequenceLocation location, int readPosition); } private boolean checkSubstDistance( int readPosition, @NonNull SequenceLocation location, boolean tooLate, Handle<Boolean> insertCandidateAtRegularPosition, ExtendedSAMRecord extendedRec) { int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition.get()) { stats.rejectedSubstDistanceToLigationSite.insert(-distance); stats.nCandidateSubstitutionsBeforeFirstNBases.increment(location); } } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to barcode for read " + extendedRec.getFullName()); } insertCandidateAtRegularPosition.set(false); } else if (tooLate && insertCandidateAtRegularPosition.get()) { stats.nCandidateSubstitutionsAfterLastNBases.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to read end for read " + extendedRec.getFullName()); } insertCandidateAtRegularPosition.set(false); } return distance < 0; } private void processWildtypeBase( final CandidateFiller candidateFiller, final @NonNull SequenceLocation location, final @Nullable SequenceLocation locationPH, final int readPosition, final int refPosition, byte wildType, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final boolean readOnNegativeStrand, final boolean forceCandidateInsertion, final Handle<Boolean> insertCandidateAtRegularPosition) { int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition.get()) { stats.wtRejectedDistanceToLigationSite.insert(-distance); } } if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } } else { if (!extendedRec.formsWrongPair() && distance < -150) { throw new AssertionFailedException("Distance problem 1 at read position " + readPosition + " and refPosition " + refPosition + ' ' + extendedRec.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance + ""); } distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (!extendedRec.formsWrongPair() && insertCandidateAtRegularPosition.get()) { stats.wtAcceptedBaseDistanceToLigationSite.insert(-distance); } } if (((!readOnNegativeStrand && readPosition > extendedRec.record.getReadLength() - 1 - param.ignoreLastNBases) || (readOnNegativeStrand && readPosition < param.ignoreLastNBases))) { if (insertCandidateAtRegularPosition.get()) { stats.nCandidateWildtypeAfterLastNBases.increment(location); } if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } } CandidateSequence candidate = new CandidateSequence(this, WILDTYPE, null, location, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(-distance); } candidate.setWildtypeSequence(wildType); candidateFiller.fillInPhred(candidate, location, readPosition); if (insertCandidateAtRegularPosition.get()) { //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, location); //noinspection UnusedAssignment candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(-distance); } candidate2.setWildtypeSequence(wildType); //noinspection UnusedAssignment candidate2 = readLocalCandidates.add(candidate2, locationPH); //noinspection UnusedAssignment candidate2 = null; } } private void processSubstitution( final CandidateFiller candidateFiller, final @NonNull SequenceLocation location, final @Nullable SequenceLocation locationPH, final int readPosition, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final boolean readOnNegativeStrand, final byte wildType, final int effectiveReadLength, final boolean forceCandidateInsertion, final Handle<Boolean> insertCandidateAtRegularPosition) { if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Substitution at position " + readPosition + " for read " + extendedRec.record.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + extendedRec.getInsertSize() + ')'); } final byte mutation = extendedRec.record.getReadBases()[readPosition]; final byte mutationUC = StringUtil.toUpperCase(mutation); switch (mutationUC) { case 'A': stats.nCandidateSubstitutionsToA.increment(location); break; case 'T': stats.nCandidateSubstitutionsToT.increment(location); break; case 'G': stats.nCandidateSubstitutionsToG.increment(location); break; case 'C': stats.nCandidateSubstitutionsToC.increment(location); break; case 'N': stats.nNs.increment(location); if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } break; default: throw new AssertionFailedException("Unexpected letter: " + mutationUC); } final int distance = -extendedRec.tooCloseToBarcode(readPosition, 0); CandidateSequence candidate = new CandidateSequence(this, SUBSTITUTION, byteArrayMap.get(mutation), location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidateFiller.accept(candidate); candidate.setPositionInRead(readPosition); candidate.setWildtypeSequence(wildType); candidateFiller.fillInPhred(candidate, location, readPosition); extendedRec.nReferenceDisagreements++; if (param.computeRawMismatches && insertCandidateAtRegularPosition.get()) { registerRawMismatch(location, extendedRec, readPosition, distance, candidate.getMutableRawMismatchesQ2(), stats.rawMismatchesQ1, getFromByteMap(wildType, readOnNegativeStrand), getFromByteMap(mutationUC, readOnNegativeStrand)); } if (insertCandidateAtRegularPosition.get()) { //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, location); //noinspection UnusedAssignment candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(distance); } candidate2.setWildtypeSequence(wildType); //noinspection UnusedAssignment candidate2 = readLocalCandidates.add(candidate2, locationPH); //noinspection UnusedAssignment candidate2 = null; } } private static @NonNull String getFromByteMap(byte b, boolean reverseComplement) { String result = reverseComplement ? byteMap.get(Mutation.complement(b)) : byteMap.get(b); return Objects.requireNonNull(result); } private void registerRawMismatch( final @NonNull SequenceLocation location, final @NonNull ExtendedSAMRecord extendedRec, final int readPosition, final int distance, final Collection<ComparablePair<String, String>> mismatches, final MultiCounter<ComparablePair<String, String>> q1Stats, final @NonNull String wildType, final @NonNull String mutation) { final ComparablePair<String, String> mutationPair = new ComparablePair<>(wildType, mutation); q1Stats.accept(location, mutationPair); if (meetsQ2Thresholds(extendedRec) && extendedRec.record.getBaseQualities()[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { mismatches.add(mutationPair); } } private static @NonNull String toUpperCase(byte @NonNull [] deletedSequence, boolean readOnNegativeStrand) { @NonNull String s = new String(deletedSequence).toUpperCase(); return readOnNegativeStrand ? Mutation.reverseComplement(s) : s; } //Deletion or skipped region ("N" in Cigar) private void processDeletion( final CandidateFiller candidateFiller, final @NonNull SequenceLocation location, final @NonNull ReferenceSequence ref, final ExtendedAlignmentBlock block, final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, final InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec) { if (refPosition > ref.length() - 1) { logger.warn("Ignoring rest of read after base mapped at " + refPosition + ", beyond the end of " + ref.getName()); return; } int distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, param.ignoreFirstNBasesQ1); int distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, param.ignoreFirstNBasesQ1); int distance = Math.min(distance0, distance1) + 1; final boolean isIntron = block.previousCigarOperator == CigarOperator.N; final boolean Q1reject = distance < 0; if (!isIntron && Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring deletion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); } else { distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, 0); distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, 0); distance = Math.min(distance0, distance1) + 1; if (!isIntron) stats.nCandidateDeletions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Deletion or intron at position " + readPosition + " for read " + extendedRec.record.getReadName()); } final int deletionLength = refPosition - (refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation newLocation = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation deletionEnd = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), newLocation.position + deletionLength); final byte @Nullable[] deletedSequence = isIntron ? null : Arrays.copyOfRange(ref.getBases(), refEndOfPreviousAlignment + 1, refPosition); //Add hidden mutations to all locations covered by deletion //So disagreements between deletions that have only overlapping //spans are detected. if (!isIntron) { for (int i = 1; i < deletionLength; i++) { SequenceLocation location2 = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1 + i); CandidateSequence hiddenCandidate = new CandidateDeletion( this, deletedSequence, location2, extendedRec, Integer.MAX_VALUE, MutationType.DELETION, newLocation, deletionEnd); candidateFiller.accept(hiddenCandidate); hiddenCandidate.setHidden(true); hiddenCandidate.setPositionInRead(readPosition); //noinspection UnusedAssignment hiddenCandidate = readLocalCandidates.add(hiddenCandidate, location2); //noinspection UnusedAssignment hiddenCandidate = null; } } CandidateSequence candidate = new CandidateDeletion(this, deletedSequence, newLocation, extendedRec, distance, isIntron ? MutationType.INTRON : MutationType.DELETION, newLocation, SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refPosition)); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidateFiller.accept(candidate); candidate.setPositionInRead(readPosition); if (!isIntron) extendedRec.nReferenceDisagreements++; if (!isIntron && param.computeRawMismatches) { Objects.requireNonNull(deletedSequence); stats.rawDeletionLengthQ1.insert(deletedSequence.length); final boolean negativeStrand = extendedRec.getReadNegativeStrandFlag(); registerRawMismatch(newLocation, extendedRec, readPosition, distance, candidate.getMutableRawDeletionsQ2(), stats.rawDeletionsQ1, getFromByteMap(deletedSequence[0], negativeStrand), toUpperCase(deletedSequence, negativeStrand)); } //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, newLocation); //noinspection UnusedAssignment candidate = null; } } private boolean processInsertion( final CandidateFiller candidateFiller, final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, final InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final boolean readOnNegativeStrand) { final @NonNull SequenceLocation location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment, true); int distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, param.ignoreFirstNBasesQ1); int distance1 = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); int distance = Math.max(distance0, distance1); distance = -distance + 1; final boolean Q1reject = distance < 0; if (Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring insertion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); return false; } distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, 0); distance1 = extendedRec.tooCloseToBarcode(readPosition, 0); distance = Math.max(distance0, distance1); distance = -distance + 1; final byte [] readBases = extendedRec.record.getReadBases(); final byte @NonNull [] insertedSequence = Arrays.copyOfRange(readBases, readEndOfPreviousAlignment + 1, readPosition); CandidateSequence candidate = new CandidateSequence( this, INSERTION, insertedSequence, location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidateFiller.accept(candidate); candidate.setPositionInRead(readPosition); if (param.computeRawMismatches) { stats.rawInsertionLengthQ1.insert(insertedSequence.length); registerRawMismatch(location, extendedRec, readPosition, distance, candidate.getMutableRawInsertionsQ2(), stats.rawInsertionsQ1, getFromByteMap(readBases[readEndOfPreviousAlignment], readOnNegativeStrand), toUpperCase(insertedSequence, readOnNegativeStrand)); } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion of " + new String(candidate.getSequence()) + " at ref " + refPosition + " and read position " + readPosition + " for read " + extendedRec.getFullName()); } //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, location); //noinspection UnusedAssignment candidate = null; if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Added candidate at " + location /*+ "; readLocalCandidates now " + readLocalCandidates.build()*/); } extendedRec.nReferenceDisagreements++; return true; } public @NonNull Mutinack getAnalyzer() { return analyzer; } }
src/uk/org/cinquin/mutinack/SubAnalyzer.java
/** * Mutinack mutation detection program. * Copyright (C) 2014-2016 Olivier Cinquin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.org.cinquin.mutinack; import static contrib.uk.org.lidalia.slf4jext.Level.TRACE; import static uk.org.cinquin.mutinack.MutationType.INSERTION; import static uk.org.cinquin.mutinack.MutationType.SUBSTITUTION; import static uk.org.cinquin.mutinack.MutationType.WILDTYPE; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.DISAGREEMENT; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.MISSING_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.N_READS_PER_STRAND; import static uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay.QUALITY_AT_POSITION; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.FRACTION_WRONG_PAIRS_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_DPLX_Q_IGNORING_DISAG; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MAX_Q_FOR_ALL_DUPLEXES; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_CANDIDATE_PHRED; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.MEDIAN_PHRED_AT_POS; import static uk.org.cinquin.mutinack.candidate_sequences.PositionAssay.NO_DUPLEXES; import static uk.org.cinquin.mutinack.misc_util.DebugLogControl.NONTRIVIAL_ASSERTIONS; import static uk.org.cinquin.mutinack.misc_util.Util.basesEqual; import static uk.org.cinquin.mutinack.qualities.Quality.ATROCIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.DUBIOUS; import static uk.org.cinquin.mutinack.qualities.Quality.GOOD; import static uk.org.cinquin.mutinack.qualities.Quality.MINIMUM; import static uk.org.cinquin.mutinack.qualities.Quality.POOR; import static uk.org.cinquin.mutinack.qualities.Quality.max; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.IntSummaryStatistics; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import org.eclipse.collections.api.RichIterable; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.list.primitive.MutableFloatList; import org.eclipse.collections.api.multimap.set.MutableSetMultimap; import org.eclipse.collections.api.set.ImmutableSet; import org.eclipse.collections.api.set.MutableSet; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.list.mutable.FastList; import org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import contrib.net.sf.picard.reference.ReferenceSequence; import contrib.net.sf.samtools.CigarOperator; import contrib.net.sf.samtools.SAMRecord; import contrib.net.sf.samtools.SamPairUtil; import contrib.net.sf.samtools.SamPairUtil.PairOrientation; import contrib.net.sf.samtools.util.StringUtil; import contrib.uk.org.lidalia.slf4jext.Logger; import contrib.uk.org.lidalia.slf4jext.LoggerFactory; import gnu.trove.list.array.TByteArrayList; import gnu.trove.map.TByteObjectMap; import gnu.trove.map.hash.TByteObjectHashMap; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.set.hash.TCustomHashSet; import gnu.trove.set.hash.THashSet; import uk.org.cinquin.mutinack.candidate_sequences.CandidateBuilder; import uk.org.cinquin.mutinack.candidate_sequences.CandidateCounter; import uk.org.cinquin.mutinack.candidate_sequences.CandidateDeletion; import uk.org.cinquin.mutinack.candidate_sequences.CandidateSequence; import uk.org.cinquin.mutinack.candidate_sequences.DuplexAssay; import uk.org.cinquin.mutinack.candidate_sequences.ExtendedAlignmentBlock; import uk.org.cinquin.mutinack.candidate_sequences.PositionAssay; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.ComparablePair; import uk.org.cinquin.mutinack.misc_util.DebugLogControl; import uk.org.cinquin.mutinack.misc_util.Handle; import uk.org.cinquin.mutinack.misc_util.Pair; import uk.org.cinquin.mutinack.misc_util.SettableDouble; import uk.org.cinquin.mutinack.misc_util.SettableInteger; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.collections.HashingStrategies; import uk.org.cinquin.mutinack.misc_util.collections.InterningSet; import uk.org.cinquin.mutinack.misc_util.collections.duplex_keeper.DuplexArrayListKeeper; import uk.org.cinquin.mutinack.misc_util.collections.duplex_keeper.DuplexHashMapKeeper; import uk.org.cinquin.mutinack.misc_util.collections.duplex_keeper.DuplexKeeper; import uk.org.cinquin.mutinack.misc_util.exceptions.AssertionFailedException; import uk.org.cinquin.mutinack.output.LocationExaminationResults; import uk.org.cinquin.mutinack.qualities.DetailedPositionQualities; import uk.org.cinquin.mutinack.qualities.DetailedQualities; import uk.org.cinquin.mutinack.qualities.Quality; import uk.org.cinquin.mutinack.statistics.DoubleAdderFormatter; import uk.org.cinquin.mutinack.statistics.Histogram; import uk.org.cinquin.mutinack.statistics.MultiCounter; public final class SubAnalyzer { private static final Logger logger = LoggerFactory.getLogger(SubAnalyzer.class); //For assertion and debugging purposes public boolean incrementednPosDuplexQualityQ2OthersQ1Q2, processed, c1, c2, c3, c4; public final @NonNull Mutinack analyzer; @NonNull Parameters param; @NonNull public AnalysisStats stats;//Will in fact be null until set in SubAnalyzerPhaser but that's OK final @NonNull SettableInteger lastProcessablePosition = new SettableInteger(-1); final @NonNull THashMap<SequenceLocation, THashSet<CandidateSequence>> candidateSequences = new THashMap<>(1_000); int truncateProcessingAt = Integer.MAX_VALUE; int startProcessingAt = 0; MutableList<@NonNull Duplex> analyzedDuplexes; float[] averageClipping; int averageClippingOffset = Integer.MAX_VALUE; final @NonNull THashMap<String, @NonNull ExtendedSAMRecord> extSAMCache = new THashMap<>(10_000, 0.5f); private final AtomicInteger threadCount = new AtomicInteger(); @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") @NonNull Map<@NonNull ExtendedSAMRecord, @NonNull SAMRecord> readsToWrite = new THashMap<>(); private final Random random; public static final @NonNull Set<@NonNull DuplexAssay> ASSAYS_TO_IGNORE_FOR_DISAGREEMENT_QUALITY = Collections.unmodifiableSet(EnumSet.of(DISAGREEMENT)), ASSAYS_TO_IGNORE_FOR_DUPLEX_NSTRANDS = Collections.unmodifiableSet(EnumSet.of(N_READS_PER_STRAND, MISSING_STRAND, DuplexAssay.TOTAL_N_READS_Q2)); static final @NonNull TByteObjectMap<@NonNull String> byteMap; static { byteMap = new TByteObjectHashMap<>(); Assert.isNull(byteMap.put((byte) 'A', "A")); Assert.isNull(byteMap.put((byte) 'a', "A")); Assert.isNull(byteMap.put((byte) 'T', "T")); Assert.isNull(byteMap.put((byte) 't', "T")); Assert.isNull(byteMap.put((byte) 'G', "G")); Assert.isNull(byteMap.put((byte) 'g', "G")); Assert.isNull(byteMap.put((byte) 'C', "C")); Assert.isNull(byteMap.put((byte) 'c', "C")); Assert.isNull(byteMap.put((byte) 'N', "N")); Assert.isNull(byteMap.put((byte) 'n', "N")); Assert.isNull(byteMap.put((byte) 'W', "W")); Assert.isNull(byteMap.put((byte) 'w', "W")); Assert.isNull(byteMap.put((byte) 'S', "S")); Assert.isNull(byteMap.put((byte) 's', "S")); Assert.isNull(byteMap.put((byte) 'Y', "Y")); Assert.isNull(byteMap.put((byte) 'y', "Y")); Assert.isNull(byteMap.put((byte) 'R', "R")); Assert.isNull(byteMap.put((byte) 'r', "R")); Assert.isNull(byteMap.put((byte) 'B', "B")); Assert.isNull(byteMap.put((byte) 'b', "B")); Assert.isNull(byteMap.put((byte) 'D', "D")); Assert.isNull(byteMap.put((byte) 'd', "D")); Assert.isNull(byteMap.put((byte) 'H', "H")); Assert.isNull(byteMap.put((byte) 'h', "H")); Assert.isNull(byteMap.put((byte) 'K', "K")); Assert.isNull(byteMap.put((byte) 'k', "K")); Assert.isNull(byteMap.put((byte) 'M', "M")); Assert.isNull(byteMap.put((byte) 'm', "M")); Assert.isNull(byteMap.put((byte) 'V', "V")); Assert.isNull(byteMap.put((byte) 'v', "V")); } static final @NonNull TByteObjectMap<byte @NonNull[]> byteArrayMap; static { byteArrayMap = new TByteObjectHashMap<>(); Assert.isNull(byteArrayMap.put((byte) 'A', new byte[] {'A'})); Assert.isNull(byteArrayMap.put((byte) 'a', new byte[] {'a'})); Assert.isNull(byteArrayMap.put((byte) 'T', new byte[] {'T'})); Assert.isNull(byteArrayMap.put((byte) 't', new byte[] {'t'})); Assert.isNull(byteArrayMap.put((byte) 'G', new byte[] {'G'})); Assert.isNull(byteArrayMap.put((byte) 'g', new byte[] {'g'})); Assert.isNull(byteArrayMap.put((byte) 'C', new byte[] {'C'})); Assert.isNull(byteArrayMap.put((byte) 'c', new byte[] {'c'})); Assert.isNull(byteArrayMap.put((byte) 'N', new byte[] {'N'})); Assert.isNull(byteArrayMap.put((byte) 'n', new byte[] {'n'})); Assert.isNull(byteArrayMap.put((byte) 'W', new byte[] {'W'})); Assert.isNull(byteArrayMap.put((byte) 'w', new byte[] {'w'})); Assert.isNull(byteArrayMap.put((byte) 'S', new byte[] {'S'})); Assert.isNull(byteArrayMap.put((byte) 's', new byte[] {'s'})); Assert.isNull(byteArrayMap.put((byte) 'Y', new byte[] {'Y'})); Assert.isNull(byteArrayMap.put((byte) 'y', new byte[] {'y'})); Assert.isNull(byteArrayMap.put((byte) 'R', new byte[] {'R'})); Assert.isNull(byteArrayMap.put((byte) 'r', new byte[] {'r'})); Assert.isNull(byteArrayMap.put((byte) 'B', new byte[] {'B'})); Assert.isNull(byteArrayMap.put((byte) 'D', new byte[] {'D'})); Assert.isNull(byteArrayMap.put((byte) 'H', new byte[] {'H'})); Assert.isNull(byteArrayMap.put((byte) 'K', new byte[] {'K'})); Assert.isNull(byteArrayMap.put((byte) 'M', new byte[] {'M'})); Assert.isNull(byteArrayMap.put((byte) 'V', new byte[] {'V'})); Assert.isNull(byteArrayMap.put((byte) 'b', new byte[] {'b'})); Assert.isNull(byteArrayMap.put((byte) 'd', new byte[] {'d'})); Assert.isNull(byteArrayMap.put((byte) 'h', new byte[] {'h'})); Assert.isNull(byteArrayMap.put((byte) 'k', new byte[] {'k'})); Assert.isNull(byteArrayMap.put((byte) 'm', new byte[] {'m'})); Assert.isNull(byteArrayMap.put((byte) 'v', new byte[] {'v'})); } private volatile boolean writing = false; synchronized void queueOutputRead(@NonNull ExtendedSAMRecord e, @NonNull SAMRecord r, boolean mayAlreadyBeQueued) { Assert.isFalse(writing); final SAMRecord previous; if ((previous = readsToWrite.put(e, r)) != null && !mayAlreadyBeQueued) { throw new IllegalStateException("Read " + e.getFullName() + " already queued for writing; new: " + r.toString() + "; previous: " + previous.toString()); } } void writeOutputReads() { Assert.isFalse(writing); writing = true; try { synchronized(analyzer.outputAlignmentWriter) { for (SAMRecord samRecord: readsToWrite.values()) { Objects.requireNonNull(analyzer.outputAlignmentWriter).addAlignment(samRecord); } } readsToWrite.clear(); } finally { writing = false; } } @SuppressWarnings("null")//Stats not initialized straight away SubAnalyzer(@NonNull Mutinack analyzer) { this.analyzer = analyzer; this.param = analyzer.param; useHashMap = param.alignmentPositionMismatchAllowed == 0; random = new Random(param.randomSeed); } private boolean meetsQ2Thresholds(@NonNull ExtendedSAMRecord extendedRec) { return !extendedRec.formsWrongPair() && extendedRec.getnClipped() <= param.maxAverageBasesClipped && extendedRec.getMappingQuality() >= param.minMappingQualityQ2 && Math.abs(extendedRec.getInsertSize()) <= param.maxInsertSize; } /** * Make sure that concurring reads get associated with a unique candidate. * We should *not* insert candidates directly into candidateSequences. * Get interning as a small, beneficial side effect. * @param candidate * @param location * @return */ private @NonNull CandidateSequence insertCandidateAtPosition(@NonNull CandidateSequence candidate, @NonNull SequenceLocation location) { //No need for synchronization since we should not be //concurrently inserting two candidates at the same position THashSet<CandidateSequence> candidates = candidateSequences.computeIfAbsent(location, k -> new THashSet<>(2, 0.2f)); CandidateSequence candidateMapValue = candidates.get(candidate); if (candidateMapValue == null) { boolean added = candidates.add(candidate); Assert.isTrue(added); } else { candidateMapValue.mergeWith(candidate); candidate = candidateMapValue; } return candidate; } /** * Load all reads currently referred to by candidate sequences and group them into DuplexReads * @param toPosition * @param fromPosition */ void load(int fromPosition, int toPosition) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { if (toPosition < fromPosition) { throw new IllegalArgumentException("Going from " + fromPosition + " to " + toPosition); } final MutableList<@NonNull Duplex> resultDuplexes = new FastList<>(3_000); loadAll(fromPosition, toPosition, resultDuplexes); analyzedDuplexes = resultDuplexes; } finally { if (NONTRIVIAL_ASSERTIONS) { threadCount.decrementAndGet(); } } } void checkAllDone() { if (!candidateSequences.isEmpty()) { final SettableInteger nLeftBehind = new SettableInteger(-1); candidateSequences.forEach((k,v) -> { Assert.isTrue(v.isEmpty() || (v.iterator().next().getLocation().equals(k)), "Mismatched locations"); String s = v.stream(). filter(c -> c.getLocation().position > truncateProcessingAt + param.maxInsertSize && c.getLocation().position < startProcessingAt - param.maxInsertSize). flatMap(v0 -> v0.getNonMutableConcurringReads().keySet().stream()). map(read -> { if (nLeftBehind.incrementAndGet() == 0) { logger.error("Sequences left behind before " + truncateProcessingAt); } return Integer.toString(read.getAlignmentStart()) + '-' + Integer.toString(read.getAlignmentEnd()); }) .collect(Collectors.joining("; ")); if (!s.equals("")) { logger.error(s); } }); Assert.isFalse(nLeftBehind.get() > 0); } } private final boolean useHashMap; private @NonNull DuplexKeeper getDuplexKeeper(boolean fallBackOnIntervalTree) { final @NonNull DuplexKeeper result; if (MutinackGroup.forceKeeperType != null) { switch(MutinackGroup.forceKeeperType) { case "DuplexHashMapKeeper": if (useHashMap) { result = new DuplexHashMapKeeper(); } else { result = new DuplexArrayListKeeper(5_000); } break; //case "DuplexITKeeper": // result = new DuplexITKeeper(); // break; case "DuplexArrayListKeeper": result = new DuplexArrayListKeeper(5_000); break; default: throw new AssertionFailedException(); } } else { if (useHashMap) { result = new DuplexHashMapKeeper(); } else /*if (fallBackOnIntervalTree) { result = new DuplexITKeeper(); } else */{ result = new DuplexArrayListKeeper(5_000); } } return result; } /** * Group reads into duplexes. * @param toPosition * @param fromPosition * @param finalResult */ private void loadAll( final int fromPosition, final int toPosition, final @NonNull List<Duplex> finalResult) { /** * Use a custom hash map type to keep track of duplexes when * alignmentPositionMismatchAllowed is 0. * This provides by far the highest performance. * When alignmentPositionMismatchAllowed is greater than 0, use * either an interval tree or a plain list. The use of an interval * tree instead of a plain list provides a speed benefit only when * there is large number of local duplexes, so switch dynamically * based on that number. The threshold was optimized empirically * and at a gross level. */ final boolean fallBackOnIntervalTree = extSAMCache.size() > 5_000; @NonNull DuplexKeeper duplexKeeper = getDuplexKeeper(fallBackOnIntervalTree); InterningSet<SequenceLocation> sequenceLocationCache = new InterningSet<>(500); final AlignmentExtremetiesDistance ed = new AlignmentExtremetiesDistance( analyzer.groupSettings, param); final SettableInteger nReadsExcludedFromDuplexes = new SettableInteger(0); final TObjectProcedure<@NonNull ExtendedSAMRecord> callLoadRead = rExtended -> { loadRead(rExtended, duplexKeeper, ed, sequenceLocationCache, nReadsExcludedFromDuplexes); return true; }; if (param.jiggle) { List<@NonNull ExtendedSAMRecord> reorderedReads = new ArrayList<>(extSAMCache.values()); Collections.shuffle(reorderedReads, random); reorderedReads.forEach(callLoadRead::execute); } else { extSAMCache.forEachValue(callLoadRead); } sequenceLocationCache.clear();//Not strictly necessary, but might as well release the //memory now if (param.randomizeStrand) { duplexKeeper.forEach(dr -> dr.randomizeStrands(random)); } duplexKeeper.forEach(Duplex::computeGlobalProperties); Pair<Duplex, Duplex> pair; if (param.enableCostlyAssertions && (pair = Duplex.checkNoEqualDuplexes(duplexKeeper)) != null) { throw new AssertionFailedException("Equal duplexes: " + pair.fst + " and " + pair.snd); } if (param.enableCostlyAssertions) { Assert.isTrue(checkReadsOccurOnceInDuplexes(extSAMCache.values(), duplexKeeper, nReadsExcludedFromDuplexes.get())); } //Group duplexes that have alignment positions that differ by at most //param.alignmentPositionMismatchAllowed //and left/right consensus that differ by at most //param.nVariableBarcodeMismatchesAllowed final DuplexKeeper cleanedUpDuplexes; if (param.nVariableBarcodeMismatchesAllowed > 0 /*&& duplexKeeper.size() < analyzer.maxNDuplexes*/) { cleanedUpDuplexes = Duplex.groupDuplexes( duplexKeeper, duplex -> duplex.computeConsensus(false, param.variableBarcodeLength), () -> getDuplexKeeper(fallBackOnIntervalTree), param, stats, 0); } else { cleanedUpDuplexes = duplexKeeper; cleanedUpDuplexes.forEach(Duplex::computeGlobalProperties); } if (param.nVariableBarcodeMismatchesAllowed == 0) { cleanedUpDuplexes.forEach(d -> d.computeConsensus(true, param.variableBarcodeLength)); } if (param.variableBarcodeLength == 0) { //Group duplexes by alignment start (or equivalent) TIntObjectHashMap<List<Duplex>> duplexPositions = new TIntObjectHashMap<> (1_000, 0.5f, -999); cleanedUpDuplexes.forEach(dr -> { List<Duplex> list = duplexPositions.computeIfAbsent(dr.leftAlignmentStart.position, (Supplier<List<Duplex>>) ArrayList::new); list.add(dr); }); final double @NonNull[] insertSizeProb = Objects.requireNonNull(analyzer.insertSizeProbSmooth); duplexPositions.forEachValue(list -> { for (Duplex dr: list) { double sizeP = insertSizeProb[ Math.min(insertSizeProb.length - 1, dr.maxInsertSize)]; Assert.isTrue(Double.isNaN(sizeP) || sizeP >= 0, () -> "Insert size problem: " + Arrays.toString(insertSizeProb)); dr.probAtLeastOneCollision = 1 - Math.pow(1 - sizeP, list.size()); } return true; }); } cleanedUpDuplexes.forEach(duplexRead -> duplexRead.analyzeForStats(param, stats)); cleanedUpDuplexes.forEach(finalResult::add); averageClippingOffset = fromPosition; final int arrayLength = toPosition - fromPosition + 1; averageClipping = new float[arrayLength]; int[] duplexNumber = new int[arrayLength]; cleanedUpDuplexes.forEach(duplexRead -> { int start = duplexRead.getUnclippedAlignmentStart() - fromPosition; int stop = duplexRead.getUnclippedAlignmentEnd() - fromPosition; start = Math.min(Math.max(0, start), toPosition - fromPosition); stop = Math.min(Math.max(0, stop), toPosition - fromPosition); for (int i = start; i <= stop; i++) { averageClipping[i] += duplexRead.averageNClipped; duplexNumber[i]++; } }); insertDuplexGroupSizeStats(cleanedUpDuplexes, 0, stats.duplexLocalGroupSize); insertDuplexGroupSizeStats(cleanedUpDuplexes, 15, stats.duplexLocalShiftedGroupSize); if (param.computeDuplexDistances && cleanedUpDuplexes.size() < analyzer.maxNDuplexes) { cleanedUpDuplexes.forEach(d1 -> cleanedUpDuplexes.forEach(d2 -> stats.duplexDistance.insert(d1.euclideanDistanceTo(d2)))); } for (int i = 0; i < averageClipping.length; i++) { int n = duplexNumber[i]; if (n == 0) { Assert.isTrue(averageClipping[i] == 0); } else { averageClipping[i] /= n; } } }//End loadAll private static void insertDuplexGroupSizeStats(DuplexKeeper keeper, int offset, Histogram stats) { keeper.forEach(duplexRead -> { duplexRead.assignedToLocalGroup = duplexRead.leftAlignmentStart.position == ExtendedSAMRecord.NO_MATE_POSITION || duplexRead.rightAlignmentEnd.position == ExtendedSAMRecord.NO_MATE_POSITION;//Ignore duplexes from reads that //have a missing mate }); keeper.forEach(duplexRead -> { if (!duplexRead.assignedToLocalGroup) { int groupSize = countDuplexesInWindow(duplexRead, keeper, offset, 5); stats.insert(groupSize); duplexRead.assignedToLocalGroup = true; } }); } private static int countDuplexesInWindow(Duplex d, DuplexKeeper dk, int offset, int windowWidth) { SettableInteger result = new SettableInteger(0); dk.getOverlappingWithSlop(d, offset, windowWidth).forEach(od -> { if (od.assignedToLocalGroup) { return; } int distance1 = od.rightAlignmentEnd.position - (d.rightAlignmentEnd.position + offset); if (Math.abs(distance1) <= windowWidth) { Assert.isTrue(Math.abs(distance1) <= windowWidth + Math.abs(offset)); int distance2 = od.leftAlignmentStart.position - (d.leftAlignmentStart.position + offset); if (Math.abs(distance2) <= windowWidth) { od.assignedToLocalGroup = true; if (distance1 != 0 && distance2 != 0) { result.incrementAndGet(); } } } }); return result.get(); } private void loadRead(@NonNull ExtendedSAMRecord rExtended, @NonNull DuplexKeeper duplexKeeper, AlignmentExtremetiesDistance ed, InterningSet<SequenceLocation> sequenceLocationCache, SettableInteger nReadsExcludedFromDuplexes) { final @NonNull SequenceLocation location = rExtended.getLocation(); final byte @NonNull[] barcode = rExtended.variableBarcode; final byte @NonNull[] mateBarcode = rExtended.getMateVariableBarcode(); final @NonNull SAMRecord r = rExtended.record; if (rExtended.getMate() == null) { stats.nMateOutOfReach.add(location, 1); } if (r.getMateUnmappedFlag()) { //It is not trivial to tell whether the mate is unmapped because //e.g. it did not sequence properly, or because all of the reads //from the duplex just do not map to the genome. To avoid //artificially inflating local duplex number, do not allow the //read to contribute to computed duplexes. Note that the rest of //the duplex-handling code could technically handle an unmapped //mate, and that the read will still be able to contribute to //local statistics such as average clipping. nReadsExcludedFromDuplexes.incrementAndGet(); return; } boolean foundDuplexRead = false; final boolean matchToLeft = rExtended.duplexLeft(); ed.set(rExtended); for (final Duplex duplex: duplexKeeper.getOverlapping(ed.temp)) { //stats.nVariableBarcodeCandidateExaminations.increment(location); boolean forceGrouping = false; if (duplex.allRecords.detect(drRec -> drRec.record.getReadName().equals(r.getReadName())) != null) { forceGrouping = true; } ed.set(duplex); if (!forceGrouping && ed.getMaxDistance() > param.alignmentPositionMismatchAllowed) { continue; } final boolean barcodeMatch; //During first pass, do not allow any barcode mismatches if (forceGrouping) { barcodeMatch = true; } else if (matchToLeft) { barcodeMatch = basesEqual(duplex.leftBarcode, barcode, param.acceptNInBarCode) && basesEqual(duplex.rightBarcode, mateBarcode, param.acceptNInBarCode); } else { barcodeMatch = basesEqual(duplex.leftBarcode, mateBarcode, param.acceptNInBarCode) && basesEqual(duplex.rightBarcode, barcode, param.acceptNInBarCode); } //noinspection StatementWithEmptyBody if (forceGrouping || barcodeMatch) { if (r.getInferredInsertSize() >= 0) { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.topStrandRecords.contains(rExtended)); } duplex.topStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.bottomStrandRecords.contains(rExtended)); } duplex.bottomStrandRecords.add(rExtended); } } else { if (r.getFirstOfPairFlag()) { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.bottomStrandRecords.contains(rExtended)); } duplex.bottomStrandRecords.add(rExtended); } else { if (param.enableCostlyAssertions) { Assert.isFalse(duplex.topStrandRecords.contains(rExtended)); } duplex.topStrandRecords.add(rExtended); } } if (param.enableCostlyAssertions) {//XXX May fail if there was a barcode //read error and duplex grouping was forced for mate Assert.noException(duplex::assertAllBarcodesEqual); } rExtended.duplex = duplex; //stats.nVariableBarcodeMatchAfterPositionCheck.increment(location); foundDuplexRead = true; break; } else {//left and/or right barcodes do not match /* leftEqual = basesEqual(duplexRead.leftBarcode, barcode, true, 1); rightEqual = basesEqual(duplexRead.rightBarcode, barcode, true, 1); if (leftEqual || rightEqual) { stats.nVariableBarcodesCloseMisses.increment(location); }*/ } }//End loop over duplexReads if (!foundDuplexRead) { final Duplex duplex = matchToLeft ? new Duplex(analyzer.groupSettings, barcode, mateBarcode, !r.getReadNegativeStrandFlag(), r.getReadNegativeStrandFlag()) : new Duplex(analyzer.groupSettings, mateBarcode, barcode, r.getReadNegativeStrandFlag(), !r.getReadNegativeStrandFlag()); duplex.roughLocation = location; rExtended.duplex = duplex; if (!matchToLeft) { if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (!r.getFirstOfPairFlag()) { duplex.topStrandRecords.add(rExtended); } else { duplex.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplex::assertAllBarcodesEqual); } duplex.rightAlignmentStart = sequenceLocationCache.intern( rExtended.getOffsetUnclippedStartLoc()); duplex.rightAlignmentEnd = sequenceLocationCache.intern( rExtended.getOffsetUnclippedEndLoc()); duplex.leftAlignmentStart = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedStartLoc()); duplex.leftAlignmentEnd = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedEndLoc()); } else {//Read on positive strand if (rExtended.getMateAlignmentStart() == rExtended.getAlignmentStart()) { //Reads that completely overlap because of short insert size? stats.nPosDuplexCompletePairOverlap.increment(location); } //Arbitrarily choose top strand as the one associated with //first of pair that maps to the lowest position in the contig if (r.getFirstOfPairFlag()) { duplex.topStrandRecords.add(rExtended); } else { duplex.bottomStrandRecords.add(rExtended); } if (param.enableCostlyAssertions) { Assert.noException(duplex::assertAllBarcodesEqual); } duplex.leftAlignmentStart = sequenceLocationCache.intern( rExtended.getOffsetUnclippedStartLoc()); duplex.leftAlignmentEnd = sequenceLocationCache.intern( rExtended.getOffsetUnclippedEndLoc()); duplex.rightAlignmentStart = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedStartLoc()); duplex.rightAlignmentEnd = sequenceLocationCache.intern( rExtended.getMateOffsetUnclippedEndLoc()); } duplexKeeper.add(duplex); if (false) //noinspection RedundantCast Assert.isFalse( /* There are funny alignments that can trigger this assert; but it should not hurt for alignment start and end to be switched, since it should happen in the same fashion for all reads in a duplex */ duplex.leftAlignmentEnd.contigIndex == duplex.leftAlignmentStart.contigIndex && duplex.leftAlignmentEnd.compareTo(duplex.leftAlignmentStart) < 0, (Supplier<Object>) duplex.leftAlignmentStart::toString, (Supplier<Object>) duplex.leftAlignmentEnd::toString, (Supplier<Object>) duplex::toString, (Supplier<Object>) rExtended::getFullName, "Misordered duplex: %s -- %s %s %s"); }//End new duplex creation if (param.enableCostlyAssertions) { Duplex.checkNoEqualDuplexes(duplexKeeper); } } private static boolean checkReadsOccurOnceInDuplexes( Collection<@NonNull ExtendedSAMRecord> reads, @NonNull Iterable<Duplex> duplexes, int nReadsExcludedFromDuplexes) { ExtendedSAMRecord lostRead = null; int nUnfoundReads = 0; for (final @NonNull ExtendedSAMRecord rExtended: reads) { boolean found = false; for (Duplex dr: duplexes) { if (dr.topStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } if (dr.bottomStrandRecords.contains(rExtended)) { if (found) { throw new AssertionFailedException("Two occurrences of read " + rExtended); } found = true; } } if (!found) { nUnfoundReads++; lostRead = rExtended; } } if (nUnfoundReads != nReadsExcludedFromDuplexes) { throw new AssertionFailedException("Lost " + nUnfoundReads + " but expected " + nReadsExcludedFromDuplexes + "; see perhaps " + lostRead); } return true; } @NonNull LocationExaminationResults examineLocation(final @NonNull SequenceLocation location) { Assert.isFalse(threadCount.incrementAndGet() > 1); try { return examineLocation0(location); } finally { threadCount.decrementAndGet(); } } @SuppressWarnings({"null", "ReferenceEquality"}) /** * This method is *NOT* thread-safe (it modifies DuplexReads associated with location retrieved * from field candidateSequences) * @param location * @return */ @NonNull private LocationExaminationResults examineLocation0(final @NonNull SequenceLocation location) { final LocationExaminationResults result = new LocationExaminationResults(); final THashSet<CandidateSequence> candidateSet0 = candidateSequences.get(location); if (candidateSet0 == null) { stats.nPosUncovered.increment(location); result.analyzedCandidateSequences = Sets.immutable.empty(); return result; } final ImmutableSet<CandidateSequence> candidateSet = // DebugLogControl.COSTLY_ASSERTIONS ? // Collections.unmodifiableSet(candidateSet0) // : Sets.immutable.ofAll(candidateSet0); //Retrieve relevant duplex reads //It is necessary not to duplicate the duplex reads, hence the use of a set //Identity should be good enough (and is faster) because no two different duplex read //objects we use in this method should be equal according to the equals() method //(although when grouping duplexes we don't check equality for the inner ends of //the reads since they depend on read length) final TCustomHashSet<Duplex> duplexes = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); candidateSet.forEach(candidate -> { candidate.reset(); final Set<Duplex> candidateDuplexReads = new TCustomHashSet<>(HashingStrategies.identityHashingStrategy, 200); List<ExtendedSAMRecord> discarded = Lists.mutable.empty(); candidate.getMutableConcurringReads().retainEntries((r, c) -> { if (r.discarded) { discarded.add(r); return false; } if (param.filterOpticalDuplicates) { if (r.isOpticalDuplicate()) { return false; } } @Nullable Duplex d = r.duplex; //noinspection StatementWithEmptyBody if (d != null) { candidateDuplexReads.add(d); } else { //throw new AssertionFailedException("Read without a duplex :" + r); } return true; }); discarded.forEach(candidate.getMutableConcurringReads()::remove); if (param.enableCostlyAssertions) { checkDuplexes(candidateDuplexReads); } duplexes.addAll(candidateDuplexReads); }); //Allocate here to avoid repeated allocation in DuplexRead::examineAtLoc final CandidateCounter topCounter = new CandidateCounter(candidateSet, location); final CandidateCounter bottomCounter = new CandidateCounter(candidateSet, location); int[] insertSizes = new int [duplexes.size()]; SettableDouble averageCollisionProbS = new SettableDouble(0d); SettableInteger index = new SettableInteger(0); duplexes.forEach(duplexRead -> { Assert.isFalse(duplexRead.invalid); Assert.isTrue(duplexRead.averageNClipped >= 0, () -> duplexRead.toString()); Assert.isTrue(param.variableBarcodeLength > 0 || Double.isNaN(duplexRead.probAtLeastOneCollision) || duplexRead.probAtLeastOneCollision >= 0); duplexRead.examineAtLoc( location, result, candidateSet, topCounter, bottomCounter, analyzer, param, stats); if (index.get() < insertSizes.length) { //Check in case array size was capped (for future use; it is //never capped currently) insertSizes[index.get()] = duplexRead.maxInsertSize; index.incrementAndGet(); } averageCollisionProbS.addAndGet(duplexRead.probAtLeastOneCollision); if (param.variableBarcodeLength == 0 && !duplexRead.missingStrand) { stats.duplexCollisionProbabilityWhen2Strands.insert((int) (1_000f * duplexRead.probAtLeastOneCollision)); } }); if (param.enableCostlyAssertions) { Assert.noException(() -> checkDuplexAndCandidates(duplexes, candidateSet)); candidateSet.forEach(candidate -> checkCandidateDupNoQ(candidate, location)); } if (index.get() > 0) { Arrays.parallelSort(insertSizes, 0, index.get()); result.duplexInsertSize10thP = insertSizes[(int) (index.get() * 0.1f)]; result.duplexInsertSize90thP = insertSizes[(int) (index.get() * 0.9f)]; } double averageCollisionProb = averageCollisionProbS.get(); averageCollisionProb /= duplexes.size(); if (param.variableBarcodeLength == 0) { stats.duplexCollisionProbability.insert((int) (1_000d * averageCollisionProb)); } result.probAtLeastOneCollision = averageCollisionProb; final DetailedQualities<PositionAssay> positionQualities = new DetailedPositionQualities(); if (averageClipping[location.position - averageClippingOffset] > param.maxAverageClippingOfAllCoveringDuplexes) { positionQualities.addUnique( MAX_AVERAGE_CLIPPING_OF_DUPLEX_AT_POS, DUBIOUS); } if (param.enableCostlyAssertions) { Assert.noException(() -> duplexes.forEach((Consumer<Duplex>) Duplex::checkReadOwnership)); } final int totalReadsAtPosition = (int) candidateSet.sumOfInt( c -> c.getNonMutableConcurringReads().size()); final TByteArrayList allPhredQualitiesAtPosition = new TByteArrayList(500); final SettableInteger nWrongPairsAtPosition = new SettableInteger(0); final SettableInteger nPairsAtPosition = new SettableInteger(0); candidateSet.forEach(candidate -> { candidate.addPhredScoresToList(allPhredQualitiesAtPosition); nPairsAtPosition.addAndGet(candidate.getNonMutableConcurringReads().size()); SettableInteger count = new SettableInteger(0); candidate.getNonMutableConcurringReads().forEachKey(r -> { if (r.formsWrongPair()) { count.incrementAndGet(); } return true; }); candidate.setnWrongPairs(count.get()); nWrongPairsAtPosition.addAndGet(candidate.getnWrongPairs()); }); final int nPhredQualities = allPhredQualitiesAtPosition.size(); allPhredQualitiesAtPosition.sort(); final byte positionMedianPhred = nPhredQualities == 0 ? 127 : allPhredQualitiesAtPosition.get(nPhredQualities / 2); if (positionMedianPhred < param.minMedianPhredScoreAtPosition) { positionQualities.addUnique(MEDIAN_PHRED_AT_POS, DUBIOUS); stats.nMedianPhredAtPositionTooLow.increment(location); } stats.medianPositionPhredQuality.insert(positionMedianPhred); if (nWrongPairsAtPosition.get() / ((float) nPairsAtPosition.get()) > param.maxFractionWrongPairsAtPosition) { positionQualities.addUnique(FRACTION_WRONG_PAIRS_AT_POS, DUBIOUS); stats.nFractionWrongPairsAtPositionTooHigh.increment(location); } Handle<Byte> wildtypeBase = new Handle<>((byte) 'X'); candidateSet.forEach(candidate -> { candidate.getQuality().addAllUnique(positionQualities); processCandidateQualityStep1(candidate, result, positionMedianPhred, positionQualities); if (candidate.getMutationType().isWildtype()) { wildtypeBase.set(candidate.getWildtypeSequence()); } }); Quality maxQuality; int totalGoodDuplexes, totalGoodOrDubiousDuplexes, totalGoodDuplexesIgnoringDisag, totalAllDuplexes; boolean leave = false; final boolean qualityOKBeforeTopAllele = Quality.nullableMax(positionQualities.getValue(true), GOOD).atLeast(GOOD); Quality topAlleleQuality = null; //noinspection UnnecessaryBoxing do { maxQuality = MINIMUM; totalAllDuplexes = 0; totalGoodDuplexes = 0; totalGoodOrDubiousDuplexes = 0; totalGoodDuplexesIgnoringDisag = 0; for (CandidateSequence candidate: candidateSet) { if (leave) { candidate.getQuality().addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, DUBIOUS); } @NonNull MutableSetMultimap<Quality, Duplex> map = candidate.getDuplexes(). groupBy(dr -> candidate.filterQuality(dr.localAndGlobalQuality)); if (param.enableCostlyAssertions) { map.forEachKeyMultiValues((k, v) -> Assert.isTrue(Util.getDuplicates(v).isEmpty())); Assert.isTrue(map.multiValuesView().collectInt(RichIterable::size).sum() == candidate.getDuplexes().size()); } @Nullable MutableSet<Duplex> gd = map.get(GOOD); candidate.setnGoodDuplexes(gd == null ? 0 : gd.size()); @Nullable MutableSet<Duplex> db = map.get(DUBIOUS); candidate.setnGoodOrDubiousDuplexes(candidate.getnGoodDuplexes() + (db == null ? 0 : db.size())); candidate.setnGoodDuplexesIgnoringDisag(candidate.getDuplexes(). count(dr -> dr.localAndGlobalQuality.getValueIgnoring(ASSAYS_TO_IGNORE_FOR_DISAGREEMENT_QUALITY).atLeast(GOOD))); maxQuality = max(candidate.getQuality().getValue(), maxQuality); totalAllDuplexes += candidate.getnDuplexes(); totalGoodDuplexes += candidate.getnGoodDuplexes(); totalGoodOrDubiousDuplexes += candidate.getnGoodOrDubiousDuplexes(); totalGoodDuplexesIgnoringDisag += candidate.getnGoodDuplexesIgnoringDisag(); processCandidateQualityStep2(candidate, location); } if (leave) { break; } else { result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; topAlleleQuality = getAlleleFrequencyQuality(candidateSet, result); if (topAlleleQuality == null) { break; } Assert.isTrue(topAlleleQuality == DUBIOUS); positionQualities.addUnique(PositionAssay.TOP_ALLELE_FREQUENCY, topAlleleQuality); leave = true;//Just one more iteration //noinspection UnnecessaryContinue continue; } } while (Boolean.valueOf(null));//Assert never reached if (qualityOKBeforeTopAllele) { registerDuplexMinFracTopCandidate(duplexes, topAlleleQuality == null ? stats.minTopCandFreqQ2PosTopAlleleFreqOK : stats.minTopCandFreqQ2PosTopAlleleFreqKO ); } if (positionQualities.getValue(true) != null && positionQualities.getValue(true).lowerThan(GOOD)) { result.disagreements.clear(); } else { if (param.maxMutFreqForDisag < 1f) { final int finalTotalGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.disagreements.forEachKey(disag -> { Mutation m = disag.getSnd(); if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } m = disag.getFst(); if (m != null && m.mutationType != WILDTYPE) { if (!(lowMutFreq(m, candidateSet, finalTotalGoodOrDubiousDuplexes))) { disag.quality = Quality.min(disag.quality, POOR); } } return true; }); } stats.nPosDuplexCandidatesForDisagreementQ2.acceptSkip0(location, result.disagQ2Coverage); stats.nPosDuplexCandidatesForDisagreementQ1.acceptSkip0(location, result.disagOneStrandedCoverage); if (param.computeRawMismatches) { candidateSet.forEach(c -> result.rawMismatchesQ2.addAll(c.getRawMismatchesQ2())); candidateSet.forEach(c -> result.rawInsertionsQ2.addAll(c.getRawInsertionsQ2())); candidateSet.forEach(c -> result.rawDeletionsQ2.addAll(c.getRawDeletionsQ2())); } } for (CandidateSequence candidate: candidateSet) { candidate.setTotalAllDuplexes(totalAllDuplexes); candidate.setTotalGoodDuplexes(totalGoodDuplexes); candidate.setTotalGoodOrDubiousDuplexes(totalGoodOrDubiousDuplexes); candidate.setTotalReadsAtPosition(totalReadsAtPosition); final long topReads = candidate.getDuplexes().sumOfInt(d -> d.topStrandRecords.size()); final float bottomReads = candidate.getDuplexes().sumOfInt(d -> d.bottomStrandRecords.size()); candidate.setFractionTopStrandReads(topReads / (topReads + bottomReads)); candidate.setTopAndBottomStrandsPresent(topReads > 0 && bottomReads > 0); } result.nGoodOrDubiousDuplexes = totalGoodOrDubiousDuplexes; result.nGoodDuplexes = totalGoodDuplexes; result.nGoodDuplexesIgnoringDisag = totalGoodDuplexesIgnoringDisag; stats.Q1Q2DuplexCoverage.insert(result.nGoodOrDubiousDuplexes); stats.Q2DuplexCoverage.insert(result.nGoodDuplexes); if (result.nGoodOrDubiousDuplexes == 0) { stats.missingStrandsWhenNoUsableDuplex.insert(result.nMissingStrands); stats.strandCoverageImbalanceWhenNoUsableDuplex.insert(result.strandCoverageImbalance); } if (maxQuality.atMost(POOR)) { stats.nPosQualityPoor.increment(location); switch (wildtypeBase.get()) { case 'A' : stats.nPosQualityPoorA.increment(location); break; case 'T' : stats.nPosQualityPoorT.increment(location); break; case 'G' : stats.nPosQualityPoorG.increment(location); break; case 'C' : stats.nPosQualityPoorC.increment(location); break; case 'X' : case 'N' : break;//Ignore because we do not have a record of wildtype sequence default : throw new AssertionFailedException(); } } else if (maxQuality == DUBIOUS) { stats.nPosQualityQ1.increment(location); } else if (maxQuality == GOOD) { stats.nPosQualityQ2.increment(location); } else { throw new AssertionFailedException(); } result.analyzedCandidateSequences = candidateSet; return result; }//End examineLocation private static void registerDuplexMinFracTopCandidate(TCustomHashSet<Duplex> duplexes, Histogram hist) { duplexes.forEach(dr -> { if (dr.allRecords.size() < 2 || dr.minFracTopCandidate == Float.MAX_VALUE) { return true; } hist.insert((int) (dr.minFracTopCandidate * 10)); return true; }); } private boolean lowMutFreq(Mutation mut, ImmutableSet<CandidateSequence> candidateSet, int nGOrDDuplexes) { Objects.requireNonNull(mut); Handle<Boolean> result = new Handle<>(true); candidateSet.detect((CandidateSequence c) -> { Mutation cMut = c.getMutation(); if (cMut.equals(mut)) { if (c.getnGoodOrDubiousDuplexes() > param.maxMutFreqForDisag * nGOrDDuplexes) { result.set(false); } return true; } return false; }); return result.get(); } private static float divideWithNanToZero(float f1, float f2) { return f2 == 0f ? 0 : f1 / f2; } private @Nullable Quality getAlleleFrequencyQuality( ImmutableSet<CandidateSequence> candidateSet, LocationExaminationResults result) { MutableFloatList frequencyList = candidateSet.collectFloat(c -> divideWithNanToZero(c.getnGoodOrDubiousDuplexes(), result.nGoodOrDubiousDuplexes), new FloatArrayList(Math.max(2, candidateSet.size()))).//Need second argument to collectInt //to avoid collecting into a set sortThis(); result.alleleFrequencies = frequencyList; while (frequencyList.size() < 2) { frequencyList.addAtIndex(0, Float.NaN); } float topAlleleFrequency = frequencyList.getLast(); if (!(topAlleleFrequency >= param.minTopAlleleFreqQ2 && topAlleleFrequency <= param.maxTopAlleleFreqQ2)) { return DUBIOUS; } return null; } private static void checkCandidateDupNoQ(CandidateSequence candidate, SequenceLocation location) { candidate.getNonMutableConcurringReads().forEachKey(r -> { Duplex dr = r.duplex; if (dr != null) { if (dr.lastExaminedPosition != location.position) { throw new AssertionFailedException("Last examined position is " + dr.lastExaminedPosition + " instead of " + location.position + " for duplex " + dr); } if (r.discarded) { throw new AssertionFailedException("Discarded read " + r + " in duplex " + dr); } Assert.isTrue(dr.localAndGlobalQuality.getQuality(QUALITY_AT_POSITION) == null); Assert.isFalse(dr.invalid); } return true; }); } @SuppressWarnings("null") private void processCandidateQualityStep1( final CandidateSequence candidate, final LocationExaminationResults result, final byte positionMedianPhred, final @NonNull DetailedQualities<PositionAssay> positionQualities) { candidate.setMedianPhredAtPosition(positionMedianPhred); final byte candidateMedianPhred = candidate.getMedianPhredScore();//Will be -1 for insertions and deletions if (candidateMedianPhred != -1 && candidateMedianPhred < param.minCandidateMedianPhredScore) { candidate.getQuality().addUnique(MEDIAN_CANDIDATE_PHRED, DUBIOUS); } //TODO Should report min rather than average collision probability? candidate.setProbCollision((float) result.probAtLeastOneCollision); candidate.setInsertSizeAtPos10thP(result.duplexInsertSize10thP); candidate.setInsertSizeAtPos90thP(result.duplexInsertSize90thP); final MutableSet<Duplex> candidateDuplexes = candidate.computeSupportingDuplexes(); candidate.setDuplexes(candidateDuplexes); candidate.setnDuplexes(candidateDuplexes.size()); if (candidate.getnDuplexes() == 0) { candidate.getQuality().addUnique(NO_DUPLEXES, ATROCIOUS); } if (param.verbosity > 2) { candidateDuplexes.forEach(d -> candidate.getIssues().put(d, d.localAndGlobalQuality.toLong())); } final Quality posQMin = positionQualities.getValue(true); Handle<Quality> maxDuplexQHandle = new Handle<>(ATROCIOUS); candidateDuplexes.each(dr -> { if (posQMin != null) { dr.localAndGlobalQuality.addUnique(QUALITY_AT_POSITION, posQMin); } maxDuplexQHandle.set(max(maxDuplexQHandle.get(), candidate.filterQuality(dr.localAndGlobalQuality))); }); final @NonNull Quality maxDuplexQ = maxDuplexQHandle.get(); candidate.updateQualities(param); switch(param.candidateQ2Criterion) { case "1Q2Duplex": candidate.getQuality().addUnique(MAX_Q_FOR_ALL_DUPLEXES, maxDuplexQ); break; case "NQ1Duplexes": int duplexCount = candidateDuplexes.count(d -> d.localAndGlobalQuality.getValueIgnoring(ASSAYS_TO_IGNORE_FOR_DUPLEX_NSTRANDS).atLeast(GOOD) && d.allRecords.size() > 1 * 2); setNQ1DupQuality(candidate, duplexCount, param.minQ1Duplexes, param.minTotalReadsForNQ1Duplexes); break; default: throw new AssertionFailedException(); } if (PositionAssay.COMPUTE_MAX_DPLX_Q_IGNORING_DISAG) { candidateDuplexes.stream(). map(dr -> dr.localAndGlobalQuality.getValueIgnoring(ASSAYS_TO_IGNORE_FOR_DISAGREEMENT_QUALITY, true)). max(Quality::compareTo).ifPresent(q -> candidate.getQuality().addUnique(MAX_DPLX_Q_IGNORING_DISAG, q)); } if (maxDuplexQ.atLeast(DUBIOUS)) { candidateDuplexes.forEach(dr -> { if (dr.localAndGlobalQuality.getValue().atLeast(maxDuplexQ)) { candidate.acceptLigSiteDistance(dr.getMaxDistanceToLigSite()); } }); } } private static void setNQ1DupQuality(CandidateSequence candidate, int duplexCount, int minQ1Duplexes, int minTotalReads) { boolean good = duplexCount >= minQ1Duplexes && candidate.getNonMutableConcurringReads().size() >= minTotalReads; candidate.getQuality().addUnique(PositionAssay.N_Q1_DUPLEXES, good ? GOOD : DUBIOUS); } private void processCandidateQualityStep2( final CandidateSequence candidate, final @NonNull SequenceLocation location ) { if (false && !param.rnaSeq) { candidate.getNonMutableConcurringReads().forEachKey(r -> { final int refPosition = location.position; final int readPosition = r.referencePositionToReadPosition(refPosition); if (!r.formsWrongPair()) { final int distance = r.tooCloseToBarcode(readPosition, 0); if (Math.abs(distance) > 160) { throw new AssertionFailedException("Distance problem with candidate " + candidate + " read at read position " + readPosition + " and refPosition " + refPosition + ' ' + r.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance); } if (distance >= 0) { stats.singleAnalyzerQ2CandidateDistanceToLigationSite.insert(distance); } else { stats.Q2CandidateDistanceToLigationSiteN.insert(-distance); } } return true; }); } if (candidate.getMutationType().isWildtype()) { candidate.setSupplementalMessage(null); } else if (candidate.getQuality().getNonNullValue().greaterThan(POOR)) { final StringBuilder supplementalMessage = new StringBuilder(); final Map<String, Integer> stringCounts = new HashMap<>(100); candidate.getNonMutableConcurringReads().forEachKey(er -> { String other = er.record.getMateReferenceName(); if (!er.record.getReferenceName().equals(other)) { String s = other + ':' + er.getMateAlignmentStart(); int found = stringCounts.getOrDefault(s, 0); stringCounts.put(s, found + 1); } return true; }); final Optional<String> mates = stringCounts.entrySet().stream().map(entry -> entry.getKey() + ((entry.getValue() == 1) ? "" : (" (" + entry.getValue() + " repeats)")) + "; "). sorted().reduce(String::concat); final String hasMateOnOtherChromosome = mates.orElse(""); IntSummaryStatistics insertSizeStats = candidate.getConcurringReadSummaryStatistics(er -> Math.abs(er.getInsertSize())); final int localMaxInsertSize = insertSizeStats.getMax(); final int localMinInsertSize = insertSizeStats.getMin(); candidate.setMinInsertSize(insertSizeStats.getMin()); candidate.setMaxInsertSize(insertSizeStats.getMax()); if (localMaxInsertSize < param.minInsertSize || localMinInsertSize > param.maxInsertSize) { candidate.getQuality().add(PositionAssay.INSERT_SIZE, DUBIOUS); } final NumberFormat nf = DoubleAdderFormatter.nf.get(); @SuppressWarnings("null") final boolean hasNoMate = candidate.getNonMutableConcurringReads().forEachKey( er -> er.record.getMateReferenceName() != null); if (localMaxInsertSize > param.maxInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMaxInsertSize)).append("; "); } if (localMinInsertSize < param.minInsertSize) { supplementalMessage.append("one predicted insert size is " + nf.format(localMinInsertSize)).append("; "); } IntSummaryStatistics mappingQualities = candidate.getConcurringReadSummaryStatistics(er -> er.record.getMappingQuality()); candidate.setAverageMappingQuality((int) mappingQualities.getAverage()); if (!"".equals(hasMateOnOtherChromosome)) { supplementalMessage.append("pair elements map to other chromosomes: " + hasMateOnOtherChromosome).append("; "); } if (hasNoMate) { supplementalMessage.append("at least one read has no mate nearby; "); } if ("".equals(hasMateOnOtherChromosome) && !hasNoMate && localMinInsertSize == 0) { supplementalMessage.append("at least one insert has 0 predicted size; "); } if (candidate.getnWrongPairs() > 0) { supplementalMessage.append(candidate.getnWrongPairs() + " wrong pairs; "); } candidate.setSupplementalMessage(supplementalMessage); } } @SuppressWarnings("ReferenceEquality") private static void checkDuplexes(Iterable<Duplex> duplexes) { for (Duplex duplex: duplexes) { duplex.allRecords.each(r -> { //noinspection ObjectEquality if (r.duplex != duplex) { throw new AssertionFailedException("Read " + r + " associated with duplexes " + r.duplex + " and " + duplex); } }); } @NonNull Set<Duplex> duplicates = Util.getDuplicates(duplexes); if (!duplicates.isEmpty()) { throw new AssertionFailedException("Duplicate duplexes: " + duplicates); } } @SuppressWarnings("ReferenceEquality") private static void checkDuplexAndCandidates(Set<Duplex> duplexes, ImmutableSet<CandidateSequence> candidateSet) { checkDuplexes(duplexes); candidateSet.each(c -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); Set<Duplex> duplexesSupportingC = c.computeSupportingDuplexes(); candidateSet.each(c2 -> { Assert.isTrue(c.getNonMutableConcurringReads().keySet().equals( c.getMutableConcurringReads().keySet())); //noinspection ObjectEquality if (c2 == c) { return; } if (c2.equals(c)) { throw new AssertionFailedException(); } c2.getNonMutableConcurringReads().keySet().forEach(r -> { //if (r.isOpticalDuplicate()) { // return; //} Assert.isFalse(r.discarded); Duplex d = r.duplex; if (d != null && duplexesSupportingC.contains(d)) { boolean disowned = !d.allRecords.contains(r); throw new AssertionFailedException(disowned + " Duplex " + d + " associated with candidates " + c + " and " + c2); } }); }); }); } private boolean checkConstantBarcode(byte[] bases, boolean allowN, int nAllowableMismatches) { if (nAllowableMismatches == 0 && !allowN) { //noinspection ArrayEquality return bases == analyzer.constantBarcode;//OK because of interning } int nMismatches = 0; for (int i = 0; i < analyzer.constantBarcode.length; i++) { if (!basesEqual(analyzer.constantBarcode[i], bases[i], allowN)) { nMismatches ++; if (nMismatches > nAllowableMismatches) return false; } } return true; } @NonNull ExtendedSAMRecord getExtended(@NonNull SAMRecord record, @NonNull SequenceLocation location) { final @NonNull String readFullName = ExtendedSAMRecord.getReadFullName(record, false); return extSAMCache.computeIfAbsent(readFullName, s -> new ExtendedSAMRecord(record, readFullName, analyzer.stats, analyzer, location, extSAMCache)); } @SuppressWarnings("null") public static @NonNull ExtendedSAMRecord getExtendedNoCaching(@NonNull SAMRecord record, @NonNull SequenceLocation location, Mutinack analyzer) { final @NonNull String readFullName = ExtendedSAMRecord.getReadFullName(record, false); return new ExtendedSAMRecord(record, readFullName, Collections.emptyList(), analyzer, location, null); } /** * * @return the furthest position in the contig covered by the read */ int processRead( final @NonNull SequenceLocation location, final @NonNull InterningSet<SequenceLocation> locationInterningSet, final @NonNull ExtendedSAMRecord extendedRec, final @NonNull ReferenceSequence ref) { Assert.isFalse(extendedRec.processed, "Double processing of record %s"/*, extendedRec.getFullName()*/); extendedRec.processed = true; final SAMRecord rec = extendedRec.record; final int effectiveReadLength = extendedRec.effectiveLength; if (effectiveReadLength == 0) { return -1; } final CandidateBuilder readLocalCandidates = new CandidateBuilder(rec.getReadNegativeStrandFlag(), analyzer.codingStrandTester, param.enableCostlyAssertions ? null : (k, v) -> insertCandidateAtPosition(v, k)); final int insertSize = extendedRec.getInsertSize(); final int insertSizeAbs = Math.abs(insertSize); if (insertSizeAbs > param.maxInsertSize) { stats.nReadsInsertSizeAboveMaximum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } if (insertSizeAbs < param.minInsertSize) { stats.nReadsInsertSizeBelowMinimum.increment(location); if (param.ignoreSizeOutOfRangeInserts) { return -1; } } final PairOrientation pairOrientation; if (rec.getReadPairedFlag() && !rec.getReadUnmappedFlag() && !rec.getMateUnmappedFlag() && rec.getReferenceIndex().equals(rec.getMateReferenceIndex()) && ((pairOrientation = SamPairUtil.getPairOrientation(rec)) == PairOrientation.TANDEM || pairOrientation == PairOrientation.RF)) { if (pairOrientation == PairOrientation.TANDEM) { stats.nReadsPairTandem.increment(location); } else if (pairOrientation == PairOrientation.RF) { stats.nReadsPairRF.increment(location); } if (param.ignoreTandemRFPairs) { return -1; } } final boolean readOnNegativeStrand = rec.getReadNegativeStrandFlag(); if (!checkConstantBarcode(extendedRec.constantBarcode, false, param.nConstantBarcodeMismatchesAllowed)) { if (checkConstantBarcode(extendedRec.constantBarcode, true, param.nConstantBarcodeMismatchesAllowed)) { if (readOnNegativeStrand) stats.nConstantBarcodeDodgyNStrand.increment(location); else stats.nConstantBarcodeDodgy.increment(location); if (!param.acceptNInBarCode) return -1; } else { stats.nConstantBarcodeMissing.increment(location); return -1; } } stats.nReadsConstantBarcodeOK.increment(location); if (extendedRec.medianPhred < param.minReadMedianPhredScore) { stats.nReadMedianPhredBelowThreshold.accept(location); return -1; } stats.mappingQualityKeptRecords.insert(rec.getMappingQuality()); SettableInteger refEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger readEndOfPreviousAlignment = new SettableInteger(-1); SettableInteger returnValue = new SettableInteger(-1); if (insertSize == 0) { stats.nReadsInsertNoSize.increment(location); if (param.ignoreZeroInsertSizeReads) { return -1; } } if (rec.getMappingQuality() < param.minMappingQualityQ1) { return -1; } for (ExtendedAlignmentBlock block: extendedRec.getAlignmentBlocks()) { processAlignmentBlock( location, locationInterningSet, readLocalCandidates, ref, block, extendedRec, rec, readOnNegativeStrand, effectiveReadLength, refEndOfPreviousAlignment, readEndOfPreviousAlignment, returnValue); } if (param.enableCostlyAssertions) { readLocalCandidates.build().forEach((k, v) -> insertCandidateAtPosition(v, k)); } return returnValue.get(); } private void processAlignmentBlock( @NonNull SequenceLocation location, InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ReferenceSequence ref, final ExtendedAlignmentBlock block, final @NonNull ExtendedSAMRecord extendedRec, final SAMRecord rec, final boolean readOnNegativeStrand, final int effectiveReadLength, final SettableInteger refEndOfPreviousAlignment0, final SettableInteger readEndOfPreviousAlignment0, final SettableInteger returnValue) { @SuppressWarnings("AnonymousInnerClassMayBeStatic") final CandidateFiller fillInCandidateInfo = new CandidateFiller() { @Override public void accept(CandidateSequence candidate) { candidate.setInsertSize(extendedRec.getInsertSize()); candidate.setReadEL(effectiveReadLength); candidate.setReadName(extendedRec.getFullName()); candidate.setReadAlignmentStart(extendedRec.getRefAlignmentStart()); candidate.setMateReadAlignmentStart(extendedRec.getMateRefAlignmentStart()); candidate.setReadAlignmentEnd(extendedRec.getRefAlignmentEnd()); candidate.setMateReadAlignmentEnd(extendedRec.getMateRefAlignmentEnd()); candidate.setRefPositionOfMateLigationSite(extendedRec.getRefPositionOfMateLigationSite()); } @Override public void fillInPhred(CandidateSequence candidate, SequenceLocation location1, int readPosition) { final byte quality = rec.getBaseQualities()[readPosition]; candidate.addBasePhredScore(quality); if (extendedRec.basePhredScores.put(location1, quality) != ExtendedSAMRecord.PHRED_NO_ENTRY) { logger.warn("Recording Phred score multiple times at same position " + location1); } } }; int refPosition = block.getReferenceStart() - 1; int readPosition = block.getReadStart() - 1; final int nBlockBases = block.getLength(); final int refEndOfPreviousAlignment = refEndOfPreviousAlignment0.get(); final int readEndOfPreviousAlignment = readEndOfPreviousAlignment0.get(); returnValue.set(Math.max(returnValue.get(), refPosition + nBlockBases)); /** * When adding an insertion candidate, make sure that a wildtype or * mismatch candidate is also inserted at the same position, even * if it normally would not have been (for example because of low Phred * quality). This should avoid awkward comparisons between e.g. an * insertion candidate and a combo insertion + wildtype candidate. */ boolean forceCandidateInsertion = false; if (refEndOfPreviousAlignment != -1) { final boolean insertion = refPosition == refEndOfPreviousAlignment + 1; final boolean tooLate = (readOnNegativeStrand ? (insertion ? readPosition <= param.ignoreLastNBases : readPosition < param.ignoreLastNBases) : readPosition > rec.getReadLength() - param.ignoreLastNBases) && !param.rnaSeq; if (tooLate) { if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring indel too close to end " + readPosition + (readOnNegativeStrand ? " neg strand " : " pos strand ") + readPosition + ' ' + (rec.getReadLength() - 1) + ' ' + extendedRec.getFullName()); } stats.nCandidateIndelAfterLastNBases.increment(location); } else { if (insertion) { stats.nCandidateInsertions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion at position " + readPosition + " for read " + rec.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand); } forceCandidateInsertion = processInsertion( fillInCandidateInfo, readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec, readOnNegativeStrand); } else if (refPosition < refEndOfPreviousAlignment + 1) { throw new AssertionFailedException("Alignment block misordering"); } else { processDeletion( fillInCandidateInfo, location, ref, block, readPosition, refPosition, readEndOfPreviousAlignment, refEndOfPreviousAlignment, locationInterningSet, readLocalCandidates, extendedRec); }//End of deletion case }//End of case with accepted indel }//End of case where there was a previous alignment block refEndOfPreviousAlignment0.set(refPosition + (nBlockBases - 1)); readEndOfPreviousAlignment0.set(readPosition + (nBlockBases - 1)); final byte [] readBases = rec.getReadBases(); final byte [] baseQualities = rec.getBaseQualities(); for (int i = 0; i < nBlockBases; i++, readPosition++, refPosition++) { if (i == 1) { forceCandidateInsertion = false; } Handle<Boolean> insertCandidateAtRegularPosition = new Handle<>(true); final SequenceLocation locationPH = i < nBlockBases - 1 ? //No insertion or deletion; make a note of it SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refPosition, true) : null; location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refPosition); if (baseQualities[readPosition] < param.minBasePhredScoreQ1) { stats.nBasesBelowPhredScore.increment(location); if (forceCandidateInsertion) { insertCandidateAtRegularPosition.set(false); } else { continue; } } if (refPosition > ref.length() - 1) { logger.warn("Ignoring base mapped at " + refPosition + ", beyond the end of " + ref.getName()); continue; } stats.nCandidateSubstitutionsConsidered.increment(location); byte wildType = StringUtil.toUpperCase(ref.getBases()[refPosition]); if (isMutation(wildType, readBases[readPosition])) {/*Mismatch*/ final boolean tooLate = readOnNegativeStrand ? readPosition < param.ignoreLastNBases : readPosition > (rec.getReadLength() - 1) - param.ignoreLastNBases; boolean goodToInsert = checkSubstDistance( readPosition, location, tooLate, insertCandidateAtRegularPosition, extendedRec) && !tooLate; if (goodToInsert || forceCandidateInsertion) { processSubstitution( fillInCandidateInfo, location, locationPH, readPosition, readLocalCandidates, extendedRec, readOnNegativeStrand, wildType, effectiveReadLength, forceCandidateInsertion, insertCandidateAtRegularPosition); }//End of mismatched read case } else { processWildtypeBase( fillInCandidateInfo, location, locationPH, readPosition, refPosition, wildType, readLocalCandidates, extendedRec, readOnNegativeStrand, forceCandidateInsertion, insertCandidateAtRegularPosition); }//End of wildtype case }//End of loop over alignment bases } private static boolean isMutation(byte ucReferenceBase, byte ucReadBase) { Assert.isTrue(ucReferenceBase < 91);//Assert base is upper case Assert.isTrue(ucReadBase < 91); switch (ucReferenceBase) { case 'Y': return ucReadBase != 'C' && ucReadBase != 'T'; case 'R': return ucReadBase != 'G' && ucReadBase != 'A'; case 'W': return ucReadBase != 'A' && ucReadBase != 'T'; default: return ucReadBase != ucReferenceBase; } } private interface CandidateFiller { void accept(CandidateSequence candidate); void fillInPhred(CandidateSequence candidate, SequenceLocation location, int readPosition); } private boolean checkSubstDistance( int readPosition, @NonNull SequenceLocation location, boolean tooLate, Handle<Boolean> insertCandidateAtRegularPosition, ExtendedSAMRecord extendedRec) { int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition.get()) { stats.rejectedSubstDistanceToLigationSite.insert(-distance); stats.nCandidateSubstitutionsBeforeFirstNBases.increment(location); } } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to barcode for read " + extendedRec.getFullName()); } insertCandidateAtRegularPosition.set(false); } else if (tooLate && insertCandidateAtRegularPosition.get()) { stats.nCandidateSubstitutionsAfterLastNBases.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Ignoring subst too close to read end for read " + extendedRec.getFullName()); } insertCandidateAtRegularPosition.set(false); } return distance < 0; } private void processWildtypeBase( final CandidateFiller candidateFiller, final @NonNull SequenceLocation location, final @Nullable SequenceLocation locationPH, final int readPosition, final int refPosition, byte wildType, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final boolean readOnNegativeStrand, final boolean forceCandidateInsertion, final Handle<Boolean> insertCandidateAtRegularPosition) { int distance = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); if (distance >= 0) { if (!extendedRec.formsWrongPair()) { distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (distance <= 0 && insertCandidateAtRegularPosition.get()) { stats.wtRejectedDistanceToLigationSite.insert(-distance); } } if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } } else { if (!extendedRec.formsWrongPair() && distance < -150) { throw new AssertionFailedException("Distance problem 1 at read position " + readPosition + " and refPosition " + refPosition + ' ' + extendedRec.toString() + " in analyzer" + analyzer.inputBam.getAbsolutePath() + "; distance is " + distance + ""); } distance = extendedRec.tooCloseToBarcode(readPosition, 0); if (!extendedRec.formsWrongPair() && insertCandidateAtRegularPosition.get()) { stats.wtAcceptedBaseDistanceToLigationSite.insert(-distance); } } if (((!readOnNegativeStrand && readPosition > extendedRec.record.getReadLength() - 1 - param.ignoreLastNBases) || (readOnNegativeStrand && readPosition < param.ignoreLastNBases))) { if (insertCandidateAtRegularPosition.get()) { stats.nCandidateWildtypeAfterLastNBases.increment(location); } if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } } CandidateSequence candidate = new CandidateSequence(this, WILDTYPE, null, location, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(-distance); } candidate.setWildtypeSequence(wildType); candidateFiller.fillInPhred(candidate, location, readPosition); if (insertCandidateAtRegularPosition.get()) { //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, location); //noinspection UnusedAssignment candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, -distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(-distance); } candidate2.setWildtypeSequence(wildType); //noinspection UnusedAssignment candidate2 = readLocalCandidates.add(candidate2, locationPH); //noinspection UnusedAssignment candidate2 = null; } } private void processSubstitution( final CandidateFiller candidateFiller, final @NonNull SequenceLocation location, final @Nullable SequenceLocation locationPH, final int readPosition, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final boolean readOnNegativeStrand, final byte wildType, final int effectiveReadLength, final boolean forceCandidateInsertion, final Handle<Boolean> insertCandidateAtRegularPosition) { if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Substitution at position " + readPosition + " for read " + extendedRec.record.getReadName() + " (effective length: " + effectiveReadLength + "; reversed:" + readOnNegativeStrand + "; insert size: " + extendedRec.getInsertSize() + ')'); } final byte mutation = extendedRec.record.getReadBases()[readPosition]; final byte mutationUC = StringUtil.toUpperCase(mutation); switch (mutationUC) { case 'A': stats.nCandidateSubstitutionsToA.increment(location); break; case 'T': stats.nCandidateSubstitutionsToT.increment(location); break; case 'G': stats.nCandidateSubstitutionsToG.increment(location); break; case 'C': stats.nCandidateSubstitutionsToC.increment(location); break; case 'N': stats.nNs.increment(location); if (!forceCandidateInsertion) { return; } else { insertCandidateAtRegularPosition.set(false); } break; default: throw new AssertionFailedException("Unexpected letter: " + mutationUC); } final int distance = -extendedRec.tooCloseToBarcode(readPosition, 0); CandidateSequence candidate = new CandidateSequence(this, SUBSTITUTION, byteArrayMap.get(mutation), location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidateFiller.accept(candidate); candidate.setPositionInRead(readPosition); candidate.setWildtypeSequence(wildType); candidateFiller.fillInPhred(candidate, location, readPosition); extendedRec.nReferenceDisagreements++; if (param.computeRawMismatches && insertCandidateAtRegularPosition.get()) { registerRawMismatch(location, extendedRec, readPosition, distance, candidate.getMutableRawMismatchesQ2(), stats.rawMismatchesQ1, getFromByteMap(wildType, readOnNegativeStrand), getFromByteMap(mutationUC, readOnNegativeStrand)); } if (insertCandidateAtRegularPosition.get()) { //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, location); //noinspection UnusedAssignment candidate = null; } if (locationPH != null) { CandidateSequence candidate2 = new CandidateSequence(this, WILDTYPE, null, locationPH, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate2.acceptLigSiteDistance(distance); } candidate2.setWildtypeSequence(wildType); //noinspection UnusedAssignment candidate2 = readLocalCandidates.add(candidate2, locationPH); //noinspection UnusedAssignment candidate2 = null; } } private static @NonNull String getFromByteMap(byte b, boolean reverseComplement) { String result = reverseComplement ? byteMap.get(Mutation.complement(b)) : byteMap.get(b); return Objects.requireNonNull(result); } private void registerRawMismatch( final @NonNull SequenceLocation location, final @NonNull ExtendedSAMRecord extendedRec, final int readPosition, final int distance, final Collection<ComparablePair<String, String>> mismatches, final MultiCounter<ComparablePair<String, String>> q1Stats, final @NonNull String wildType, final @NonNull String mutation) { final ComparablePair<String, String> mutationPair = new ComparablePair<>(wildType, mutation); q1Stats.accept(location, mutationPair); if (meetsQ2Thresholds(extendedRec) && extendedRec.record.getBaseQualities()[readPosition] >= param.minBasePhredScoreQ2 && !extendedRec.formsWrongPair() && distance > param.ignoreFirstNBasesQ2) { mismatches.add(mutationPair); } } private static @NonNull String toUpperCase(byte @NonNull [] deletedSequence, boolean readOnNegativeStrand) { @NonNull String s = new String(deletedSequence).toUpperCase(); return readOnNegativeStrand ? Mutation.reverseComplement(s) : s; } //Deletion or skipped region ("N" in Cigar) private void processDeletion( final CandidateFiller candidateFiller, final @NonNull SequenceLocation location, final @NonNull ReferenceSequence ref, final ExtendedAlignmentBlock block, final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, final InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec) { if (refPosition > ref.length() - 1) { logger.warn("Ignoring rest of read after base mapped at " + refPosition + ", beyond the end of " + ref.getName()); return; } int distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, param.ignoreFirstNBasesQ1); int distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, param.ignoreFirstNBasesQ1); int distance = Math.min(distance0, distance1) + 1; final boolean isIntron = block.previousCigarOperator == CigarOperator.N; final boolean Q1reject = distance < 0; if (!isIntron && Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring deletion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); } else { distance0 = -extendedRec.tooCloseToBarcode(readPosition - 1, 0); distance1 = -extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment + 1, 0); distance = Math.min(distance0, distance1) + 1; if (!isIntron) stats.nCandidateDeletions.increment(location); if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Deletion or intron at position " + readPosition + " for read " + extendedRec.record.getReadName()); } final int deletionLength = refPosition - (refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation newLocation = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1); final @NonNull SequenceLocation deletionEnd = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), newLocation.position + deletionLength); final byte @Nullable[] deletedSequence = isIntron ? null : Arrays.copyOfRange(ref.getBases(), refEndOfPreviousAlignment + 1, refPosition); //Add hidden mutations to all locations covered by deletion //So disagreements between deletions that have only overlapping //spans are detected. if (!isIntron) { for (int i = 1; i < deletionLength; i++) { SequenceLocation location2 = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment + 1 + i); CandidateSequence hiddenCandidate = new CandidateDeletion( this, deletedSequence, location2, extendedRec, Integer.MAX_VALUE, MutationType.DELETION, newLocation, deletionEnd); candidateFiller.accept(hiddenCandidate); hiddenCandidate.setHidden(true); hiddenCandidate.setPositionInRead(readPosition); //noinspection UnusedAssignment hiddenCandidate = readLocalCandidates.add(hiddenCandidate, location2); //noinspection UnusedAssignment hiddenCandidate = null; } } CandidateSequence candidate = new CandidateDeletion(this, deletedSequence, newLocation, extendedRec, distance, isIntron ? MutationType.INTRON : MutationType.DELETION, newLocation, SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refPosition)); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidateFiller.accept(candidate); candidate.setPositionInRead(readPosition); if (!isIntron) extendedRec.nReferenceDisagreements++; if (!isIntron && param.computeRawMismatches) { Objects.requireNonNull(deletedSequence); stats.rawDeletionLengthQ1.insert(deletedSequence.length); final boolean negativeStrand = extendedRec.getReadNegativeStrandFlag(); registerRawMismatch(newLocation, extendedRec, readPosition, distance, candidate.getMutableRawDeletionsQ2(), stats.rawDeletionsQ1, getFromByteMap(deletedSequence[0], negativeStrand), toUpperCase(deletedSequence, negativeStrand)); } //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, newLocation); //noinspection UnusedAssignment candidate = null; } } private boolean processInsertion( final CandidateFiller candidateFiller, final int readPosition, final int refPosition, final int readEndOfPreviousAlignment, final int refEndOfPreviousAlignment, final InterningSet<@NonNull SequenceLocation> locationInterningSet, final CandidateBuilder readLocalCandidates, final @NonNull ExtendedSAMRecord extendedRec, final boolean readOnNegativeStrand) { final @NonNull SequenceLocation location = SequenceLocation.get(locationInterningSet, extendedRec.getLocation().contigIndex, param.referenceGenomeShortName, extendedRec.getLocation().getContigName(), refEndOfPreviousAlignment, true); int distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, param.ignoreFirstNBasesQ1); int distance1 = extendedRec.tooCloseToBarcode(readPosition, param.ignoreFirstNBasesQ1); int distance = Math.max(distance0, distance1); distance = -distance + 1; final boolean Q1reject = distance < 0; if (Q1reject) { if (!extendedRec.formsWrongPair()) { stats.rejectedIndelDistanceToLigationSite.insert(-distance); stats.nCandidateIndelBeforeFirstNBases.increment(location); } logger.trace("Ignoring insertion " + readEndOfPreviousAlignment + param.ignoreFirstNBasesQ1 + ' ' + extendedRec.getFullName()); return false; } distance0 = extendedRec.tooCloseToBarcode(readEndOfPreviousAlignment, 0); distance1 = extendedRec.tooCloseToBarcode(readPosition, 0); distance = Math.max(distance0, distance1); distance = -distance + 1; final byte [] readBases = extendedRec.record.getReadBases(); final byte @NonNull [] insertedSequence = Arrays.copyOfRange(readBases, readEndOfPreviousAlignment + 1, readPosition); CandidateSequence candidate = new CandidateSequence( this, INSERTION, insertedSequence, location, extendedRec, distance); if (!extendedRec.formsWrongPair()) { candidate.acceptLigSiteDistance(distance); } candidateFiller.accept(candidate); candidate.setPositionInRead(readPosition); if (param.computeRawMismatches) { stats.rawInsertionLengthQ1.insert(insertedSequence.length); registerRawMismatch(location, extendedRec, readPosition, distance, candidate.getMutableRawInsertionsQ2(), stats.rawInsertionsQ1, getFromByteMap(readBases[readEndOfPreviousAlignment], readOnNegativeStrand), toUpperCase(insertedSequence, readOnNegativeStrand)); } if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Insertion of " + new String(candidate.getSequence()) + " at ref " + refPosition + " and read position " + readPosition + " for read " + extendedRec.getFullName()); } //noinspection UnusedAssignment candidate = readLocalCandidates.add(candidate, location); //noinspection UnusedAssignment candidate = null; if (DebugLogControl.shouldLog(TRACE, logger, param, location)) { logger.info("Added candidate at " + location /*+ "; readLocalCandidates now " + readLocalCandidates.build()*/); } extendedRec.nReferenceDisagreements++; return true; } public @NonNull Mutinack getAnalyzer() { return analyzer; } }
Silence warning.
src/uk/org/cinquin/mutinack/SubAnalyzer.java
Silence warning.
<ide><path>rc/uk/org/cinquin/mutinack/SubAnalyzer.java <ide> //stats.nVariableBarcodeCandidateExaminations.increment(location); <ide> <ide> boolean forceGrouping = false; <del> if (duplex.allRecords.detect(drRec -> drRec.record.getReadName().equals(r.getReadName())) != null) { <add> if (Util.nullableify(duplex.allRecords.detect(drRec -> drRec.record.getReadName().equals(r.getReadName()))) <add> != null) { <ide> forceGrouping = true; <ide> } <ide>
Java
apache-2.0
d1df20e8b815d231fdb8411296506cd669b8791f
0
akosyakov/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,diorcety/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,signed/intellij-community,dslomov/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,apixandru/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,holmes/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,kool79/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,kool79/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,akosyakov/intellij-community,caot/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,asedunov/intellij-community,samthor/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,semonte/intellij-community,blademainer/intellij-community,adedayo/intellij-community,supersven/intellij-community,semonte/intellij-community,ryano144/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,allotria/intellij-community,gnuhub/intellij-community,izonder/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,da1z/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,robovm/robovm-studio,caot/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,signed/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,nicolargo/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,joewalnes/idea-community,FHannes/intellij-community,semonte/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,caot/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,da1z/intellij-community,izonder/intellij-community,ernestp/consulo,vladmm/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,fitermay/intellij-community,clumsy/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,supersven/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,holmes/intellij-community,petteyg/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ryano144/intellij-community,da1z/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,xfournet/intellij-community,adedayo/intellij-community,vladmm/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,allotria/intellij-community,robovm/robovm-studio,apixandru/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,xfournet/intellij-community,allotria/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,diorcety/intellij-community,adedayo/intellij-community,da1z/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,caot/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,ibinti/intellij-community,clumsy/intellij-community,FHannes/intellij-community,amith01994/intellij-community,kdwink/intellij-community,amith01994/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,fnouama/intellij-community,petteyg/intellij-community,slisson/intellij-community,vladmm/intellij-community,caot/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,fnouama/intellij-community,signed/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,fitermay/intellij-community,izonder/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,jagguli/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,hurricup/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,semonte/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,caot/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,semonte/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,blademainer/intellij-community,kool79/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,retomerz/intellij-community,amith01994/intellij-community,da1z/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,clumsy/intellij-community,hurricup/intellij-community,retomerz/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,jagguli/intellij-community,holmes/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,jagguli/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,samthor/intellij-community,adedayo/intellij-community,fnouama/intellij-community,semonte/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,holmes/intellij-community,kdwink/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,caot/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,ernestp/consulo,wreckJ/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,allotria/intellij-community,ibinti/intellij-community,kool79/intellij-community,joewalnes/idea-community,adedayo/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,da1z/intellij-community,slisson/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,jexp/idea2,clumsy/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,supersven/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,signed/intellij-community,signed/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,allotria/intellij-community,amith01994/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,caot/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,semonte/intellij-community,holmes/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,clumsy/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,jexp/idea2,mglukhikh/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,signed/intellij-community,ryano144/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,da1z/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,izonder/intellij-community,hurricup/intellij-community,kdwink/intellij-community,vladmm/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,retomerz/intellij-community,jexp/idea2,Lekanich/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,adedayo/intellij-community,FHannes/intellij-community,joewalnes/idea-community,ibinti/intellij-community,allotria/intellij-community,kdwink/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ernestp/consulo,gnuhub/intellij-community,jexp/idea2,signed/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,ryano144/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,blademainer/intellij-community,vvv1559/intellij-community,kool79/intellij-community,allotria/intellij-community,retomerz/intellij-community,supersven/intellij-community,robovm/robovm-studio,ryano144/intellij-community,diorcety/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,izonder/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,retomerz/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,supersven/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,signed/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,allotria/intellij-community,samthor/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,da1z/intellij-community,izonder/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,kdwink/intellij-community,xfournet/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,allotria/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,consulo/consulo,holmes/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,blademainer/intellij-community,samthor/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,semonte/intellij-community,jagguli/intellij-community,petteyg/intellij-community,signed/intellij-community,xfournet/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,joewalnes/idea-community,holmes/intellij-community,ryano144/intellij-community,dslomov/intellij-community,ryano144/intellij-community,supersven/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,slisson/intellij-community,consulo/consulo,joewalnes/idea-community,slisson/intellij-community,dslomov/intellij-community,caot/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,jexp/idea2,petteyg/intellij-community,slisson/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,kool79/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,samthor/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,fitermay/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,signed/intellij-community,ol-loginov/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,jexp/idea2,vvv1559/intellij-community,jexp/idea2,wreckJ/intellij-community,consulo/consulo,da1z/intellij-community,amith01994/intellij-community,allotria/intellij-community,Distrotech/intellij-community,izonder/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,supersven/intellij-community,semonte/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ernestp/consulo,apixandru/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,supersven/intellij-community,robovm/robovm-studio,retomerz/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,supersven/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ibinti/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ibinti/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community
package com.intellij.psi.impl.source.xml; import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiRecursiveElementVisitor; import com.intellij.psi.PsiReferenceExpression; import com.intellij.psi.impl.meta.MetaRegistry; import com.intellij.psi.impl.source.tree.ChildRole; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.impl.source.xml.aspect.XmlDocumentChanged; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.CachedValue; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlProlog; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlToken; import com.intellij.xml.XmlNSDescriptor; import com.intellij.pom.PomModel; import com.intellij.pom.event.PomModelEvent; import com.intellij.pom.impl.PomTransactionBase; import com.intellij.util.IncorrectOperationException; import gnu.trove.TObjectIntHashMap; /** * @author Mike */ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.xml.XmlDocumentImpl"); private CachedValue myDescriptor = null; public XmlDocumentImpl() { this(XML_DOCUMENT); } protected XmlDocumentImpl(IElementType type) { super(type); } public void accept(PsiElementVisitor visitor) { visitor.visitXmlDocument(this); } public int getChildRole(ASTNode child) { LOG.assertTrue(child.getTreeParent() == this); IElementType i = child.getElementType(); if (i == XML_PROLOG) { return ChildRole.XML_PROLOG; } else if (i == XML_TAG) { return ChildRole.XML_TAG; } else { return ChildRole.NONE; } } public XmlProlog getProlog() { return (XmlProlog)findElementByTokenType(XML_PROLOG); } public XmlTag getRootTag() { return (XmlTag)findElementByTokenType(XML_TAG); } public XmlNSDescriptor getRootTagNSDescriptor() { XmlTag rootTag = getRootTag(); return rootTag != null ? rootTag.getNSDescriptor(rootTag.getNamespace(), false) : null; } public PsiElement copy() { final XmlDocumentImpl copy = (XmlDocumentImpl)super.copy(); copy.myDescriptor = null; return copy; } public PsiMetaData getMetaData() { return MetaRegistry.getMeta(this); } public boolean isMetaEnough() { return true; } public void dumpStatistics(){ System.out.println("Statistics:"); final TObjectIntHashMap map = new TObjectIntHashMap(); final PsiRecursiveElementVisitor psiRecursiveElementVisitor = new PsiRecursiveElementVisitor(){ public void visitReferenceExpression(PsiReferenceExpression expression) { visitElement(expression); } public void visitXmlToken(XmlToken token) { inc("Tokens"); } public void visitElement(PsiElement element) { inc("Elements"); super.visitElement(element); } private void inc(final String key) { map.put(key, map.get(key) + 1); } }; this.accept(psiRecursiveElementVisitor); final Object[] keys = map.keys(); for (int i = 0; i < keys.length; i++) { final Object key = keys[i]; System.out.println(key + ": " + map.get(key)); } } public TreeElement addInternal(final TreeElement first, final ASTNode last, final ASTNode anchor, final Boolean before) { final PomModel model = getProject().getModel(); final XmlAspect aspect = model.getModelAspect(XmlAspect.class); final TreeElement[] holder = new TreeElement[1]; try{ model.runTransaction(new PomTransactionBase(this) { public PomModelEvent run() throws IncorrectOperationException { holder[0] = XmlDocumentImpl.super.addInternal(first, last, anchor, before); return XmlDocumentChanged.createXmlDocumentChanged(model, XmlDocumentImpl.this); } }, aspect); } catch(IncorrectOperationException e){} return holder[0]; } public void deleteChildInternal(final ASTNode child) { final PomModel model = getProject().getModel(); final XmlAspect aspect = model.getModelAspect(XmlAspect.class); try{ model.runTransaction(new PomTransactionBase(this) { public PomModelEvent run() throws IncorrectOperationException { XmlDocumentImpl.super.deleteChildInternal(child); return XmlDocumentChanged.createXmlDocumentChanged(model, XmlDocumentImpl.this); } }, aspect); } catch(IncorrectOperationException e){} } public void replaceChildInternal(final ASTNode child, final TreeElement newElement) { final PomModel model = getProject().getModel(); final XmlAspect aspect = model.getModelAspect(XmlAspect.class); try{ model.runTransaction(new PomTransactionBase(this) { public PomModelEvent run() throws IncorrectOperationException { XmlDocumentImpl.super.replaceChildInternal(child, newElement); return XmlDocumentChanged.createXmlDocumentChanged(model, XmlDocumentImpl.this); } }, aspect); } catch(IncorrectOperationException e){} } }
source/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java
package com.intellij.psi.impl.source.xml; import com.intellij.ant.impl.dom.xmlBridge.AntDOMNSDescriptor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.psi.*; import com.intellij.psi.impl.meta.MetaRegistry; import com.intellij.psi.impl.source.tree.ChildRole; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.xml.*; import com.intellij.util.IncorrectOperationException; import com.intellij.xml.XmlNSDescriptor; import com.intellij.xml.util.XmlNSDescriptorSequence; import com.intellij.xml.util.XmlUtil; import com.intellij.lang.ASTNode; import gnu.trove.TObjectIntHashMap; import java.lang.ref.WeakReference; /** * @author Mike */ public class XmlDocumentImpl extends XmlElementImpl implements XmlDocument { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.xml.XmlDocumentImpl"); private CachedValue myDescriptor = null; public XmlDocumentImpl() { this(XML_DOCUMENT); } protected XmlDocumentImpl(IElementType type) { super(type); } public void accept(PsiElementVisitor visitor) { visitor.visitXmlDocument(this); } public int getChildRole(ASTNode child) { LOG.assertTrue(child.getTreeParent() == this); IElementType i = child.getElementType(); if (i == XML_PROLOG) { return ChildRole.XML_PROLOG; } else if (i == XML_TAG) { return ChildRole.XML_TAG; } else { return ChildRole.NONE; } } public XmlProlog getProlog() { return (XmlProlog)findElementByTokenType(XML_PROLOG); } public XmlTag getRootTag() { return (XmlTag)findElementByTokenType(XML_TAG); } public XmlNSDescriptor getRootTagNSDescriptor() { XmlTag rootTag = getRootTag(); return rootTag != null ? rootTag.getNSDescriptor(rootTag.getNamespace(), false) : null; } public PsiElement copy() { final XmlDocumentImpl copy = (XmlDocumentImpl)super.copy(); copy.myDescriptor = null; return copy; } public PsiMetaData getMetaData() { return MetaRegistry.getMeta(this); } public boolean isMetaEnough() { return true; } public void dumpStatistics(){ System.out.println("Statistics:"); final TObjectIntHashMap map = new TObjectIntHashMap(); final PsiRecursiveElementVisitor psiRecursiveElementVisitor = new PsiRecursiveElementVisitor(){ public void visitReferenceExpression(PsiReferenceExpression expression) { visitElement(expression); } public void visitXmlToken(XmlToken token) { inc("Tokens"); } public void visitElement(PsiElement element) { inc("Elements"); super.visitElement(element); } private void inc(final String key) { map.put(key, map.get(key) + 1); } }; this.accept(psiRecursiveElementVisitor); final Object[] keys = map.keys(); for (int i = 0; i < keys.length; i++) { final Object key = keys[i]; System.out.println(key + ": " + map.get(key)); } } }
XmlDocument changes now send XML events
source/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java
XmlDocument changes now send XML events
<ide><path>ource/com/intellij/psi/impl/source/xml/XmlDocumentImpl.java <ide> package com.intellij.psi.impl.source.xml; <ide> <del>import com.intellij.ant.impl.dom.xmlBridge.AntDOMNSDescriptor; <add>import com.intellij.lang.ASTNode; <ide> import com.intellij.openapi.diagnostic.Logger; <del>import com.intellij.openapi.fileTypes.StdFileTypes; <del>import com.intellij.psi.*; <add>import com.intellij.psi.PsiElement; <add>import com.intellij.psi.PsiElementVisitor; <add>import com.intellij.psi.PsiRecursiveElementVisitor; <add>import com.intellij.psi.PsiReferenceExpression; <ide> import com.intellij.psi.impl.meta.MetaRegistry; <ide> import com.intellij.psi.impl.source.tree.ChildRole; <ide> import com.intellij.psi.impl.source.tree.TreeElement; <add>import com.intellij.psi.impl.source.xml.aspect.XmlDocumentChanged; <ide> import com.intellij.psi.meta.PsiMetaData; <ide> import com.intellij.psi.tree.IElementType; <ide> import com.intellij.psi.util.CachedValue; <del>import com.intellij.psi.util.CachedValueProvider; <del>import com.intellij.psi.xml.*; <add>import com.intellij.psi.xml.XmlDocument; <add>import com.intellij.psi.xml.XmlProlog; <add>import com.intellij.psi.xml.XmlTag; <add>import com.intellij.psi.xml.XmlToken; <add>import com.intellij.xml.XmlNSDescriptor; <add>import com.intellij.pom.PomModel; <add>import com.intellij.pom.event.PomModelEvent; <add>import com.intellij.pom.impl.PomTransactionBase; <ide> import com.intellij.util.IncorrectOperationException; <del>import com.intellij.xml.XmlNSDescriptor; <del>import com.intellij.xml.util.XmlNSDescriptorSequence; <del>import com.intellij.xml.util.XmlUtil; <del>import com.intellij.lang.ASTNode; <ide> import gnu.trove.TObjectIntHashMap; <del> <del>import java.lang.ref.WeakReference; <ide> <ide> /** <ide> * @author Mike <ide> System.out.println(key + ": " + map.get(key)); <ide> } <ide> } <add> <add> public TreeElement addInternal(final TreeElement first, final ASTNode last, final ASTNode anchor, final Boolean before) { <add> final PomModel model = getProject().getModel(); <add> final XmlAspect aspect = model.getModelAspect(XmlAspect.class); <add> final TreeElement[] holder = new TreeElement[1]; <add> try{ <add> model.runTransaction(new PomTransactionBase(this) { <add> public PomModelEvent run() throws IncorrectOperationException { <add> holder[0] = XmlDocumentImpl.super.addInternal(first, last, anchor, before); <add> return XmlDocumentChanged.createXmlDocumentChanged(model, XmlDocumentImpl.this); <add> } <add> }, aspect); <add> } <add> catch(IncorrectOperationException e){} <add> return holder[0]; <add> } <add> <add> public void deleteChildInternal(final ASTNode child) { <add> final PomModel model = getProject().getModel(); <add> final XmlAspect aspect = model.getModelAspect(XmlAspect.class); <add> try{ <add> model.runTransaction(new PomTransactionBase(this) { <add> public PomModelEvent run() throws IncorrectOperationException { <add> XmlDocumentImpl.super.deleteChildInternal(child); <add> return XmlDocumentChanged.createXmlDocumentChanged(model, XmlDocumentImpl.this); <add> } <add> }, aspect); <add> } <add> catch(IncorrectOperationException e){} <add> } <add> <add> public void replaceChildInternal(final ASTNode child, final TreeElement newElement) { <add> final PomModel model = getProject().getModel(); <add> final XmlAspect aspect = model.getModelAspect(XmlAspect.class); <add> try{ <add> model.runTransaction(new PomTransactionBase(this) { <add> public PomModelEvent run() throws IncorrectOperationException { <add> XmlDocumentImpl.super.replaceChildInternal(child, newElement); <add> return XmlDocumentChanged.createXmlDocumentChanged(model, XmlDocumentImpl.this); <add> } <add> }, aspect); <add> } <add> catch(IncorrectOperationException e){} <add> } <ide> }
JavaScript
isc
a91ab18ebde2357170a69f2e6cd06445ece56453
0
bhj/karaoke-forever,bhj/karaoke-forever
import React, { PropTypes } from 'react' import SongItem from '../SongItem' class SongList extends React.Component { static propTypes = { fetchSongs: PropTypes.func.isRequired, songs: PropTypes.array, isFetching: PropTypes.bool.isRequired } render () { if (!this.props.songs || this.props.isFetching) return null let songs = this.props.songs.map(song => { return ( <SongItem title={song.title} plays={song.plays} onSelectSong={this.handleSongClick.bind(this, song.uid)} key={song.uid} /> ) }) return ( <div> {songs} </div> ) } handleSongClick(uid){ console.log('select', uid) } } export default SongList
src/routes/Library/routes/Songs/components/SongList/SongList.js
import React, { PropTypes } from 'react' import SongItem from '../SongItem' class SongList extends React.Component { static propTypes = { fetchSongs: PropTypes.func.isRequired, songs: PropTypes.object, isFetching: PropTypes.bool.isRequired } render () { if (!this.props.songs || this.props.isFetching) return null let songs = this.props.songs.map(song => { return ( <SongItem title={song.title} plays={song.plays} onSelectSong={this.handleSongClick.bind(this, song.uid)} key={song.uid} /> ) }) return ( <div> {songs} </div> ) } handleSongClick(uid){ console.log('select', uid) } } export default SongList
Fix propType
src/routes/Library/routes/Songs/components/SongList/SongList.js
Fix propType
<ide><path>rc/routes/Library/routes/Songs/components/SongList/SongList.js <ide> class SongList extends React.Component { <ide> static propTypes = { <ide> fetchSongs: PropTypes.func.isRequired, <del> songs: PropTypes.object, <add> songs: PropTypes.array, <ide> isFetching: PropTypes.bool.isRequired <ide> } <ide>
Java
apache-2.0
error: pathspec 'jmeter-parallel-http/src/test/java/com/blazemeter/jmeter/http/ParallelHTTPSamplerMock.java' did not match any file(s) known to git
1fd64300aa444d044033fb001e8a018ac2e14a3a
1
Blazemeter/jmeter-bzm-plugins,Blazemeter/jmeter-bzm-plugins
package com.blazemeter.jmeter.http; import org.apache.jmeter.protocol.http.sampler.HTTPAbstractImpl; import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase; import java.net.URL; public class ParallelHTTPSamplerMock extends ParallelHTTPSampler { public ParallelHTTPSamplerMock() { super(); impl = new HCMock(this); } public class HCMock extends HTTPAbstractImpl { public HCMock(HTTPSamplerBase testElement) { super(testElement); } @Override protected HTTPSampleResult sample(URL url, String s, boolean b, int i) { HTTPSampleResult res = new HTTPSampleResult(); res.setSuccessful(true); return res; } @Override public boolean interrupt() { return false; } } }
jmeter-parallel-http/src/test/java/com/blazemeter/jmeter/http/ParallelHTTPSamplerMock.java
add mock file
jmeter-parallel-http/src/test/java/com/blazemeter/jmeter/http/ParallelHTTPSamplerMock.java
add mock file
<ide><path>meter-parallel-http/src/test/java/com/blazemeter/jmeter/http/ParallelHTTPSamplerMock.java <add>package com.blazemeter.jmeter.http; <add> <add>import org.apache.jmeter.protocol.http.sampler.HTTPAbstractImpl; <add>import org.apache.jmeter.protocol.http.sampler.HTTPSampleResult; <add>import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase; <add> <add>import java.net.URL; <add> <add>public class ParallelHTTPSamplerMock extends ParallelHTTPSampler { <add> public ParallelHTTPSamplerMock() { <add> super(); <add> impl = new HCMock(this); <add> } <add> <add> public class HCMock extends HTTPAbstractImpl { <add> public HCMock(HTTPSamplerBase testElement) { <add> super(testElement); <add> } <add> <add> @Override <add> protected HTTPSampleResult sample(URL url, String s, boolean b, int i) { <add> HTTPSampleResult res = new HTTPSampleResult(); <add> res.setSuccessful(true); <add> return res; <add> } <add> <add> @Override <add> public boolean interrupt() { <add> return false; <add> } <add> } <add>} <add>
Java
apache-2.0
a5a5d9690e92294720e5fdd8ed1d930af5f2cd3c
0
wuwen5/mybatis-3,shurun19851206/mybaties,yankee42/mybatis-3,fangjz/mybatis-3,gdarmont/mybatis-3,harawata/mybatis-3,jeasonyoung/mybatis-3,gigold/mybatis-3,harawata/mybatis-3,huitutu/mybatis-3,mway08/mybatis-3,jackgao2016/mybatis-3_site,open-source-explore/mybatis-3,hazendaz/mybatis-3,fengsmith/mybatis-3,jingyuzhu/mybatis-3,Ex-Codes/mybatis-3,nyer/mybatis-3,kkxx/mybatis-3,raphaelmonteiro15/mybatis-3,jackgao2016/mybatis-3_site,deboss/mybatis,zhangwei5095/mybatis3-annotaion,raupachz/mybatis-3,JuwinS1993/mybatis-3,fromm0/mybatis-3,yaotj/mybatis-3,spyu2000/mybatis,Prymon/mybatis-3,VioletLife/mybatis-3,wangype/mybatis-3,lxq1008/mybatis-3,510529571/mybatis-3,SeaSky0606/mybatis-3,zduantao/mybatis-3,lindzh/mybatis-3,z744489075/mybatis-3,fromm0/mybatis-3,creary/mybatis,LuBaijiang/mybatis-3,jankill/mybatis-3,langlan/mybatis-3,iaiti/mybatis-3,rollenholt-forks/mybatis,hucy2014/mybatis-3,Xcorpio/mybatis-3,yummy222/mybatis-3,lknny/mybatis-3,gaojinhua/mybatis-3,Zzyong-5170/mybatis-3,mybatis/mybatis-3,xiexingguang/mybatis-3,danyXu/mybatis-3,NanYoMy/mybatis-3,fengsmith/mybatis-3,hehaiyangwork/mybatis-3,qiuyesuifeng/mybatis-3,VioletLife/mybatis-3,ningg/mybatis-3,emacarron/mybatis-3-no-local-cache,salchemist/mybatis-3,hahaduo/mybatis-3,mlc0202/mybatis-3,cuihz/mybatis-3,vniu/mybatis-3,Alwayswithme/mybatis-3,forestqqqq/mybatis-3,tuguangquan/mybatis,keyeMyria/mybatis-3,jmurciego/mybatis-3,liuqk/mybatis-3,chuyuqiao/mybatis-3,xpenxpen/mybatis-3,Liyue1314/mybatis,sshling/mybatis-1,nyer/mybatis-3,csucaicai/mybaties,lousama/mybatis-3,E1110CNotFound/mybatis-3,SpringMybatis/mybatis-3
/* * Copyright 2009-2012 The MyBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.binding; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.executor.result.DefaultResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import domain.blog.Author; import domain.blog.Blog; import domain.blog.DraftPost; import domain.blog.Post; import domain.blog.Section; public class BindingTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void setup() throws Exception { sqlSessionFactory = new IbatisConfig().getSqlSessionFactory(); } @Test public void shouldSelectBlogWithPostsUsingSubSelect() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog b = mapper.selectBlogWithPostsUsingSubSelect(1); assertEquals(1, b.getId()); session.close(); assertNotNull(b.getAuthor()); assertEquals(101, b.getAuthor().getId()); assertEquals("jim", b.getAuthor().getUsername()); assertEquals("********", b.getAuthor().getPassword()); assertEquals(2, b.getPosts().size()); } finally { session.close(); } } @Test public void shouldFindPostsInList() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); List<Post> posts = mapper.findPostsInList(new ArrayList<Integer>() {{ add(1); add(3); add(5); }}); assertEquals(3, posts.size()); session.rollback(); } finally { session.close(); } } @Test public void shouldFindPostsInArray() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Integer[] params = new Integer[]{1, 3, 5}; List<Post> posts = mapper.findPostsInArray(params); assertEquals(3, posts.size()); session.rollback(); } finally { session.close(); } } @Test public void shouldfindThreeSpecificPosts() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); List<Post> posts = mapper.findThreeSpecificPosts(1, new RowBounds(1, 1), 3, 5); assertEquals(1, posts.size()); assertEquals(3, posts.get(0).getId()); session.rollback(); } finally { session.close(); } } @Test public void shouldInsertAuthorWithSelectKey() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = new Author(-1, "cbegin", "******", "[email protected]", "N/A", Section.NEWS); int rows = mapper.insertAuthor(author); assertEquals(1, rows); session.rollback(); } finally { session.close(); } } @Test public void shouldInsertAuthorWithSelectKeyAndDynamicParams() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = new Author(-1, "cbegin", "******", "[email protected]", "N/A", Section.NEWS); int rows = mapper.insertAuthorDynamic(author); assertEquals(1, rows); assertFalse(-1 == author.getId()); // id must be autogenerated Author author2 = mapper.selectAuthor(author.getId()); assertNotNull(author2); assertEquals(author.getEmail(), author2.getEmail()); session.rollback(); } finally { session.close(); } } @Test public void shouldSelectRandom() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Integer x = mapper.selectRandom(); assertNotNull(x); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectListOfBlogsStatement() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Blog> blogs = mapper.selectBlogs(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectMapOfBlogsById() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> blogs = mapper.selectBlogsAsMapById(); assertEquals(2, blogs.size()); for(Map.Entry<Integer,Blog> blogEntry : blogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectOfBlogsByIdInWithProvidedResultHandlerBetweenSessions() { SqlSession session = sqlSessionFactory.openSession(); try { final DefaultResultHandler handler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", handler); //new session session.close(); session = sqlSessionFactory.openSession(); final DefaultResultHandler moreHandler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", moreHandler); assertEquals(2, handler.getResultList().size()); assertEquals(2, moreHandler.getResultList().size()); } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectOfBlogsByIdInWithProvidedResultHandlerInSameSession() { SqlSession session = sqlSessionFactory.openSession(); try { final DefaultResultHandler handler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", handler); final DefaultResultHandler moreHandler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", moreHandler); assertEquals(2, handler.getResultList().size()); assertEquals(2, moreHandler.getResultList().size()); } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectMapOfBlogsByIdInSameSessionWithoutClearingLocalCache() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> blogs = mapper.selectBlogsAsMapById(); Map<Integer,Blog> moreBlogs = mapper.selectBlogsAsMapById(); assertEquals(2, blogs.size()); assertEquals(2, moreBlogs.size()); for(Map.Entry<Integer,Blog> blogEntry : blogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } for(Map.Entry<Integer,Blog> blogEntry : moreBlogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectMapOfBlogsByIdBetweenTwoSessionsWithGlobalCacheEnabled() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> blogs = mapper.selectBlogsAsMapById(); session.close(); //New Session session = sqlSessionFactory.openSession(); mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> moreBlogs = mapper.selectBlogsAsMapById(); assertEquals(2, blogs.size()); assertEquals(2, moreBlogs.size()); for(Map.Entry<Integer,Blog> blogEntry : blogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } for(Map.Entry<Integer,Blog> blogEntry : moreBlogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } } finally { session.close(); } } @Test public void shouldSelectListOfBlogsUsingXMLConfig() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Blog> blogs = mapper.selectBlogsFromXML(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectListOfBlogsStatementUsingProvider() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Blog> blogs = mapper.selectBlogsUsingProvider(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectListOfBlogsAsMaps() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Map<String,Object>> blogs = mapper.selectBlogsAsMaps(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldSelectListOfPostsLike() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPostsLike(new RowBounds(1,1),"%a%"); assertEquals(1, posts.size()); } finally { session.close(); } } @Test public void shouldSelectListOfPostsLikeTwoParameters() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPostsLikeSubjectAndBody(new RowBounds(1,1),"%a%","%a%"); assertEquals(1, posts.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectOneBlogStatement() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlog(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectOneBlogStatementWithConstructor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogUsingConstructor(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectBlogUsingConstructorWithResultMap() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogUsingConstructorWithResultMap(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Ignore @Test // issue #480 public void shouldExecuteBoundSelectBlogUsingConstructorWithResultMapCollection() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogUsingConstructorWithResultMapCollection(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectOneBlogStatementWithConstructorUsingXMLConfig() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogByIdUsingConstructor(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Test public void shouldSelectOneBlogAsMap() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<String,Object> blog = mapper.selectBlogAsMap(new HashMap<String, Object>() { { put("id", 1); } }); assertEquals(1, blog.get("ID")); assertEquals("Jim Business", blog.get("TITLE")); } finally { session.close(); } } @Test public void shouldSelectOneAuthor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = mapper.selectAuthor(101); assertEquals(101, author.getId()); assertEquals("jim", author.getUsername()); assertEquals("********", author.getPassword()); assertEquals("[email protected]", author.getEmail()); assertEquals("", author.getBio()); } finally { session.close(); } } @Test public void shouldSelectOneAuthorFromCache() { Author author1 = selectOneAuthor(); Author author2 = selectOneAuthor(); assertTrue("Same (cached) instance should be returned unless rollback is called.", author1 == author2); } private Author selectOneAuthor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); return mapper.selectAuthor(101); } finally { session.close(); } } @Test public void shouldSelectOneAuthorByConstructor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = mapper.selectAuthorConstructor(101); assertEquals(101, author.getId()); assertEquals("jim", author.getUsername()); assertEquals("********", author.getPassword()); assertEquals("[email protected]", author.getEmail()); assertEquals("", author.getBio()); } finally { session.close(); } } @Test public void shouldSelectDraftTypedPosts() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPosts(); assertEquals(5, posts.size()); assertTrue(posts.get(0) instanceof DraftPost); assertFalse(posts.get(1) instanceof DraftPost); assertTrue(posts.get(2) instanceof DraftPost); assertFalse(posts.get(3) instanceof DraftPost); assertFalse(posts.get(4) instanceof DraftPost); } finally { session.close(); } } @Test public void shouldSelectDraftTypedPostsWithResultMap() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPostsWithResultMap(); assertEquals(5, posts.size()); assertTrue(posts.get(0) instanceof DraftPost); assertFalse(posts.get(1) instanceof DraftPost); assertTrue(posts.get(2) instanceof DraftPost); assertFalse(posts.get(3) instanceof DraftPost); assertFalse(posts.get(4) instanceof DraftPost); } finally { session.close(); } } @Test public void shouldReturnANotNullToString() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); assertNotNull(mapper.toString()); } finally { session.close(); } } @Test public void shouldReturnANotNullHashCode() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); assertNotNull(mapper.hashCode()); } finally { session.close(); } } @Test public void shouldCompareTwoMappers() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); BoundBlogMapper mapper2 = session.getMapper(BoundBlogMapper.class); assertFalse(mapper.equals(mapper2)); } finally { session.close(); } } @Test(expected = Exception.class) public void shouldFailWhenSelectingOneBlogWithNonExistentParam() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); mapper.selectBlogByNonExistentParam(1); } finally { session.close(); } } @Test(expected = Exception.class) public void shouldFailWhenSelectingOneBlogWithNullParam() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); mapper.selectBlogByNullParam(null); } finally { session.close(); } } @Test // Decided that maps are dynamic so no existent params do not fail public void shouldFailWhenSelectingOneBlogWithNonExistentNestedParam() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); mapper.selectBlogByNonExistentNestedParam(1, Collections.<String, Object>emptyMap()); } finally { session.close(); } } @Test public void shouldSelectBlogWithDefault30ParamNames() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogByDefault30ParamNames(1, "Jim Business"); assertNotNull(blog); } finally { session.close(); } } @Test public void shouldSelectBlogWithDefault31ParamNames() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogByDefault31ParamNames(1, "Jim Business"); assertNotNull(blog); } finally { session.close(); } } @Test public void shouldSelectBlogWithAParamNamedValue() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogWithAParamNamedValue("id", 1, "Jim Business"); assertNotNull(blog); } finally { session.close(); } } @Test public void shouldCacheMapperMethod() throws Exception { final SqlSession session = sqlSessionFactory.openSession(); try { // Create another mapper instance with a method cache we can test against: final MapperProxyFactory<BoundBlogMapper> mapperProxyFactory = new MapperProxyFactory<BoundBlogMapper>(BoundBlogMapper.class); assertEquals(BoundBlogMapper.class, mapperProxyFactory.getMapperInterface()); final BoundBlogMapper mapper = mapperProxyFactory.newInstance(session); assertNotSame(mapper, mapperProxyFactory.newInstance(session)); assertTrue(mapperProxyFactory.getMethodCache().isEmpty()); // Mapper methods we will call later: final Method selectBlog = BoundBlogMapper.class.getMethod("selectBlog", Integer.TYPE); final Method selectBlogByIdUsingConstructor = BoundBlogMapper.class.getMethod("selectBlogByIdUsingConstructor", Integer.TYPE); // Call mapper method and verify it is cached: mapper.selectBlog(1); assertEquals(1, mapperProxyFactory.getMethodCache().size()); assertTrue(mapperProxyFactory.getMethodCache().containsKey(selectBlog)); final MapperMethod cachedSelectBlog = mapperProxyFactory.getMethodCache().get(selectBlog); // Call mapper method again and verify the cache is unchanged: session.clearCache(); mapper.selectBlog(1); assertEquals(1, mapperProxyFactory.getMethodCache().size()); assertSame(cachedSelectBlog, mapperProxyFactory.getMethodCache().get(selectBlog)); // Call another mapper method and verify that it shows up in the cache as well: session.clearCache(); mapper.selectBlogByIdUsingConstructor(1); assertEquals(2, mapperProxyFactory.getMethodCache().size()); assertSame(cachedSelectBlog, mapperProxyFactory.getMethodCache().get(selectBlog)); assertTrue(mapperProxyFactory.getMethodCache().containsKey(selectBlogByIdUsingConstructor)); } finally { session.close(); } } }
src/test/java/org/apache/ibatis/binding/BindingTest.java
/* * Copyright 2009-2012 The MyBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.binding; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertSame; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.executor.result.DefaultResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import domain.blog.Author; import domain.blog.Blog; import domain.blog.DraftPost; import domain.blog.Post; import domain.blog.Section; public class BindingTest { private static SqlSessionFactory sqlSessionFactory; @BeforeClass public static void setup() throws Exception { sqlSessionFactory = new IbatisConfig().getSqlSessionFactory(); } @Test public void shouldSelectBlogWithPostsUsingSubSelect() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog b = mapper.selectBlogWithPostsUsingSubSelect(1); assertEquals(1, b.getId()); session.close(); assertNotNull(b.getAuthor()); assertEquals(101, b.getAuthor().getId()); assertEquals("jim", b.getAuthor().getUsername()); assertEquals("********", b.getAuthor().getPassword()); assertEquals(2, b.getPosts().size()); } finally { session.close(); } } @Test public void shouldFindPostsInList() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); List<Post> posts = mapper.findPostsInList(new ArrayList<Integer>() {{ add(1); add(3); add(5); }}); assertEquals(3, posts.size()); session.rollback(); } finally { session.close(); } } @Test public void shouldFindPostsInArray() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Integer[] params = new Integer[]{1, 3, 5}; List<Post> posts = mapper.findPostsInArray(params); assertEquals(3, posts.size()); session.rollback(); } finally { session.close(); } } @Test public void shouldfindThreeSpecificPosts() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); List<Post> posts = mapper.findThreeSpecificPosts(1, new RowBounds(1, 1), 3, 5); assertEquals(1, posts.size()); assertEquals(3, posts.get(0).getId()); session.rollback(); } finally { session.close(); } } @Test public void shouldInsertAuthorWithSelectKey() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = new Author(-1, "cbegin", "******", "[email protected]", "N/A", Section.NEWS); int rows = mapper.insertAuthor(author); assertEquals(1, rows); session.rollback(); } finally { session.close(); } } @Test public void shouldInsertAuthorWithSelectKeyAndDynamicParams() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = new Author(-1, "cbegin", "******", "[email protected]", "N/A", Section.NEWS); int rows = mapper.insertAuthorDynamic(author); assertEquals(1, rows); assertFalse(-1 == author.getId()); // id must be autogenerated Author author2 = mapper.selectAuthor(author.getId()); assertNotNull(author2); assertEquals(author.getEmail(), author2.getEmail()); session.rollback(); } finally { session.close(); } } @Test public void shouldSelectRandom() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Integer x = mapper.selectRandom(); assertNotNull(x); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectListOfBlogsStatement() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Blog> blogs = mapper.selectBlogs(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectMapOfBlogsById() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> blogs = mapper.selectBlogsAsMapById(); assertEquals(2, blogs.size()); for(Map.Entry<Integer,Blog> blogEntry : blogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectOfBlogsByIdInWithProvidedResultHandlerBetweenSessions() { SqlSession session = sqlSessionFactory.openSession(); try { final DefaultResultHandler handler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", handler); //new session session.close(); session = sqlSessionFactory.openSession(); final DefaultResultHandler moreHandler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", moreHandler); assertEquals(2, handler.getResultList().size()); assertEquals(2, moreHandler.getResultList().size()); } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectOfBlogsByIdInWithProvidedResultHandlerInSameSession() { SqlSession session = sqlSessionFactory.openSession(); try { final DefaultResultHandler handler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", handler); final DefaultResultHandler moreHandler = new DefaultResultHandler(); session.select("selectBlogsAsMapById", moreHandler); assertEquals(2, handler.getResultList().size()); assertEquals(2, moreHandler.getResultList().size()); } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectMapOfBlogsByIdInSameSessionWithoutClearingLocalCache() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> blogs = mapper.selectBlogsAsMapById(); Map<Integer,Blog> moreBlogs = mapper.selectBlogsAsMapById(); assertEquals(2, blogs.size()); assertEquals(2, moreBlogs.size()); for(Map.Entry<Integer,Blog> blogEntry : blogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } for(Map.Entry<Integer,Blog> blogEntry : moreBlogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } } finally { session.close(); } } @Test public void shouldExecuteMultipleBoundSelectMapOfBlogsByIdBetweenTwoSessionsWithGlobalCacheEnabled() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> blogs = mapper.selectBlogsAsMapById(); session.close(); //New Session session = sqlSessionFactory.openSession(); mapper = session.getMapper(BoundBlogMapper.class); Map<Integer,Blog> moreBlogs = mapper.selectBlogsAsMapById(); assertEquals(2, blogs.size()); assertEquals(2, moreBlogs.size()); for(Map.Entry<Integer,Blog> blogEntry : blogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } for(Map.Entry<Integer,Blog> blogEntry : moreBlogs.entrySet()) { assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId()); } } finally { session.close(); } } @Test public void shouldSelectListOfBlogsUsingXMLConfig() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Blog> blogs = mapper.selectBlogsFromXML(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectListOfBlogsStatementUsingProvider() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Blog> blogs = mapper.selectBlogsUsingProvider(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectListOfBlogsAsMaps() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Map<String,Object>> blogs = mapper.selectBlogsAsMaps(); assertEquals(2, blogs.size()); } finally { session.close(); } } @Test public void shouldSelectListOfPostsLike() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPostsLike(new RowBounds(1,1),"%a%"); assertEquals(1, posts.size()); } finally { session.close(); } } @Test public void shouldSelectListOfPostsLikeTwoParameters() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPostsLikeSubjectAndBody(new RowBounds(1,1),"%a%","%a%"); assertEquals(1, posts.size()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectOneBlogStatement() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlog(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectOneBlogStatementWithConstructor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogUsingConstructor(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectBlogUsingConstructorWithResultMap() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogUsingConstructorWithResultMap(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Ignore @Test // issue #480 public void shouldExecuteBoundSelectBlogUsingConstructorWithResultMapCollection() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogUsingConstructorWithResultMapCollection(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Test public void shouldExecuteBoundSelectOneBlogStatementWithConstructorUsingXMLConfig() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogByIdUsingConstructor(1); assertEquals(1, blog.getId()); assertEquals("Jim Business", blog.getTitle()); assertNotNull("author should not be null", blog.getAuthor()); List<Post> posts = blog.getPosts(); assertTrue("posts should not be empty", posts != null && !posts.isEmpty()); } finally { session.close(); } } @Test public void shouldSelectOneBlogAsMap() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Map<String,Object> blog = mapper.selectBlogAsMap(new HashMap<String,Object>() { { put("id", 1); } }); assertEquals(1, blog.get("ID")); assertEquals("Jim Business", blog.get("TITLE")); } finally { session.close(); } } @Test public void shouldSelectOneAuthor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = mapper.selectAuthor(101); assertEquals(101, author.getId()); assertEquals("jim", author.getUsername()); assertEquals("********", author.getPassword()); assertEquals("[email protected]", author.getEmail()); assertEquals("", author.getBio()); } finally { session.close(); } } @Test public void shouldSelectOneAuthorFromCache() { Author author1 = selectOneAuthor(); Author author2 = selectOneAuthor(); assertTrue("Same (cached) instance should be returned unless rollback is called.", author1 == author2); } private Author selectOneAuthor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); return mapper.selectAuthor(101); } finally { session.close(); } } @Test public void shouldSelectOneAuthorByConstructor() { SqlSession session = sqlSessionFactory.openSession(); try { BoundAuthorMapper mapper = session.getMapper(BoundAuthorMapper.class); Author author = mapper.selectAuthorConstructor(101); assertEquals(101, author.getId()); assertEquals("jim", author.getUsername()); assertEquals("********", author.getPassword()); assertEquals("[email protected]", author.getEmail()); assertEquals("", author.getBio()); } finally { session.close(); } } @Test public void shouldSelectDraftTypedPosts() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPosts(); assertEquals(5, posts.size()); assertTrue(posts.get(0) instanceof DraftPost); assertFalse(posts.get(1) instanceof DraftPost); assertTrue(posts.get(2) instanceof DraftPost); assertFalse(posts.get(3) instanceof DraftPost); assertFalse(posts.get(4) instanceof DraftPost); } finally { session.close(); } } @Test public void shouldSelectDraftTypedPostsWithResultMap() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); List<Post> posts = mapper.selectPostsWithResultMap(); assertEquals(5, posts.size()); assertTrue(posts.get(0) instanceof DraftPost); assertFalse(posts.get(1) instanceof DraftPost); assertTrue(posts.get(2) instanceof DraftPost); assertFalse(posts.get(3) instanceof DraftPost); assertFalse(posts.get(4) instanceof DraftPost); } finally { session.close(); } } @Test public void shouldReturnANotNullToString() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); assertNotNull(mapper.toString()); } finally { session.close(); } } @Test public void shouldReturnANotNullHashCode() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); assertNotNull(mapper.hashCode()); } finally { session.close(); } } @Test public void shouldCompareTwoMappers() throws Exception { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); BoundBlogMapper mapper2 = session.getMapper(BoundBlogMapper.class); assertFalse(mapper.equals(mapper2)); } finally { session.close(); } } @Test(expected = Exception.class) public void shouldFailWhenSelectingOneBlogWithNonExistentParam() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); mapper.selectBlogByNonExistentParam(1); } finally { session.close(); } } @Test(expected = Exception.class) public void shouldFailWhenSelectingOneBlogWithNullParam() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); mapper.selectBlogByNullParam(null); } finally { session.close(); } } @Test // Decided that maps are dynamic so no existent params do not fail public void shouldFailWhenSelectingOneBlogWithNonExistentNestedParam() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); mapper.selectBlogByNonExistentNestedParam(1, Collections.<String, Object>emptyMap()); } finally { session.close(); } } @Test public void shouldSelectBlogWithDefault30ParamNames() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogByDefault30ParamNames(1, "Jim Business"); assertNotNull(blog); } finally { session.close(); } } @Test public void shouldSelectBlogWithDefault31ParamNames() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogByDefault31ParamNames(1, "Jim Business"); assertNotNull(blog); } finally { session.close(); } } @Test public void shouldSelectBlogWithAParamNamedValue() { SqlSession session = sqlSessionFactory.openSession(); try { BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); Blog blog = mapper.selectBlogWithAParamNamedValue("id", 1, "Jim Business"); assertNotNull(blog); } finally { session.close(); } } @Test public void shouldCacheMapperMethod() throws Exception { final SqlSession session = sqlSessionFactory.openSession(); try { // First register mapper interface with session to ensure it is correctly mapped: session.getMapper(BoundBlogMapper.class); // Create another mapper instance with a method cache we can test against: final Map<Method, MapperMethod> methodCache = new HashMap<Method, MapperMethod>(); final BoundBlogMapper mapper = MapperProxy.newMapperProxy(BoundBlogMapper.class, session, methodCache); // Mapper methods we will call later: final Method selectBlog = BoundBlogMapper.class.getMethod("selectBlog", Integer.TYPE); final Method selectBlogByIdUsingConstructor = BoundBlogMapper.class.getMethod("selectBlogByIdUsingConstructor", Integer.TYPE); // Call mapper method and verify it is cached: mapper.selectBlog(1); assertEquals(1, methodCache.size()); assertTrue(methodCache.containsKey(selectBlog)); final MapperMethod cachedSelectBlog = methodCache.get(selectBlog); // Call mapper method again and verify the cache is unchanged: session.clearCache(); mapper.selectBlog(1); assertEquals(1, methodCache.size()); assertSame(cachedSelectBlog, methodCache.get(selectBlog)); // Call another mapper method and verify that it shows up in the cache as well: session.clearCache(); mapper.selectBlogByIdUsingConstructor(1); assertEquals(2, methodCache.size()); assertSame(cachedSelectBlog, methodCache.get(selectBlog)); assertTrue(methodCache.containsKey(selectBlogByIdUsingConstructor)); } finally { session.close(); } } }
Forgot to commit the test, related to http://code.google.com/p/mybatis/issues/detail?id=734
src/test/java/org/apache/ibatis/binding/BindingTest.java
Forgot to commit the test, related to http://code.google.com/p/mybatis/issues/detail?id=734
<ide><path>rc/test/java/org/apache/ibatis/binding/BindingTest.java <ide> import static org.junit.Assert.assertFalse; <ide> import static org.junit.Assert.assertNotNull; <ide> import static org.junit.Assert.assertTrue; <add>import static org.junit.Assert.assertNotSame; <ide> import static org.junit.Assert.assertSame; <ide> <ide> import java.lang.reflect.Method; <ide> SqlSession session = sqlSessionFactory.openSession(); <ide> try { <ide> BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class); <del> Map<String,Object> blog = mapper.selectBlogAsMap(new HashMap<String,Object>() { <add> Map<String,Object> blog = mapper.selectBlogAsMap(new HashMap<String, Object>() { <ide> { <ide> put("id", 1); <ide> } <ide> public void shouldCacheMapperMethod() throws Exception { <ide> final SqlSession session = sqlSessionFactory.openSession(); <ide> try { <del> // First register mapper interface with session to ensure it is correctly mapped: <del> session.getMapper(BoundBlogMapper.class); <ide> <ide> // Create another mapper instance with a method cache we can test against: <del> final Map<Method, MapperMethod> methodCache = new HashMap<Method, MapperMethod>(); <del> final BoundBlogMapper mapper = MapperProxy.newMapperProxy(BoundBlogMapper.class, session, methodCache); <add> final MapperProxyFactory<BoundBlogMapper> mapperProxyFactory = new MapperProxyFactory<BoundBlogMapper>(BoundBlogMapper.class); <add> assertEquals(BoundBlogMapper.class, mapperProxyFactory.getMapperInterface()); <add> final BoundBlogMapper mapper = mapperProxyFactory.newInstance(session); <add> assertNotSame(mapper, mapperProxyFactory.newInstance(session)); <add> assertTrue(mapperProxyFactory.getMethodCache().isEmpty()); <ide> <ide> // Mapper methods we will call later: <ide> final Method selectBlog = BoundBlogMapper.class.getMethod("selectBlog", Integer.TYPE); <ide> <ide> // Call mapper method and verify it is cached: <ide> mapper.selectBlog(1); <del> assertEquals(1, methodCache.size()); <del> assertTrue(methodCache.containsKey(selectBlog)); <del> final MapperMethod cachedSelectBlog = methodCache.get(selectBlog); <add> assertEquals(1, mapperProxyFactory.getMethodCache().size()); <add> assertTrue(mapperProxyFactory.getMethodCache().containsKey(selectBlog)); <add> final MapperMethod cachedSelectBlog = mapperProxyFactory.getMethodCache().get(selectBlog); <ide> <ide> // Call mapper method again and verify the cache is unchanged: <ide> session.clearCache(); <ide> mapper.selectBlog(1); <del> assertEquals(1, methodCache.size()); <del> assertSame(cachedSelectBlog, methodCache.get(selectBlog)); <add> assertEquals(1, mapperProxyFactory.getMethodCache().size()); <add> assertSame(cachedSelectBlog, mapperProxyFactory.getMethodCache().get(selectBlog)); <ide> <ide> // Call another mapper method and verify that it shows up in the cache as well: <ide> session.clearCache(); <ide> mapper.selectBlogByIdUsingConstructor(1); <del> assertEquals(2, methodCache.size()); <del> assertSame(cachedSelectBlog, methodCache.get(selectBlog)); <del> assertTrue(methodCache.containsKey(selectBlogByIdUsingConstructor)); <add> assertEquals(2, mapperProxyFactory.getMethodCache().size()); <add> assertSame(cachedSelectBlog, mapperProxyFactory.getMethodCache().get(selectBlog)); <add> assertTrue(mapperProxyFactory.getMethodCache().containsKey(selectBlogByIdUsingConstructor)); <ide> <ide> } finally { <ide> session.close();
JavaScript
mit
5685d48efffe68b6fa6efe88b33058f67dbb275a
0
juice-project/juice,juice-project/juice,juice-project/juice,juice-project/juice
function talis_prism_metadef(){ juice.findMeta("isbns",".item #details .table .ISBN",juice.stringToAlphnumAray); juice.findMeta("isbn",".item #details .table .ISBN"); juice.findMeta("author",".item .summary .author .author"); juice.findMeta("title",".item .summary .title"); juice.findMeta("shelfmark","#availability .options table td:nth-child(2)"); juice.setMeta("shelfmark",talis_prism_dedup(juice.getValues('shelfmark'))); juice.findMeta("location","#availability .options h3 span"); juice.findMeta("workids",".item .summary > .title > a","href",talis_prism_items_workids); juice.setMeta("workid",talis_prism_item_workid); } function talis_prism_item_workid(){ var locationBits = document.location.pathname.split('/'); if(locationBits[locationBits.length - 2] == "items"){ return locationBits[locationBits.length - 1]; } return null; } function talis_prism_items_workids(val,id){ if(val){ var path = val.split('/'); if(path && path[0] == "items"){ var id = path[1].split("?"); return id[0]; } } } function talis_prism_dedup(a) { var i, r=[], o={}; for (i=0;i<a.length;i++) { if (!o[a[i]]){ o[a[i]]={}; r.push(a[i]); } } return r; }
metadefs/talis_prism_metadef.js
function talis_prism_metadef(){ juice.findMeta("isbns",".item > #details .table .ISBN",juice.stringToAlphnumAray); juice.findMeta("isbn",".item > #details .table .ISBN"); juice.findMeta("author",".item > .summary .author > .author"); juice.findMeta("title",".item > .summary > .title"); juice.findMeta("shelfmark","#availability > table > tbody > tr > td:nth-child(3)",null); juice.findMeta("location","#availability > table > tbody > tr > td:nth-child(2)",null); juice.findMeta("workids",".item > .summary > .title > a","href",talis_prism_items_workids); juice.setMeta("workid",talis_prism_item_workid); // juice.debugMeta(); } function talis_prism_item_workid(){ var locationBits = document.location.pathname.split('/'); if(locationBits[locationBits.length - 2] == "items"){ return locationBits[locationBits.length - 1]; } return null; } function talis_prism_items_workids(val,id){ if(val){ var path = val.split('/'); if(path && path[0] == "items"){ var id = path[1].split("?"); return id[0]; } } }
updated Prism 3 metadefs to work with page reworking
metadefs/talis_prism_metadef.js
updated Prism 3 metadefs to work with page reworking
<ide><path>etadefs/talis_prism_metadef.js <ide> function talis_prism_metadef(){ <del> juice.findMeta("isbns",".item > #details .table .ISBN",juice.stringToAlphnumAray); <del> juice.findMeta("isbn",".item > #details .table .ISBN"); <del> juice.findMeta("author",".item > .summary .author > .author"); <del> juice.findMeta("title",".item > .summary > .title"); <del> juice.findMeta("shelfmark","#availability > table > tbody > tr > td:nth-child(3)",null); <del> juice.findMeta("location","#availability > table > tbody > tr > td:nth-child(2)",null); <add> juice.findMeta("isbns",".item #details .table .ISBN",juice.stringToAlphnumAray); <add> juice.findMeta("isbn",".item #details .table .ISBN"); <add> juice.findMeta("author",".item .summary .author .author"); <add> juice.findMeta("title",".item .summary .title"); <add> <add> juice.findMeta("shelfmark","#availability .options table td:nth-child(2)"); <add> juice.setMeta("shelfmark",talis_prism_dedup(juice.getValues('shelfmark'))); <add> <add> juice.findMeta("location","#availability .options h3 span"); <ide> <del> juice.findMeta("workids",".item > .summary > .title > a","href",talis_prism_items_workids); <add> juice.findMeta("workids",".item .summary > .title > a","href",talis_prism_items_workids); <ide> juice.setMeta("workid",talis_prism_item_workid); <del> <del>// juice.debugMeta(); <ide> } <ide> <ide> function talis_prism_item_workid(){ <ide> <ide> } <ide> } <add> <add>function talis_prism_dedup(a) { <add> var i, r=[], o={}; <add> <add> for (i=0;i<a.length;i++) { <add> if (!o[a[i]]){ <add> o[a[i]]={}; <add> r.push(a[i]); <add> } <add> } <add> return r; <add> }
Java
mit
2d75298f4382bd8763d8aaef5af3f1ec9b99f7f1
0
sk89q/CommandHelper,sk89q/CommandHelper,sk89q/CommandHelper,sk89q/CommandHelper
package com.laytonsmith.PureUtilities.ClassLoading.ClassMirror; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import com.laytonsmith.PureUtilities.Common.StringUtils; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import static org.objectweb.asm.Opcodes.*; public class ClassMirrorVisitor extends ClassVisitor { private final ClassMirror.ClassInfo classInfo; ClassMirrorVisitor(ClassMirror.ClassInfo info) { super(Opcodes.ASM5); this.classInfo = info; } public ClassMirrorVisitor() { this(new ClassMirror.ClassInfo()); } public ClassMirror<?> getMirror(URL source) { if(!done) { throw new IllegalStateException(String.format( "Not done visiting %s", classInfo.name == null ? "none" : classInfo.name )); } return new ClassMirror<Object>(this.classInfo, source); } private boolean done; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if(done) { // Ensure we never visit more than one class throw new IllegalStateException(String.format( "Can't visit %s, because we already visited %s", name, classInfo.name )); } if ((access & ACC_ENUM) == ACC_ENUM) classInfo.isEnum = true; if ((access & ACC_INTERFACE) == ACC_INTERFACE) classInfo.isInterface = true; classInfo.modifiers = new ModifierMirror(ModifierMirror.Type.CLASS, access); classInfo.name = name; classInfo.classReferenceMirror = new ClassReferenceMirror(Type.getObjectType(name).getDescriptor()); classInfo.superClass = superName; classInfo.interfaces = interfaces; super.visit(version, access, name, signature, superName, interfaces); } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { final AnnotationMirror mirror = new AnnotationMirror(new ClassReferenceMirror(desc), visible); return new AnnotationMirrorVisitor(super.visitAnnotation(desc, visible), mirror) { @Override public void visitEnd() { classInfo.annotations.add(mirror); super.visitEnd(); } }; } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { final FieldMirror fieldMirror = new FieldMirror( classInfo.classReferenceMirror, new ModifierMirror(ModifierMirror.Type.FIELD, access), new ClassReferenceMirror(desc), name, value ); return new FieldVisitor(ASM5, super.visitField(access, name, desc, signature, value)) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { final AnnotationMirror annotationMirror = new AnnotationMirror(new ClassReferenceMirror(desc), visible); return new AnnotationMirrorVisitor(super.visitAnnotation(desc, visible), annotationMirror) { @Override public void visitEnd() { fieldMirror.addAnnotation(annotationMirror); super.visitEnd(); } }; } @Override public void visitEnd() { classInfo.fields.add(fieldMirror); super.visitEnd(); } }; } private static final Pattern STATIC_INITIALIZER_PATTERN = Pattern.compile("<clinit>"); @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (STATIC_INITIALIZER_PATTERN.matcher(name).matches()) return null; // Ignore static initializers if(ConstructorMirror.INIT.matches(name)){ // We want to replace the V at the end with the parent class type. // Yes, technically a constructor really does return void, but.. not really. desc = StringUtils.replaceLast(desc, "V", classInfo.classReferenceMirror.getJVMName()); } List<ClassReferenceMirror> parameterMirrors = new ArrayList<>(); for (Type type : Type.getArgumentTypes(desc)) { parameterMirrors.add(new ClassReferenceMirror(type.getDescriptor())); } AbstractMethodMirror _methodMirror; if(ConstructorMirror.INIT.equals(name)){ _methodMirror = new ConstructorMirror( classInfo.classReferenceMirror, new ModifierMirror(ModifierMirror.Type.METHOD, access), new ClassReferenceMirror(Type.getReturnType(desc).getDescriptor()), name, parameterMirrors, (access & ACC_VARARGS) == ACC_VARARGS, (access & ACC_SYNTHETIC) == ACC_SYNTHETIC ); } else { _methodMirror = new MethodMirror( classInfo.classReferenceMirror, new ModifierMirror(ModifierMirror.Type.METHOD, access), new ClassReferenceMirror(Type.getReturnType(desc).getDescriptor()), name, parameterMirrors, (access & ACC_VARARGS) == ACC_VARARGS, (access & ACC_SYNTHETIC) == ACC_SYNTHETIC ); } final AbstractMethodMirror methodMirror = _methodMirror; return new MethodVisitor(ASM5, super.visitMethod(access, name, desc, signature, exceptions)) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { final AnnotationMirror annotationMirror = new AnnotationMirror(new ClassReferenceMirror<>(desc), visible); return new AnnotationMirrorVisitor(super.visitAnnotation(desc, visible), annotationMirror) { @Override public void visitEnd() { methodMirror.addAnnotation(annotationMirror); } }; } @Override public void visitEnd() { classInfo.methods.add(methodMirror); super.visitEnd(); } }; } @Override public void visitEnd() { this.done = true; super.visitEnd(); } private static class AnnotationMirrorVisitor extends AnnotationVisitor { private final AnnotationMirror mirror; public AnnotationMirrorVisitor(AnnotationVisitor next, AnnotationMirror mirror) { super(ASM5, next); this.mirror = mirror; } @Override public void visit(String name, Object value) { if (value instanceof Type) value = ((Type) value).getDescriptor(); mirror.addAnnotationValue(name, value); super.visit(name, value); } } }
src/main/java/com/laytonsmith/PureUtilities/ClassLoading/ClassMirror/ClassMirrorVisitor.java
package com.laytonsmith.PureUtilities.ClassLoading.ClassMirror; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import com.google.common.base.Preconditions; import com.laytonsmith.PureUtilities.Common.StringUtils; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import static org.objectweb.asm.Opcodes.*; public class ClassMirrorVisitor extends ClassVisitor { private final ClassMirror.ClassInfo classInfo; ClassMirrorVisitor(ClassMirror.ClassInfo info) { super(Opcodes.ASM5); this.classInfo = info; } public ClassMirrorVisitor() { this(new ClassMirror.ClassInfo()); } public ClassMirror<?> getMirror(URL source) { Preconditions.checkState(done, "Not done visiting %s", classInfo.name == null ? "none" : classInfo.name); return new ClassMirror<Object>(this.classInfo, source); } private boolean done; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { Preconditions.checkState(!done, "Can't visit %s, because we already visited %s", name, classInfo.name); // Ensure we never visit more than one class if ((access & ACC_ENUM) == ACC_ENUM) classInfo.isEnum = true; if ((access & ACC_INTERFACE) == ACC_INTERFACE) classInfo.isInterface = true; classInfo.modifiers = new ModifierMirror(ModifierMirror.Type.CLASS, access); classInfo.name = name; classInfo.classReferenceMirror = new ClassReferenceMirror(Type.getObjectType(name).getDescriptor()); classInfo.superClass = superName; classInfo.interfaces = interfaces; super.visit(version, access, name, signature, superName, interfaces); } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { final AnnotationMirror mirror = new AnnotationMirror(new ClassReferenceMirror(desc), visible); return new AnnotationMirrorVisitor(super.visitAnnotation(desc, visible), mirror) { @Override public void visitEnd() { classInfo.annotations.add(mirror); super.visitEnd(); } }; } @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { final FieldMirror fieldMirror = new FieldMirror( classInfo.classReferenceMirror, new ModifierMirror(ModifierMirror.Type.FIELD, access), new ClassReferenceMirror(desc), name, value ); return new FieldVisitor(ASM5, super.visitField(access, name, desc, signature, value)) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { final AnnotationMirror annotationMirror = new AnnotationMirror(new ClassReferenceMirror(desc), visible); return new AnnotationMirrorVisitor(super.visitAnnotation(desc, visible), annotationMirror) { @Override public void visitEnd() { fieldMirror.addAnnotation(annotationMirror); super.visitEnd(); } }; } @Override public void visitEnd() { classInfo.fields.add(fieldMirror); super.visitEnd(); } }; } private static final Pattern STATIC_INITIALIZER_PATTERN = Pattern.compile("<clinit>"); @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (STATIC_INITIALIZER_PATTERN.matcher(name).matches()) return null; // Ignore static initializers if(ConstructorMirror.INIT.matches(name)){ // We want to replace the V at the end with the parent class type. // Yes, technically a constructor really does return void, but.. not really. desc = StringUtils.replaceLast(desc, "V", classInfo.classReferenceMirror.getJVMName()); } List<ClassReferenceMirror> parameterMirrors = new ArrayList<>(); for (Type type : Type.getArgumentTypes(desc)) { parameterMirrors.add(new ClassReferenceMirror(type.getDescriptor())); } AbstractMethodMirror _methodMirror; if(ConstructorMirror.INIT.equals(name)){ _methodMirror = new ConstructorMirror( classInfo.classReferenceMirror, new ModifierMirror(ModifierMirror.Type.METHOD, access), new ClassReferenceMirror(Type.getReturnType(desc).getDescriptor()), name, parameterMirrors, (access & ACC_VARARGS) == ACC_VARARGS, (access & ACC_SYNTHETIC) == ACC_SYNTHETIC ); } else { _methodMirror = new MethodMirror( classInfo.classReferenceMirror, new ModifierMirror(ModifierMirror.Type.METHOD, access), new ClassReferenceMirror(Type.getReturnType(desc).getDescriptor()), name, parameterMirrors, (access & ACC_VARARGS) == ACC_VARARGS, (access & ACC_SYNTHETIC) == ACC_SYNTHETIC ); } final AbstractMethodMirror methodMirror = _methodMirror; return new MethodVisitor(ASM5, super.visitMethod(access, name, desc, signature, exceptions)) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { final AnnotationMirror annotationMirror = new AnnotationMirror(new ClassReferenceMirror<>(desc), visible); return new AnnotationMirrorVisitor(super.visitAnnotation(desc, visible), annotationMirror) { @Override public void visitEnd() { methodMirror.addAnnotation(annotationMirror); } }; } @Override public void visitEnd() { classInfo.methods.add(methodMirror); super.visitEnd(); } }; } @Override public void visitEnd() { this.done = true; super.visitEnd(); } private static class AnnotationMirrorVisitor extends AnnotationVisitor { private final AnnotationMirror mirror; public AnnotationMirrorVisitor(AnnotationVisitor next, AnnotationMirror mirror) { super(ASM5, next); this.mirror = mirror; } @Override public void visit(String name, Object value) { if (value instanceof Type) value = ((Type) value).getDescriptor(); mirror.addAnnotationValue(name, value); super.visit(name, value); } } }
Remove random dependency on Guava
src/main/java/com/laytonsmith/PureUtilities/ClassLoading/ClassMirror/ClassMirrorVisitor.java
Remove random dependency on Guava
<ide><path>rc/main/java/com/laytonsmith/PureUtilities/ClassLoading/ClassMirror/ClassMirrorVisitor.java <ide> import java.util.List; <ide> import java.util.regex.Pattern; <ide> <del>import com.google.common.base.Preconditions; <ide> import com.laytonsmith.PureUtilities.Common.StringUtils; <ide> <ide> import org.objectweb.asm.AnnotationVisitor; <ide> } <ide> <ide> public ClassMirror<?> getMirror(URL source) { <del> Preconditions.checkState(done, "Not done visiting %s", classInfo.name == null ? "none" : classInfo.name); <add> if(!done) { <add> throw new IllegalStateException(String.format( <add> "Not done visiting %s", classInfo.name == null ? "none" : classInfo.name <add> )); <add> } <ide> return new ClassMirror<Object>(this.classInfo, source); <ide> } <ide> <ide> <ide> @Override <ide> public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { <del> Preconditions.checkState(!done, "Can't visit %s, because we already visited %s", name, classInfo.name); // Ensure we never visit more than one class <add> if(done) { <add> // Ensure we never visit more than one class <add> throw new IllegalStateException(String.format( <add> "Can't visit %s, because we already visited %s", name, classInfo.name <add> )); <add> } <ide> if ((access & ACC_ENUM) == ACC_ENUM) classInfo.isEnum = true; <ide> if ((access & ACC_INTERFACE) == ACC_INTERFACE) classInfo.isInterface = true; <ide> classInfo.modifiers = new ModifierMirror(ModifierMirror.Type.CLASS, access);
Java
apache-2.0
c71e125ca297798785598f3234ba9ff28b84a54e
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.log; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.OpenTHashSet; import com.intellij.util.messages.MessageBusConnection; import com.intellij.vcs.log.*; import com.intellij.vcs.log.data.VcsLogSorter; import com.intellij.vcs.log.graph.GraphColorManager; import com.intellij.vcs.log.graph.GraphCommit; import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl; import com.intellij.vcs.log.impl.HashImpl; import com.intellij.vcs.log.impl.LogDataImpl; import com.intellij.vcs.log.util.StopWatch; import com.intellij.vcs.log.util.UserNameRegex; import com.intellij.vcs.log.util.VcsUserUtil; import com.intellij.vcsUtil.VcsFileUtil; import com.intellij.vcsUtil.VcsUtil; import git4idea.*; import git4idea.branch.GitBranchUtil; import git4idea.branch.GitBranchesCollection; import git4idea.config.GitVersionSpecialty; import git4idea.history.GitLogUtil; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.repo.GitSubmodule; import git4idea.repo.GitSubmoduleKt; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.stream.Collectors; public class GitLogProvider implements VcsLogProvider { private static final Logger LOG = Logger.getInstance(GitLogProvider.class); public static final Function<VcsRef, String> GET_TAG_NAME = ref -> ref.getType() == GitRefManager.TAG ? ref.getName() : null; public static final TObjectHashingStrategy<VcsRef> DONT_CONSIDER_SHA = new TObjectHashingStrategy<VcsRef>() { @Override public int computeHashCode(@NotNull VcsRef ref) { return 31 * ref.getName().hashCode() + ref.getType().hashCode(); } @Override public boolean equals(@NotNull VcsRef ref1, @NotNull VcsRef ref2) { return ref1.getName().equals(ref2.getName()) && ref1.getType().equals(ref2.getType()); } }; @NotNull private final Project myProject; @NotNull private final GitVcs myVcs; @NotNull private final GitRepositoryManager myRepositoryManager; @NotNull private final GitUserRegistry myUserRegistry; @NotNull private final VcsLogRefManager myRefSorter; @NotNull private final VcsLogObjectsFactory myVcsObjectsFactory; public GitLogProvider(@NotNull Project project, @NotNull GitRepositoryManager repositoryManager, @NotNull VcsLogObjectsFactory factory, @NotNull GitUserRegistry userRegistry) { myProject = project; myRepositoryManager = repositoryManager; myUserRegistry = userRegistry; myRefSorter = new GitRefManager(myProject, myRepositoryManager); myVcsObjectsFactory = factory; myVcs = GitVcs.getInstance(project); } @NotNull @Override public DetailedLogData readFirstBlock(@NotNull VirtualFile root, @NotNull Requirements requirements) throws VcsException { if (!isRepositoryReady(root)) { return LogDataImpl.empty(); } GitRepository repository = ObjectUtils.assertNotNull(myRepositoryManager.getRepositoryForRoot(root)); // need to query more to sort them manually; this doesn't affect performance: it is equal for -1000 and -2000 int commitCount = requirements.getCommitCount() * 2; String[] params = new String[]{GitUtil.HEAD, "--branches", "--remotes", "--max-count=" + commitCount}; // NB: not specifying --tags, because it introduces great slowdown if there are many tags, // but makes sense only if there are heads without branch or HEAD labels (rare case). Such cases are partially handled below. boolean refresh = requirements instanceof VcsLogProviderRequirementsEx && ((VcsLogProviderRequirementsEx)requirements).isRefresh(); DetailedLogData data = GitLogUtil.collectMetadata(myProject, root, false, params); Set<VcsRef> safeRefs = data.getRefs(); Set<VcsRef> allRefs = new OpenTHashSet<>(safeRefs, DONT_CONSIDER_SHA); Set<VcsRef> branches = readBranches(repository); addNewElements(allRefs, branches); Collection<VcsCommitMetadata> allDetails; Set<String> currentTagNames = null; DetailedLogData commitsFromTags = null; if (!refresh) { allDetails = data.getCommits(); } else { // on refresh: get new tags, which point to commits not from the first block; then get history, walking down just from these tags // on init: just ignore such tagged-only branches. The price for speed-up. VcsLogProviderRequirementsEx rex = (VcsLogProviderRequirementsEx)requirements; currentTagNames = readCurrentTagNames(root); addOldStillExistingTags(allRefs, currentTagNames, rex.getPreviousRefs()); allDetails = newHashSet(data.getCommits()); Set<String> previousTags = newHashSet(ContainerUtil.mapNotNull(rex.getPreviousRefs(), GET_TAG_NAME)); Set<String> safeTags = newHashSet(ContainerUtil.mapNotNull(safeRefs, GET_TAG_NAME)); Set<String> newUnmatchedTags = remove(currentTagNames, previousTags, safeTags); if (!newUnmatchedTags.isEmpty()) { commitsFromTags = loadSomeCommitsOnTaggedBranches(root, commitCount, newUnmatchedTags); addNewElements(allDetails, commitsFromTags.getCommits()); addNewElements(allRefs, commitsFromTags.getRefs()); } } StopWatch sw = StopWatch.start("sorting commits in " + root.getName()); List<VcsCommitMetadata> sortedCommits = VcsLogSorter.sortByDateTopoOrder(allDetails); sortedCommits = ContainerUtil.getFirstItems(sortedCommits, requirements.getCommitCount()); sw.report(); if (LOG.isDebugEnabled()) { validateDataAndReportError(root, allRefs, sortedCommits, data, branches, currentTagNames, commitsFromTags); } return new LogDataImpl(allRefs, GitBekParentFixer.fixCommits(sortedCommits)); } private static void validateDataAndReportError(@NotNull final VirtualFile root, @NotNull final Set<? extends VcsRef> allRefs, @NotNull final List<? extends VcsCommitMetadata> sortedCommits, @NotNull final DetailedLogData firstBlockSyncData, @NotNull final Set<? extends VcsRef> manuallyReadBranches, @Nullable final Set<String> currentTagNames, @Nullable final DetailedLogData commitsFromTags) { StopWatch sw = StopWatch.start("validating data in " + root.getName()); final Set<Hash> refs = ContainerUtil.map2Set(allRefs, VcsRef::getCommitHash); PermanentGraphImpl.newInstance(sortedCommits, new GraphColorManager<Hash>() { @Override public int getColorOfBranch(@NotNull Hash headCommit) { return 0; } @Override public int getColorOfFragment(@NotNull Hash headCommit, int magicIndex) { return 0; } @Override public int compareHeads(@NotNull Hash head1, @NotNull Hash head2) { if (!refs.contains(head1) || !refs.contains(head2)) { LOG.error("GitLogProvider returned inconsistent data", new Attachment("error-details.txt", printErrorDetails(root, allRefs, sortedCommits, firstBlockSyncData, manuallyReadBranches, currentTagNames, commitsFromTags))); } return 0; } }, refs); sw.report(); } @SuppressWarnings("StringConcatenationInsideStringBufferAppend") private static String printErrorDetails(@NotNull VirtualFile root, @NotNull Set<? extends VcsRef> allRefs, @NotNull List<? extends VcsCommitMetadata> sortedCommits, @NotNull DetailedLogData firstBlockSyncData, @NotNull Set<? extends VcsRef> manuallyReadBranches, @Nullable Set<String> currentTagNames, @Nullable DetailedLogData commitsFromTags) { StringBuilder sb = new StringBuilder(); sb.append("[" + root.getName() + "]\n"); sb.append("First block data from Git:\n"); sb.append(printLogData(firstBlockSyncData)); sb.append("\n\nManually read refs:\n"); sb.append(printRefs(manuallyReadBranches)); sb.append("\n\nCurrent tag names:\n"); if (currentTagNames != null) { sb.append(StringUtil.join(currentTagNames, ", ")); if (commitsFromTags != null) { sb.append(printLogData(commitsFromTags)); } else { sb.append("\n\nCommits from new tags were not read.\n"); } } else { sb.append("\n\nCurrent tags were not read\n"); } sb.append("\n\nResult:\n"); sb.append("\nCommits (last 100): \n"); sb.append(printCommits(sortedCommits)); sb.append("\nAll refs:\n"); sb.append(printRefs(allRefs)); return sb.toString(); } @NotNull private static String printLogData(@NotNull DetailedLogData firstBlockSyncData) { return String .format("Last 100 commits:\n%s\nRefs:\n%s", printCommits(firstBlockSyncData.getCommits()), printRefs(firstBlockSyncData.getRefs())); } @NotNull private static String printCommits(@NotNull List<? extends VcsCommitMetadata> commits) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < Math.min(commits.size(), 100); i++) { GraphCommit<Hash> commit = commits.get(i); sb.append( String .format("%s -> %s\n", commit.getId().toShortString(), StringUtil.join(commit.getParents(), Hash::toShortString, ", "))); } return sb.toString(); } @NotNull private static String printRefs(@NotNull Set<? extends VcsRef> refs) { return StringUtil.join(refs, ref -> ref.getCommitHash().toShortString() + " : " + ref.getName(), "\n"); } private static void addOldStillExistingTags(@NotNull Set<? super VcsRef> allRefs, @NotNull Set<String> currentTags, @NotNull Collection<? extends VcsRef> previousRefs) { for (VcsRef ref : previousRefs) { if (!allRefs.contains(ref) && currentTags.contains(ref.getName())) { allRefs.add(ref); } } } @NotNull private Set<String> readCurrentTagNames(@NotNull VirtualFile root) throws VcsException { StopWatch sw = StopWatch.start("reading tags in " + root.getName()); Set<String> tags = newHashSet(); tags.addAll(GitBranchUtil.getAllTags(myProject, root)); sw.report(); return tags; } @NotNull private static <T> Set<T> remove(@NotNull Set<? extends T> original, @NotNull Set<T>... toRemove) { Set<T> result = newHashSet(original); for (Set<T> set : toRemove) { result.removeAll(set); } return result; } private static <T> void addNewElements(@NotNull Collection<? super T> original, @NotNull Collection<? extends T> toAdd) { for (T item : toAdd) { if (!original.contains(item)) { original.add(item); } } } @NotNull private DetailedLogData loadSomeCommitsOnTaggedBranches(@NotNull VirtualFile root, int commitCount, @NotNull Collection<String> unmatchedTags) throws VcsException { StopWatch sw = StopWatch.start("loading commits on tagged branch in " + root.getName()); List<String> params = new ArrayList<>(); params.add("--max-count=" + commitCount); Set<VcsRef> refs = ContainerUtil.newHashSet(); Set<VcsCommitMetadata> commits = ContainerUtil.newHashSet(); VcsFileUtil.foreachChunk(new ArrayList<>(unmatchedTags), 1, tagsChunk -> { String[] parameters = ArrayUtil.toStringArray(ContainerUtil.concat(params, tagsChunk)); DetailedLogData logData = GitLogUtil.collectMetadata(myProject, root, false, parameters); refs.addAll(logData.getRefs()); commits.addAll(logData.getCommits()); }); sw.report(); return new LogDataImpl(refs, ContainerUtil.newArrayList(commits)); } @Override @NotNull public LogData readAllHashes(@NotNull VirtualFile root, @NotNull final Consumer<? super TimedVcsCommit> commitConsumer) throws VcsException { if (!isRepositoryReady(root)) { return LogDataImpl.empty(); } List<String> parameters = new ArrayList<>(GitLogUtil.LOG_ALL); parameters.add("--date-order"); final GitBekParentFixer parentFixer = GitBekParentFixer.prepare(myProject, root); Set<VcsUser> userRegistry = newHashSet(); Set<VcsRef> refs = newHashSet(); GitLogUtil.readTimedCommits(myProject, root, parameters, new CollectConsumer<>(userRegistry), new CollectConsumer<>(refs), commit -> commitConsumer.consume(parentFixer.fixCommit(commit))); return new LogDataImpl(refs, userRegistry); } @Override public void readAllFullDetails(@NotNull VirtualFile root, @NotNull Consumer<? super VcsFullCommitDetails> commitConsumer) throws VcsException { if (!isRepositoryReady(root)) { return; } GitLogUtil.readFullDetails(myProject, root, commitConsumer, shouldIncludeRootChanges(root), false, true, ArrayUtil.toStringArray(GitLogUtil.LOG_ALL)); } @Override public void readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes, @NotNull Consumer<? super VcsFullCommitDetails> commitConsumer) throws VcsException { if (!isRepositoryReady(root)) { return; } GitLogUtil.readFullDetailsForHashes(myProject, root, myVcs, commitConsumer, hashes, shouldIncludeRootChanges(root), false, GitLogUtil.DiffRenameLimit.GIT_CONFIG); } @Override public void readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes, @NotNull Consumer<? super VcsFullCommitDetails> commitConsumer, boolean isForIndexing) throws VcsException { if (!isRepositoryReady(root)) { return; } GitLogUtil.readFullDetailsForHashes(myProject, root, myVcs, commitConsumer, hashes, shouldIncludeRootChanges(root), isForIndexing, isForIndexing ? GitLogUtil.DiffRenameLimit.REGISTRY : GitLogUtil.DiffRenameLimit.INFINITY); } private boolean shouldIncludeRootChanges(@NotNull VirtualFile root) { GitRepository repository = getRepository(root); if (repository == null) return true; return !repository.getInfo().isShallow(); } @NotNull @Override public List<? extends VcsCommitMetadata> readMetadata(@NotNull final VirtualFile root, @NotNull List<String> hashes) throws VcsException { return GitLogUtil.collectShortDetails(myProject, myVcs, root, hashes); } @NotNull private Set<VcsRef> readBranches(@NotNull GitRepository repository) { StopWatch sw = StopWatch.start("readBranches in " + repository.getRoot().getName()); VirtualFile root = repository.getRoot(); repository.update(); GitBranchesCollection branches = repository.getBranches(); Collection<GitLocalBranch> localBranches = branches.getLocalBranches(); Collection<GitRemoteBranch> remoteBranches = branches.getRemoteBranches(); Set<VcsRef> refs = new THashSet<>(localBranches.size() + remoteBranches.size()); for (GitLocalBranch localBranch : localBranches) { Hash hash = branches.getHash(localBranch); assert hash != null; refs.add(myVcsObjectsFactory.createRef(hash, localBranch.getName(), GitRefManager.LOCAL_BRANCH, root)); } for (GitRemoteBranch remoteBranch : remoteBranches) { Hash hash = branches.getHash(remoteBranch); assert hash != null; refs.add(myVcsObjectsFactory.createRef(hash, remoteBranch.getNameForLocalOperations(), GitRefManager.REMOTE_BRANCH, root)); } String currentRevision = repository.getCurrentRevision(); if (currentRevision != null) { // null => fresh repository refs.add(myVcsObjectsFactory.createRef(HashImpl.build(currentRevision), GitUtil.HEAD, GitRefManager.HEAD, root)); } sw.report(); return refs; } @NotNull @Override public VcsKey getSupportedVcs() { return GitVcs.getKey(); } @NotNull @Override public VcsLogRefManager getReferenceManager() { return myRefSorter; } @NotNull @Override public Disposable subscribeToRootRefreshEvents(@NotNull final Collection<? extends VirtualFile> roots, @NotNull final VcsLogRefresher refresher) { MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(GitRepository.GIT_REPO_CHANGE, repository -> { VirtualFile root = repository.getRoot(); if (roots.contains(root)) { refresher.refresh(root); } }); return connection; } @NotNull @Override public List<TimedVcsCommit> getCommitsMatchingFilter(@NotNull final VirtualFile root, @NotNull VcsLogFilterCollection filterCollection, int maxCount) throws VcsException { if (!isRepositoryReady(root)) { return Collections.emptyList(); } List<String> filterParameters = ContainerUtil.newArrayList(); VcsLogBranchFilter branchFilter = filterCollection.get(VcsLogFilterCollection.BRANCH_FILTER); VcsLogRevisionFilter revisionFilter = filterCollection.get(VcsLogFilterCollection.REVISION_FILTER); if (branchFilter != null || revisionFilter != null) { boolean atLeastOneBranchExists = false; if (branchFilter != null) { GitRepository repository = getRepository(root); assert repository != null : "repository is null for root " + root + " but was previously reported as 'ready'"; Collection<GitBranch> branches = ContainerUtil .newArrayList(ContainerUtil.concat(repository.getBranches().getLocalBranches(), repository.getBranches().getRemoteBranches())); Collection<String> branchNames = GitBranchUtil.convertBranchesToNames(branches); Collection<String> predefinedNames = ContainerUtil.list(GitUtil.HEAD); for (String branchName : ContainerUtil.concat(branchNames, predefinedNames)) { if (branchFilter.matches(branchName)) { filterParameters.add(branchName); atLeastOneBranchExists = true; } } } if (revisionFilter != null) { for (CommitId commit : revisionFilter.getHeads()) { if (commit.getRoot().equals(root)) { filterParameters.add(commit.getHash().asString()); atLeastOneBranchExists = true; } } } if (!atLeastOneBranchExists) { // no such branches in this repository => filter matches nothing return Collections.emptyList(); } } else { filterParameters.addAll(GitLogUtil.LOG_ALL); } VcsLogDateFilter dateFilter = filterCollection.get(VcsLogFilterCollection.DATE_FILTER); if (dateFilter != null) { // assuming there is only one date filter, until filter expressions are defined if (dateFilter.getAfter() != null) { filterParameters.add(prepareParameter("after", dateFilter.getAfter().toString())); } if (dateFilter.getBefore() != null) { filterParameters.add(prepareParameter("before", dateFilter.getBefore().toString())); } } VcsLogTextFilter textFilter = filterCollection.get(VcsLogFilterCollection.TEXT_FILTER); String text = textFilter != null ? textFilter.getText() : null; boolean regexp = textFilter == null || textFilter.isRegex(); boolean caseSensitive = textFilter != null && textFilter.matchesCase(); appendTextFilterParameters(text, regexp, caseSensitive, filterParameters); VcsLogUserFilter userFilter = filterCollection.get(VcsLogFilterCollection.USER_FILTER); if (userFilter != null) { Collection<String> names = ContainerUtil.map(userFilter.getUsers(root), VcsUserUtil::toExactString); if (regexp) { List<String> authors = ContainerUtil.map(names, UserNameRegex.EXTENDED_INSTANCE); if (GitVersionSpecialty.LOG_AUTHOR_FILTER_SUPPORTS_VERTICAL_BAR.existsIn(myVcs.getVersion())) { filterParameters.add(prepareParameter("author", StringUtil.join(authors, "|"))); } else { filterParameters.addAll(ContainerUtil.map(authors, a -> prepareParameter("author", a))); } } else { filterParameters.addAll(ContainerUtil.map(names, a -> prepareParameter("author", StringUtil.escapeBackSlashes(a)))); } } if (maxCount > 0) { filterParameters.add(prepareParameter("max-count", String.valueOf(maxCount))); } // note: structure filter must be the last parameter, because it uses "--" which separates parameters from paths VcsLogStructureFilter structureFilter = filterCollection.get(VcsLogFilterCollection.STRUCTURE_FILTER); if (structureFilter != null) { Collection<FilePath> files = structureFilter.getFiles(); if (!files.isEmpty()) { filterParameters.add("--full-history"); filterParameters.add("--simplify-merges"); filterParameters.add("--"); for (FilePath file : files) { filterParameters.add(VcsFileUtil.relativePath(root, file)); } } } List<TimedVcsCommit> commits = ContainerUtil.newArrayList(); GitLogUtil.readTimedCommits(myProject, root, filterParameters, EmptyConsumer.getInstance(), EmptyConsumer.getInstance(), new CollectConsumer<>(commits)); return commits; } public static void appendTextFilterParameters(@Nullable String text, boolean regexp, boolean caseSensitive, @NotNull List<? super String> filterParameters) { if (text != null) { filterParameters.add(prepareParameter("grep", text)); } filterParameters.add(regexp ? "--extended-regexp" : "--fixed-strings"); if (!caseSensitive) { filterParameters.add("--regexp-ignore-case"); // affects case sensitivity of any filter (except file filter) } } @Nullable @Override public VcsUser getCurrentUser(@NotNull VirtualFile root) { return myUserRegistry.getOrReadUser(root); } @NotNull @Override public Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException { return GitBranchUtil.getBranches(myProject, root, true, true, commitHash.asString()); } @Nullable @Override public String getCurrentBranch(@NotNull VirtualFile root) { GitRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) return null; String currentBranchName = repository.getCurrentBranchName(); if (currentBranchName == null && repository.getCurrentRevision() != null) { return GitUtil.HEAD; } return currentBranchName; } @Nullable @Override public VcsLogDiffHandler getDiffHandler() { return new GitLogDiffHandler(myProject); } @Nullable @Override public VirtualFile getVcsRoot(@NotNull Project project, @NotNull FilePath path) { VirtualFile file = path.getVirtualFile(); if (file != null && file.isDirectory()) { GitRepository repository = myRepositoryManager.getRepositoryForRoot(file); if (repository != null) { GitSubmodule submodule = GitSubmoduleKt.asSubmodule(repository); if (submodule != null) { return submodule.getParent().getRoot(); } } } return VcsUtil.getVcsRootFor(project, path); } @SuppressWarnings("unchecked") @Nullable @Override public <T> T getPropertyValue(VcsLogProperties.VcsLogProperty<T> property) { if (property == VcsLogProperties.LIGHTWEIGHT_BRANCHES) { return (T)Boolean.TRUE; } else if (property == VcsLogProperties.SUPPORTS_INDEXING) { return (T)Boolean.valueOf(isIndexingOn()); } return null; } public static boolean isIndexingOn() { return Registry.is("vcs.log.index.git"); } private static String prepareParameter(String paramName, String value) { return "--" + paramName + "=" + value; // no value quoting needed, because the parameter itself will be quoted by GeneralCommandLine } @Nullable private GitRepository getRepository(@NotNull VirtualFile root) { return myRepositoryManager.getRepositoryForRoot(root); } private boolean isRepositoryReady(@NotNull VirtualFile root) { GitRepository repository = getRepository(root); if (repository == null) { LOG.error("Repository not found for root " + root); return false; } else if (repository.isFresh()) { LOG.info("Fresh repository: " + root); return false; } return true; } @NotNull private static <T> Set<T> newHashSet() { return new THashSet<>(); } @NotNull private static <T> Set<T> newHashSet(@NotNull Collection<? extends T> initialCollection) { return new THashSet<>(initialCollection); } }
plugins/git4idea/src/git4idea/log/GitLogProvider.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.log; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.OpenTHashSet; import com.intellij.util.messages.MessageBusConnection; import com.intellij.vcs.log.*; import com.intellij.vcs.log.data.VcsLogSorter; import com.intellij.vcs.log.graph.GraphColorManager; import com.intellij.vcs.log.graph.GraphCommit; import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl; import com.intellij.vcs.log.impl.HashImpl; import com.intellij.vcs.log.impl.LogDataImpl; import com.intellij.vcs.log.util.StopWatch; import com.intellij.vcs.log.util.UserNameRegex; import com.intellij.vcs.log.util.VcsUserUtil; import com.intellij.vcsUtil.VcsFileUtil; import com.intellij.vcsUtil.VcsUtil; import git4idea.*; import git4idea.branch.GitBranchUtil; import git4idea.branch.GitBranchesCollection; import git4idea.config.GitVersionSpecialty; import git4idea.history.GitLogUtil; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.repo.GitSubmodule; import git4idea.repo.GitSubmoduleKt; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.stream.Collectors; public class GitLogProvider implements VcsLogProvider { private static final Logger LOG = Logger.getInstance(GitLogProvider.class); public static final Function<VcsRef, String> GET_TAG_NAME = ref -> ref.getType() == GitRefManager.TAG ? ref.getName() : null; public static final TObjectHashingStrategy<VcsRef> DONT_CONSIDER_SHA = new TObjectHashingStrategy<VcsRef>() { @Override public int computeHashCode(@NotNull VcsRef ref) { return 31 * ref.getName().hashCode() + ref.getType().hashCode(); } @Override public boolean equals(@NotNull VcsRef ref1, @NotNull VcsRef ref2) { return ref1.getName().equals(ref2.getName()) && ref1.getType().equals(ref2.getType()); } }; @NotNull private final Project myProject; @NotNull private final GitVcs myVcs; @NotNull private final GitRepositoryManager myRepositoryManager; @NotNull private final GitUserRegistry myUserRegistry; @NotNull private final VcsLogRefManager myRefSorter; @NotNull private final VcsLogObjectsFactory myVcsObjectsFactory; public GitLogProvider(@NotNull Project project, @NotNull GitRepositoryManager repositoryManager, @NotNull VcsLogObjectsFactory factory, @NotNull GitUserRegistry userRegistry) { myProject = project; myRepositoryManager = repositoryManager; myUserRegistry = userRegistry; myRefSorter = new GitRefManager(myProject, myRepositoryManager); myVcsObjectsFactory = factory; myVcs = GitVcs.getInstance(project); } @NotNull @Override public DetailedLogData readFirstBlock(@NotNull VirtualFile root, @NotNull Requirements requirements) throws VcsException { if (!isRepositoryReady(root)) { return LogDataImpl.empty(); } GitRepository repository = ObjectUtils.assertNotNull(myRepositoryManager.getRepositoryForRoot(root)); // need to query more to sort them manually; this doesn't affect performance: it is equal for -1000 and -2000 int commitCount = requirements.getCommitCount() * 2; String[] params = new String[]{GitUtil.HEAD, "--branches", "--remotes", "--max-count=" + commitCount}; // NB: not specifying --tags, because it introduces great slowdown if there are many tags, // but makes sense only if there are heads without branch or HEAD labels (rare case). Such cases are partially handled below. boolean refresh = requirements instanceof VcsLogProviderRequirementsEx && ((VcsLogProviderRequirementsEx)requirements).isRefresh(); DetailedLogData data = GitLogUtil.collectMetadata(myProject, root, false, params); Set<VcsRef> safeRefs = data.getRefs(); Set<VcsRef> allRefs = new OpenTHashSet<>(safeRefs, DONT_CONSIDER_SHA); Set<VcsRef> branches = readBranches(repository); addNewElements(allRefs, branches); Collection<VcsCommitMetadata> allDetails; Set<String> currentTagNames = null; DetailedLogData commitsFromTags = null; if (!refresh) { allDetails = data.getCommits(); } else { // on refresh: get new tags, which point to commits not from the first block; then get history, walking down just from these tags // on init: just ignore such tagged-only branches. The price for speed-up. VcsLogProviderRequirementsEx rex = (VcsLogProviderRequirementsEx)requirements; currentTagNames = readCurrentTagNames(root); addOldStillExistingTags(allRefs, currentTagNames, rex.getPreviousRefs()); allDetails = newHashSet(data.getCommits()); Set<String> previousTags = newHashSet(ContainerUtil.mapNotNull(rex.getPreviousRefs(), GET_TAG_NAME)); Set<String> safeTags = newHashSet(ContainerUtil.mapNotNull(safeRefs, GET_TAG_NAME)); Set<String> newUnmatchedTags = remove(currentTagNames, previousTags, safeTags); if (!newUnmatchedTags.isEmpty()) { commitsFromTags = loadSomeCommitsOnTaggedBranches(root, commitCount, newUnmatchedTags); addNewElements(allDetails, commitsFromTags.getCommits()); addNewElements(allRefs, commitsFromTags.getRefs()); } } StopWatch sw = StopWatch.start("sorting commits in " + root.getName()); List<VcsCommitMetadata> sortedCommits = VcsLogSorter.sortByDateTopoOrder(allDetails); sortedCommits = ContainerUtil.getFirstItems(sortedCommits, requirements.getCommitCount()); sw.report(); if (LOG.isDebugEnabled()) { validateDataAndReportError(root, allRefs, sortedCommits, data, branches, currentTagNames, commitsFromTags); } return new LogDataImpl(allRefs, GitBekParentFixer.fixCommits(sortedCommits)); } private static void validateDataAndReportError(@NotNull final VirtualFile root, @NotNull final Set<? extends VcsRef> allRefs, @NotNull final List<? extends VcsCommitMetadata> sortedCommits, @NotNull final DetailedLogData firstBlockSyncData, @NotNull final Set<? extends VcsRef> manuallyReadBranches, @Nullable final Set<String> currentTagNames, @Nullable final DetailedLogData commitsFromTags) { StopWatch sw = StopWatch.start("validating data in " + root.getName()); final Set<Hash> refs = ContainerUtil.map2Set(allRefs, VcsRef::getCommitHash); PermanentGraphImpl.newInstance(sortedCommits, new GraphColorManager<Hash>() { @Override public int getColorOfBranch(@NotNull Hash headCommit) { return 0; } @Override public int getColorOfFragment(@NotNull Hash headCommit, int magicIndex) { return 0; } @Override public int compareHeads(@NotNull Hash head1, @NotNull Hash head2) { if (!refs.contains(head1) || !refs.contains(head2)) { LOG.error("GitLogProvider returned inconsistent data", new Attachment("error-details.txt", printErrorDetails(root, allRefs, sortedCommits, firstBlockSyncData, manuallyReadBranches, currentTagNames, commitsFromTags))); } return 0; } }, refs); sw.report(); } @SuppressWarnings("StringConcatenationInsideStringBufferAppend") private static String printErrorDetails(@NotNull VirtualFile root, @NotNull Set<? extends VcsRef> allRefs, @NotNull List<? extends VcsCommitMetadata> sortedCommits, @NotNull DetailedLogData firstBlockSyncData, @NotNull Set<? extends VcsRef> manuallyReadBranches, @Nullable Set<String> currentTagNames, @Nullable DetailedLogData commitsFromTags) { StringBuilder sb = new StringBuilder(); sb.append("[" + root.getName() + "]\n"); sb.append("First block data from Git:\n"); sb.append(printLogData(firstBlockSyncData)); sb.append("\n\nManually read refs:\n"); sb.append(printRefs(manuallyReadBranches)); sb.append("\n\nCurrent tag names:\n"); if (currentTagNames != null) { sb.append(StringUtil.join(currentTagNames, ", ")); if (commitsFromTags != null) { sb.append(printLogData(commitsFromTags)); } else { sb.append("\n\nCommits from new tags were not read.\n"); } } else { sb.append("\n\nCurrent tags were not read\n"); } sb.append("\n\nResult:\n"); sb.append("\nCommits (last 100): \n"); sb.append(printCommits(sortedCommits)); sb.append("\nAll refs:\n"); sb.append(printRefs(allRefs)); return sb.toString(); } @NotNull private static String printLogData(@NotNull DetailedLogData firstBlockSyncData) { return String .format("Last 100 commits:\n%s\nRefs:\n%s", printCommits(firstBlockSyncData.getCommits()), printRefs(firstBlockSyncData.getRefs())); } @NotNull private static String printCommits(@NotNull List<? extends VcsCommitMetadata> commits) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < Math.min(commits.size(), 100); i++) { GraphCommit<Hash> commit = commits.get(i); sb.append( String .format("%s -> %s\n", commit.getId().toShortString(), StringUtil.join(commit.getParents(), Hash::toShortString, ", "))); } return sb.toString(); } @NotNull private static String printRefs(@NotNull Set<? extends VcsRef> refs) { return StringUtil.join(refs, ref -> ref.getCommitHash().toShortString() + " : " + ref.getName(), "\n"); } private static void addOldStillExistingTags(@NotNull Set<? super VcsRef> allRefs, @NotNull Set<String> currentTags, @NotNull Collection<? extends VcsRef> previousRefs) { for (VcsRef ref : previousRefs) { if (!allRefs.contains(ref) && currentTags.contains(ref.getName())) { allRefs.add(ref); } } } @NotNull private Set<String> readCurrentTagNames(@NotNull VirtualFile root) throws VcsException { StopWatch sw = StopWatch.start("reading tags in " + root.getName()); Set<String> tags = newHashSet(); tags.addAll(GitBranchUtil.getAllTags(myProject, root)); sw.report(); return tags; } @NotNull private static <T> Set<T> remove(@NotNull Set<? extends T> original, @NotNull Set<T>... toRemove) { Set<T> result = newHashSet(original); for (Set<T> set : toRemove) { result.removeAll(set); } return result; } private static <T> void addNewElements(@NotNull Collection<? super T> original, @NotNull Collection<? extends T> toAdd) { for (T item : toAdd) { if (!original.contains(item)) { original.add(item); } } } @NotNull private DetailedLogData loadSomeCommitsOnTaggedBranches(@NotNull VirtualFile root, int commitCount, @NotNull Collection<String> unmatchedTags) throws VcsException { StopWatch sw = StopWatch.start("loading commits on tagged branch in " + root.getName()); List<String> params = new ArrayList<>(); params.add("--max-count=" + commitCount); Set<VcsRef> refs = ContainerUtil.newHashSet(); Set<VcsCommitMetadata> commits = ContainerUtil.newHashSet(); VcsFileUtil.foreachChunk(new ArrayList<>(unmatchedTags), 1, tagsChunk -> { String[] parameters = ArrayUtil.toStringArray(ContainerUtil.concat(params, tagsChunk)); DetailedLogData logData = GitLogUtil.collectMetadata(myProject, root, false, parameters); refs.addAll(logData.getRefs()); commits.addAll(logData.getCommits()); }); sw.report(); return new LogDataImpl(refs, ContainerUtil.newArrayList(commits)); } @Override @NotNull public LogData readAllHashes(@NotNull VirtualFile root, @NotNull final Consumer<? super TimedVcsCommit> commitConsumer) throws VcsException { if (!isRepositoryReady(root)) { return LogDataImpl.empty(); } List<String> parameters = new ArrayList<>(GitLogUtil.LOG_ALL); parameters.add("--date-order"); final GitBekParentFixer parentFixer = GitBekParentFixer.prepare(myProject, root); Set<VcsUser> userRegistry = newHashSet(); Set<VcsRef> refs = newHashSet(); GitLogUtil.readTimedCommits(myProject, root, parameters, new CollectConsumer<>(userRegistry), new CollectConsumer<>(refs), commit -> commitConsumer.consume(parentFixer.fixCommit(commit))); return new LogDataImpl(refs, userRegistry); } @Override public void readAllFullDetails(@NotNull VirtualFile root, @NotNull Consumer<? super VcsFullCommitDetails> commitConsumer) throws VcsException { if (!isRepositoryReady(root)) { return; } GitLogUtil.readFullDetails(myProject, root, commitConsumer, shouldIncludeRootChanges(root), false, true, ArrayUtil.toStringArray(GitLogUtil.LOG_ALL)); } @Override public void readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes, @NotNull Consumer<? super VcsFullCommitDetails> commitConsumer) throws VcsException { if (!isRepositoryReady(root)) { return; } GitLogUtil.readFullDetailsForHashes(myProject, root, myVcs, commitConsumer, hashes, shouldIncludeRootChanges(root), false, GitLogUtil.DiffRenameLimit.GIT_CONFIG); } @Override public void readFullDetails(@NotNull VirtualFile root, @NotNull List<String> hashes, @NotNull Consumer<? super VcsFullCommitDetails> commitConsumer, boolean isForIndexing) throws VcsException { if (!isRepositoryReady(root)) { return; } GitLogUtil.readFullDetailsForHashes(myProject, root, myVcs, commitConsumer, hashes, shouldIncludeRootChanges(root), isForIndexing, isForIndexing ? GitLogUtil.DiffRenameLimit.REGISTRY : GitLogUtil.DiffRenameLimit.INFINITY); } private boolean shouldIncludeRootChanges(@NotNull VirtualFile root) { GitRepository repository = getRepository(root); if (repository == null) return true; return !repository.getInfo().isShallow(); } @NotNull @Override public List<? extends VcsCommitMetadata> readMetadata(@NotNull final VirtualFile root, @NotNull List<String> hashes) throws VcsException { return GitLogUtil.collectShortDetails(myProject, myVcs, root, hashes); } @NotNull private Set<VcsRef> readBranches(@NotNull GitRepository repository) { StopWatch sw = StopWatch.start("readBranches in " + repository.getRoot().getName()); VirtualFile root = repository.getRoot(); repository.update(); GitBranchesCollection branches = repository.getBranches(); Collection<GitLocalBranch> localBranches = branches.getLocalBranches(); Collection<GitRemoteBranch> remoteBranches = branches.getRemoteBranches(); Set<VcsRef> refs = new THashSet<>(localBranches.size() + remoteBranches.size()); for (GitLocalBranch localBranch : localBranches) { Hash hash = branches.getHash(localBranch); assert hash != null; refs.add(myVcsObjectsFactory.createRef(hash, localBranch.getName(), GitRefManager.LOCAL_BRANCH, root)); } for (GitRemoteBranch remoteBranch : remoteBranches) { Hash hash = branches.getHash(remoteBranch); assert hash != null; refs.add(myVcsObjectsFactory.createRef(hash, remoteBranch.getNameForLocalOperations(), GitRefManager.REMOTE_BRANCH, root)); } String currentRevision = repository.getCurrentRevision(); if (currentRevision != null) { // null => fresh repository refs.add(myVcsObjectsFactory.createRef(HashImpl.build(currentRevision), GitUtil.HEAD, GitRefManager.HEAD, root)); } sw.report(); return refs; } @NotNull @Override public VcsKey getSupportedVcs() { return GitVcs.getKey(); } @NotNull @Override public VcsLogRefManager getReferenceManager() { return myRefSorter; } @NotNull @Override public Disposable subscribeToRootRefreshEvents(@NotNull final Collection<? extends VirtualFile> roots, @NotNull final VcsLogRefresher refresher) { MessageBusConnection connection = myProject.getMessageBus().connect(myProject); connection.subscribe(GitRepository.GIT_REPO_CHANGE, repository -> { VirtualFile root = repository.getRoot(); if (roots.contains(root)) { refresher.refresh(root); } }); return connection; } @NotNull @Override public List<TimedVcsCommit> getCommitsMatchingFilter(@NotNull final VirtualFile root, @NotNull VcsLogFilterCollection filterCollection, int maxCount) throws VcsException { if (!isRepositoryReady(root)) { return Collections.emptyList(); } List<String> filterParameters = ContainerUtil.newArrayList(); VcsLogBranchFilter branchFilter = filterCollection.get(VcsLogFilterCollection.BRANCH_FILTER); VcsLogRevisionFilter revisionFilter = filterCollection.get(VcsLogFilterCollection.REVISION_FILTER); if (branchFilter != null || revisionFilter != null) { boolean atLeastOneBranchExists = false; if (branchFilter != null) { GitRepository repository = getRepository(root); assert repository != null : "repository is null for root " + root + " but was previously reported as 'ready'"; Collection<GitBranch> branches = ContainerUtil .newArrayList(ContainerUtil.concat(repository.getBranches().getLocalBranches(), repository.getBranches().getRemoteBranches())); Collection<String> branchNames = GitBranchUtil.convertBranchesToNames(branches); Collection<String> predefinedNames = ContainerUtil.list(GitUtil.HEAD); for (String branchName : ContainerUtil.concat(branchNames, predefinedNames)) { if (branchFilter.matches(branchName)) { filterParameters.add(branchName); atLeastOneBranchExists = true; } } } if (revisionFilter != null) { for (CommitId commit : revisionFilter.getHeads()) { if (commit.getRoot().equals(root)) { filterParameters.add(commit.getHash().asString()); atLeastOneBranchExists = true; } } } if (!atLeastOneBranchExists) { // no such branches in this repository => filter matches nothing return Collections.emptyList(); } } else { filterParameters.addAll(GitLogUtil.LOG_ALL); } VcsLogDateFilter dateFilter = filterCollection.get(VcsLogFilterCollection.DATE_FILTER); if (dateFilter != null) { // assuming there is only one date filter, until filter expressions are defined if (dateFilter.getAfter() != null) { filterParameters.add(prepareParameter("after", dateFilter.getAfter().toString())); } if (dateFilter.getBefore() != null) { filterParameters.add(prepareParameter("before", dateFilter.getBefore().toString())); } } VcsLogTextFilter textFilter = filterCollection.get(VcsLogFilterCollection.TEXT_FILTER); String text = textFilter != null ? textFilter.getText() : null; boolean regexp = textFilter == null || textFilter.isRegex(); boolean caseSensitive = textFilter != null && textFilter.matchesCase(); appendTextFilterParameters(text, regexp, caseSensitive, filterParameters); VcsLogUserFilter userFilter = filterCollection.get(VcsLogFilterCollection.USER_FILTER); if (userFilter != null) { Collection<String> names = ContainerUtil.map(userFilter.getUsers(root), VcsUserUtil::toExactString); if (regexp) { List<String> authors = ContainerUtil.map(names, UserNameRegex.EXTENDED_INSTANCE); if (GitVersionSpecialty.LOG_AUTHOR_FILTER_SUPPORTS_VERTICAL_BAR.existsIn(myVcs.getVersion())) { filterParameters.add(prepareParameter("author", StringUtil.join(authors, "|"))); } else { filterParameters.addAll(authors.stream().map(a -> prepareParameter("author", a)).collect(Collectors.toList())); } } else { filterParameters.addAll(ContainerUtil.map(names, a -> prepareParameter("author", StringUtil.escapeBackSlashes(a)))); } } if (maxCount > 0) { filterParameters.add(prepareParameter("max-count", String.valueOf(maxCount))); } // note: structure filter must be the last parameter, because it uses "--" which separates parameters from paths VcsLogStructureFilter structureFilter = filterCollection.get(VcsLogFilterCollection.STRUCTURE_FILTER); if (structureFilter != null) { Collection<FilePath> files = structureFilter.getFiles(); if (!files.isEmpty()) { filterParameters.add("--full-history"); filterParameters.add("--simplify-merges"); filterParameters.add("--"); for (FilePath file : files) { filterParameters.add(VcsFileUtil.relativePath(root, file)); } } } List<TimedVcsCommit> commits = ContainerUtil.newArrayList(); GitLogUtil.readTimedCommits(myProject, root, filterParameters, EmptyConsumer.getInstance(), EmptyConsumer.getInstance(), new CollectConsumer<>(commits)); return commits; } public static void appendTextFilterParameters(@Nullable String text, boolean regexp, boolean caseSensitive, @NotNull List<? super String> filterParameters) { if (text != null) { filterParameters.add(prepareParameter("grep", text)); } filterParameters.add(regexp ? "--extended-regexp" : "--fixed-strings"); if (!caseSensitive) { filterParameters.add("--regexp-ignore-case"); // affects case sensitivity of any filter (except file filter) } } @Nullable @Override public VcsUser getCurrentUser(@NotNull VirtualFile root) { return myUserRegistry.getOrReadUser(root); } @NotNull @Override public Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException { return GitBranchUtil.getBranches(myProject, root, true, true, commitHash.asString()); } @Nullable @Override public String getCurrentBranch(@NotNull VirtualFile root) { GitRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) return null; String currentBranchName = repository.getCurrentBranchName(); if (currentBranchName == null && repository.getCurrentRevision() != null) { return GitUtil.HEAD; } return currentBranchName; } @Nullable @Override public VcsLogDiffHandler getDiffHandler() { return new GitLogDiffHandler(myProject); } @Nullable @Override public VirtualFile getVcsRoot(@NotNull Project project, @NotNull FilePath path) { VirtualFile file = path.getVirtualFile(); if (file != null && file.isDirectory()) { GitRepository repository = myRepositoryManager.getRepositoryForRoot(file); if (repository != null) { GitSubmodule submodule = GitSubmoduleKt.asSubmodule(repository); if (submodule != null) { return submodule.getParent().getRoot(); } } } return VcsUtil.getVcsRootFor(project, path); } @SuppressWarnings("unchecked") @Nullable @Override public <T> T getPropertyValue(VcsLogProperties.VcsLogProperty<T> property) { if (property == VcsLogProperties.LIGHTWEIGHT_BRANCHES) { return (T)Boolean.TRUE; } else if (property == VcsLogProperties.SUPPORTS_INDEXING) { return (T)Boolean.valueOf(isIndexingOn()); } return null; } public static boolean isIndexingOn() { return Registry.is("vcs.log.index.git"); } private static String prepareParameter(String paramName, String value) { return "--" + paramName + "=" + value; // no value quoting needed, because the parameter itself will be quoted by GeneralCommandLine } @Nullable private GitRepository getRepository(@NotNull VirtualFile root) { return myRepositoryManager.getRepositoryForRoot(root); } private boolean isRepositoryReady(@NotNull VirtualFile root) { GitRepository repository = getRepository(root); if (repository == null) { LOG.error("Repository not found for root " + root); return false; } else if (repository.isFresh()) { LOG.info("Fresh repository: " + root); return false; } return true; } @NotNull private static <T> Set<T> newHashSet() { return new THashSet<>(); } @NotNull private static <T> Set<T> newHashSet(@NotNull Collection<? extends T> initialCollection) { return new THashSet<>(initialCollection); } }
[git] cleanup: use ContainerUtil.map
plugins/git4idea/src/git4idea/log/GitLogProvider.java
[git] cleanup: use ContainerUtil.map
<ide><path>lugins/git4idea/src/git4idea/log/GitLogProvider.java <ide> filterParameters.add(prepareParameter("author", StringUtil.join(authors, "|"))); <ide> } <ide> else { <del> filterParameters.addAll(authors.stream().map(a -> prepareParameter("author", a)).collect(Collectors.toList())); <add> filterParameters.addAll(ContainerUtil.map(authors, a -> prepareParameter("author", a))); <ide> } <ide> } <ide> else {
Java
mit
07ff9343eb092e7422fa93bef36b7d61e1f81e2a
0
alx77-demo/demo
public class DemoApp { public static void main(String[] args) { OutputManager om = new OutputManager(); om.echo(); // TODO Auto-generated method stub System.out.println("Hi there!"); System.out.println("doorsfan912873192387"); System.out.println("One more time"); System.out.println("d00rsfan"); } }
DemoApp/src/DemoApp.java
public class DemoApp { public static void main(String[] args) { OutputManager om = new OutputManager(); om.echo(); // TODO Auto-generated method stub System.out.println("Hi there!"); System.out.println("912873192387"); System.out.println("One more time"); System.out.println("d00rsfan"); } }
mycomm
DemoApp/src/DemoApp.java
mycomm
<ide><path>emoApp/src/DemoApp.java <ide> om.echo(); <ide> // TODO Auto-generated method stub <ide> System.out.println("Hi there!"); <del> System.out.println("912873192387"); <add> System.out.println("doorsfan912873192387"); <ide> System.out.println("One more time"); <ide> <ide>
Java
apache-2.0
4abd0bac0d3bda5ce21128da3b55406fd06ea55b
0
apache/manifoldcf,cogfor/mcf-cogfor,gladyscarrizales/manifoldcf,apache/manifoldcf,gladyscarrizales/manifoldcf,gladyscarrizales/manifoldcf,gladyscarrizales/manifoldcf,gladyscarrizales/manifoldcf,gladyscarrizales/manifoldcf,cogfor/mcf-cogfor,cogfor/mcf-cogfor,kishorejangid/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,cogfor/mcf-cogfor,cogfor/mcf-cogfor,kishorejangid/manifoldcf,cogfor/mcf-cogfor
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.agents.output.opensearchserver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Locale; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.manifoldcf.agents.interfaces.IOutputAddActivity; import org.apache.manifoldcf.agents.interfaces.IOutputNotifyActivity; import org.apache.manifoldcf.agents.interfaces.IOutputRemoveActivity; import org.apache.manifoldcf.agents.interfaces.OutputSpecification; import org.apache.manifoldcf.agents.interfaces.RepositoryDocument; import org.apache.manifoldcf.agents.interfaces.ServiceInterruption; import org.apache.manifoldcf.agents.output.BaseOutputConnector; import org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerAction.CommandEnum; import org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerConnection.Result; import org.apache.manifoldcf.core.interfaces.ConfigParams; import org.apache.manifoldcf.core.interfaces.ConfigurationNode; import org.apache.manifoldcf.core.interfaces.IHTTPOutput; import org.apache.manifoldcf.core.interfaces.IPostParameters; import org.apache.manifoldcf.core.interfaces.IThreadContext; import org.apache.manifoldcf.core.interfaces.ManifoldCFException; import org.apache.manifoldcf.core.interfaces.SpecificationNode; import org.apache.manifoldcf.core.system.Logging; import org.json.JSONException; import org.json.JSONObject; public class OpenSearchServerConnector extends BaseOutputConnector { private final static String OPENSEARCHSERVER_INDEXATION_ACTIVITY = "Optimize"; private final static String OPENSEARCHSERVER_DELETION_ACTIVITY = "Deletion"; private final static String OPENSEARCHSERVER_OPTIMIZE_ACTIVITY = "Indexation"; private final static String[] OPENSEARCHSERVER_ACTIVITIES = { OPENSEARCHSERVER_INDEXATION_ACTIVITY, OPENSEARCHSERVER_DELETION_ACTIVITY, OPENSEARCHSERVER_OPTIMIZE_ACTIVITY }; private final static String OPENSEARCHSERVER_TAB_OPENSEARCHSERVER = "OpenSearchServer"; private String specsCacheOutpuDescription; private OpenSearchServerSpecs specsCache; public OpenSearchServerConnector() { specsCacheOutpuDescription = null; specsCache = null; } @Override public String[] getActivitiesList() { return OPENSEARCHSERVER_ACTIVITIES; } /** * Read the content of a resource, replace the variable ${PARAMNAME} with the * value and copy it to the out. * * @param resName * @param out * @throws ManifoldCFException */ private static void outputResource(String resName, IHTTPOutput out, Locale locale, OpenSearchServerParam params) throws ManifoldCFException { Messages.outputResource(out,locale,resName,(params==null)?null:params.buildMap(),false); } @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { super.outputConfigurationHeader(threadContext, out, locale, parameters, tabsArray); tabsArray.add(Messages.getString(locale,"OpenSearchServerConnector.Parameters")); outputResource("configuration.js", out, locale, null); } @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { super.outputConfigurationBody(threadContext, out, locale, parameters, tabName); if (Messages.getString(locale,"OpenSearchServerConnector.Parameters").equals(tabName)) { outputResource("configuration.html", out, locale, getConfigParameters(parameters)); } } @Override public void outputSpecificationHeader(IHTTPOutput out, Locale locale, OutputSpecification os, List<String> tabsArray) throws ManifoldCFException, IOException { super.outputSpecificationHeader(out, locale, os, tabsArray); tabsArray.add(OPENSEARCHSERVER_TAB_OPENSEARCHSERVER); outputResource("specifications.js", out, locale, null); } final private SpecificationNode getSpecNode(OutputSpecification os) { int l = os.getChildCount(); for (int i = 0; i < l; i++) { SpecificationNode node = os.getChild(i); if (OpenSearchServerSpecs.OPENSEARCHSERVER_SPECS_NODE.equals(node .getType())) { return node; } } return null; } @Override public void outputSpecificationBody(IHTTPOutput out, Locale locale, OutputSpecification os, String tabName) throws ManifoldCFException, IOException { super.outputSpecificationBody(out, locale, os, tabName); if (OPENSEARCHSERVER_TAB_OPENSEARCHSERVER.equals(tabName)) { outputResource("specifications.html", out, locale, getSpecParameters(os)); } } @Override public String processSpecificationPost(IPostParameters variableContext, Locale locale, OutputSpecification os) throws ManifoldCFException { ConfigurationNode specNode = getSpecNode(os); boolean bAdd = (specNode == null); if (bAdd) { specNode = new SpecificationNode( OpenSearchServerSpecs.OPENSEARCHSERVER_SPECS_NODE); } OpenSearchServerSpecs.contextToSpecNode(variableContext, specNode); if (bAdd) os.addChild(os.getChildCount(), specNode); return null; } /** * Build a Set of OpenSearchServer parameters. If configParams is null, * getConfiguration() is used. * * @param configParams */ final private OpenSearchServerConfig getConfigParameters( ConfigParams configParams) { if (configParams == null) configParams = getConfiguration(); synchronized (this) { return new OpenSearchServerConfig(configParams); } } final private OpenSearchServerSpecs getSpecParameters(OutputSpecification os) throws ManifoldCFException { return new OpenSearchServerSpecs(getSpecNode(os)); } final private OpenSearchServerSpecs getSpecsCache(String outputDescription) throws ManifoldCFException { try { synchronized (this) { if (!outputDescription.equals(specsCacheOutpuDescription)) specsCache = null; if (specsCache == null) specsCache = new OpenSearchServerSpecs(new JSONObject( outputDescription)); return specsCache; } } catch (JSONException e) { throw new ManifoldCFException(e); } } @Override public String getOutputDescription(OutputSpecification os) throws ManifoldCFException { OpenSearchServerSpecs specs = new OpenSearchServerSpecs(getSpecNode(os)); return specs.toJson().toString(); } @Override public boolean checkLengthIndexable(String outputDescription, long length) throws ManifoldCFException, ServiceInterruption { OpenSearchServerSpecs specs = getSpecsCache(outputDescription); long maxFileSize = specs.getMaxFileSize(); if (length > maxFileSize) return false; return super.checkLengthIndexable(outputDescription, length); } @Override public boolean checkDocumentIndexable(String outputDescription, File localFile) throws ManifoldCFException, ServiceInterruption { OpenSearchServerSpecs specs = getSpecsCache(outputDescription); return specs .checkExtension(FilenameUtils.getExtension(localFile.getName())); } @Override public boolean checkMimeTypeIndexable(String outputDescription, String mimeType) throws ManifoldCFException, ServiceInterruption { OpenSearchServerSpecs specs = getSpecsCache(outputDescription); return specs.checkMimeType(mimeType); } @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { outputResource("view.html", out, locale, getConfigParameters(parameters)); } @Override public void viewSpecification(IHTTPOutput out, Locale locale, OutputSpecification os) throws ManifoldCFException, IOException { outputResource("viewSpec.html", out, locale, getSpecParameters(os)); } @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, ConfigParams parameters) throws ManifoldCFException { OpenSearchServerConfig.contextToConfig(variableContext, parameters); return null; } private static Map<String, Integer> ossInstances = null; private synchronized final Integer addInstance(OpenSearchServerConfig config) { if (ossInstances == null) ossInstances = new TreeMap<String, Integer>(); synchronized (ossInstances) { String uii = config.getUniqueIndexIdentifier(); Integer count = ossInstances.get(uii); if (count == null) { count = new Integer(1); ossInstances.put(uii, count); } else count++; return count; } } private synchronized final void removeInstance(OpenSearchServerConfig config) { if (ossInstances == null) return; synchronized (ossInstances) { String uii = config.getUniqueIndexIdentifier(); Integer count = ossInstances.get(uii); if (count == null) return; if (--count == 0) ossInstances.remove(uii); } } @Override public int addOrReplaceDocument(String documentURI, String outputDescription, RepositoryDocument document, String authorityNameString, IOutputAddActivity activities) throws ManifoldCFException, ServiceInterruption { OpenSearchServerConfig config = getConfigParameters(null); Integer count = addInstance(config); synchronized (count) { InputStream inputStream = document.getBinaryStream(); try { long startTime = System.currentTimeMillis(); OpenSearchServerIndex oi = new OpenSearchServerIndex(documentURI, inputStream, config); activities.recordActivity(startTime, OPENSEARCHSERVER_INDEXATION_ACTIVITY, document.getBinaryLength(), documentURI, oi.getResult().name(), oi.getResultDescription()); if (oi.getResult() != Result.OK) return DOCUMENTSTATUS_REJECTED; } finally { removeInstance(config); } return DOCUMENTSTATUS_ACCEPTED; } } @Override public void removeDocument(String documentURI, String outputDescription, IOutputRemoveActivity activities) throws ManifoldCFException, ServiceInterruption { long startTime = System.currentTimeMillis(); OpenSearchServerDelete od = new OpenSearchServerDelete(documentURI, getConfigParameters(null)); activities.recordActivity(startTime, OPENSEARCHSERVER_DELETION_ACTIVITY, null, documentURI, od.getResult().name(), od.getResultDescription()); } @Override public String check() throws ManifoldCFException { OpenSearchServerSchema oss = new OpenSearchServerSchema( getConfigParameters(null)); return oss.getResult().name() + " " + oss.getResultDescription(); } @Override public void noteJobComplete(IOutputNotifyActivity activities) throws ManifoldCFException, ServiceInterruption { long startTime = System.currentTimeMillis(); OpenSearchServerAction oo = new OpenSearchServerAction( CommandEnum.optimize, getConfigParameters(null)); activities.recordActivity(startTime, OPENSEARCHSERVER_OPTIMIZE_ACTIVITY, null, oo.getCallUrlSnippet(), oo.getResult().name(), oo.getResultDescription()); } }
connectors/opensearchserver/connector/src/main/java/org/apache/manifoldcf/agents/output/opensearchserver/OpenSearchServerConnector.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.agents.output.opensearchserver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Locale; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.manifoldcf.agents.interfaces.IOutputAddActivity; import org.apache.manifoldcf.agents.interfaces.IOutputNotifyActivity; import org.apache.manifoldcf.agents.interfaces.IOutputRemoveActivity; import org.apache.manifoldcf.agents.interfaces.OutputSpecification; import org.apache.manifoldcf.agents.interfaces.RepositoryDocument; import org.apache.manifoldcf.agents.interfaces.ServiceInterruption; import org.apache.manifoldcf.agents.output.BaseOutputConnector; import org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerAction.CommandEnum; import org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerConnection.Result; import org.apache.manifoldcf.core.interfaces.ConfigParams; import org.apache.manifoldcf.core.interfaces.ConfigurationNode; import org.apache.manifoldcf.core.interfaces.IHTTPOutput; import org.apache.manifoldcf.core.interfaces.IPostParameters; import org.apache.manifoldcf.core.interfaces.IThreadContext; import org.apache.manifoldcf.core.interfaces.ManifoldCFException; import org.apache.manifoldcf.core.interfaces.SpecificationNode; import org.apache.manifoldcf.core.system.Logging; import org.json.JSONException; import org.json.JSONObject; public class OpenSearchServerConnector extends BaseOutputConnector { private final static String OPENSEARCHSERVER_INDEXATION_ACTIVITY = "Optimize"; private final static String OPENSEARCHSERVER_DELETION_ACTIVITY = "Deletion"; private final static String OPENSEARCHSERVER_OPTIMIZE_ACTIVITY = "Indexation"; private final static String[] OPENSEARCHSERVER_ACTIVITIES = { OPENSEARCHSERVER_INDEXATION_ACTIVITY, OPENSEARCHSERVER_DELETION_ACTIVITY, OPENSEARCHSERVER_OPTIMIZE_ACTIVITY }; private final static String OPENSEARCHSERVER_TAB_OPENSEARCHSERVER = "OpenSearchServer"; private String specsCacheOutpuDescription; private OpenSearchServerSpecs specsCache; public OpenSearchServerConnector() { specsCacheOutpuDescription = null; specsCache = null; } @Override public String[] getActivitiesList() { return OPENSEARCHSERVER_ACTIVITIES; } /** * Read the content of a resource, replace the variable ${PARAMNAME} with the * value and copy it to the out. * * @param resName * @param out * @throws ManifoldCFException */ private static void outputResource(String resName, IHTTPOutput out, Locale locale, OpenSearchServerParam params) throws ManifoldCFException { Messages.outputResource(out,locale,resName,params.buildMap(),false); } @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { super.outputConfigurationHeader(threadContext, out, locale, parameters, tabsArray); tabsArray.add(Messages.getString(locale,"OpenSearchServerConnector.Parameters")); outputResource("configuration.js", out, locale, null); } @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { super.outputConfigurationBody(threadContext, out, locale, parameters, tabName); if (Messages.getString(locale,"OpenSearchServerConnector.Parameters").equals(tabName)) { outputResource("configuration.html", out, locale, getConfigParameters(parameters)); } } @Override public void outputSpecificationHeader(IHTTPOutput out, Locale locale, OutputSpecification os, List<String> tabsArray) throws ManifoldCFException, IOException { super.outputSpecificationHeader(out, locale, os, tabsArray); tabsArray.add(OPENSEARCHSERVER_TAB_OPENSEARCHSERVER); outputResource("specifications.js", out, locale, null); } final private SpecificationNode getSpecNode(OutputSpecification os) { int l = os.getChildCount(); for (int i = 0; i < l; i++) { SpecificationNode node = os.getChild(i); if (OpenSearchServerSpecs.OPENSEARCHSERVER_SPECS_NODE.equals(node .getType())) { return node; } } return null; } @Override public void outputSpecificationBody(IHTTPOutput out, Locale locale, OutputSpecification os, String tabName) throws ManifoldCFException, IOException { super.outputSpecificationBody(out, locale, os, tabName); if (OPENSEARCHSERVER_TAB_OPENSEARCHSERVER.equals(tabName)) { outputResource("specifications.html", out, locale, getSpecParameters(os)); } } @Override public String processSpecificationPost(IPostParameters variableContext, Locale locale, OutputSpecification os) throws ManifoldCFException { ConfigurationNode specNode = getSpecNode(os); boolean bAdd = (specNode == null); if (bAdd) { specNode = new SpecificationNode( OpenSearchServerSpecs.OPENSEARCHSERVER_SPECS_NODE); } OpenSearchServerSpecs.contextToSpecNode(variableContext, specNode); if (bAdd) os.addChild(os.getChildCount(), specNode); return null; } /** * Build a Set of OpenSearchServer parameters. If configParams is null, * getConfiguration() is used. * * @param configParams */ final private OpenSearchServerConfig getConfigParameters( ConfigParams configParams) { if (configParams == null) configParams = getConfiguration(); synchronized (this) { return new OpenSearchServerConfig(configParams); } } final private OpenSearchServerSpecs getSpecParameters(OutputSpecification os) throws ManifoldCFException { return new OpenSearchServerSpecs(getSpecNode(os)); } final private OpenSearchServerSpecs getSpecsCache(String outputDescription) throws ManifoldCFException { try { synchronized (this) { if (!outputDescription.equals(specsCacheOutpuDescription)) specsCache = null; if (specsCache == null) specsCache = new OpenSearchServerSpecs(new JSONObject( outputDescription)); return specsCache; } } catch (JSONException e) { throw new ManifoldCFException(e); } } @Override public String getOutputDescription(OutputSpecification os) throws ManifoldCFException { OpenSearchServerSpecs specs = new OpenSearchServerSpecs(getSpecNode(os)); return specs.toJson().toString(); } @Override public boolean checkLengthIndexable(String outputDescription, long length) throws ManifoldCFException, ServiceInterruption { OpenSearchServerSpecs specs = getSpecsCache(outputDescription); long maxFileSize = specs.getMaxFileSize(); if (length > maxFileSize) return false; return super.checkLengthIndexable(outputDescription, length); } @Override public boolean checkDocumentIndexable(String outputDescription, File localFile) throws ManifoldCFException, ServiceInterruption { OpenSearchServerSpecs specs = getSpecsCache(outputDescription); return specs .checkExtension(FilenameUtils.getExtension(localFile.getName())); } @Override public boolean checkMimeTypeIndexable(String outputDescription, String mimeType) throws ManifoldCFException, ServiceInterruption { OpenSearchServerSpecs specs = getSpecsCache(outputDescription); return specs.checkMimeType(mimeType); } @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { outputResource("view.html", out, locale, getConfigParameters(parameters)); } @Override public void viewSpecification(IHTTPOutput out, Locale locale, OutputSpecification os) throws ManifoldCFException, IOException { outputResource("viewSpec.html", out, locale, getSpecParameters(os)); } @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, ConfigParams parameters) throws ManifoldCFException { OpenSearchServerConfig.contextToConfig(variableContext, parameters); return null; } private static Map<String, Integer> ossInstances = null; private synchronized final Integer addInstance(OpenSearchServerConfig config) { if (ossInstances == null) ossInstances = new TreeMap<String, Integer>(); synchronized (ossInstances) { String uii = config.getUniqueIndexIdentifier(); Integer count = ossInstances.get(uii); if (count == null) { count = new Integer(1); ossInstances.put(uii, count); } else count++; return count; } } private synchronized final void removeInstance(OpenSearchServerConfig config) { if (ossInstances == null) return; synchronized (ossInstances) { String uii = config.getUniqueIndexIdentifier(); Integer count = ossInstances.get(uii); if (count == null) return; if (--count == 0) ossInstances.remove(uii); } } @Override public int addOrReplaceDocument(String documentURI, String outputDescription, RepositoryDocument document, String authorityNameString, IOutputAddActivity activities) throws ManifoldCFException, ServiceInterruption { OpenSearchServerConfig config = getConfigParameters(null); Integer count = addInstance(config); synchronized (count) { InputStream inputStream = document.getBinaryStream(); try { long startTime = System.currentTimeMillis(); OpenSearchServerIndex oi = new OpenSearchServerIndex(documentURI, inputStream, config); activities.recordActivity(startTime, OPENSEARCHSERVER_INDEXATION_ACTIVITY, document.getBinaryLength(), documentURI, oi.getResult().name(), oi.getResultDescription()); if (oi.getResult() != Result.OK) return DOCUMENTSTATUS_REJECTED; } finally { removeInstance(config); } return DOCUMENTSTATUS_ACCEPTED; } } @Override public void removeDocument(String documentURI, String outputDescription, IOutputRemoveActivity activities) throws ManifoldCFException, ServiceInterruption { long startTime = System.currentTimeMillis(); OpenSearchServerDelete od = new OpenSearchServerDelete(documentURI, getConfigParameters(null)); activities.recordActivity(startTime, OPENSEARCHSERVER_DELETION_ACTIVITY, null, documentURI, od.getResult().name(), od.getResultDescription()); } @Override public String check() throws ManifoldCFException { OpenSearchServerSchema oss = new OpenSearchServerSchema( getConfigParameters(null)); return oss.getResult().name() + " " + oss.getResultDescription(); } @Override public void noteJobComplete(IOutputNotifyActivity activities) throws ManifoldCFException, ServiceInterruption { long startTime = System.currentTimeMillis(); OpenSearchServerAction oo = new OpenSearchServerAction( CommandEnum.optimize, getConfigParameters(null)); activities.recordActivity(startTime, OPENSEARCHSERVER_OPTIMIZE_ACTIVITY, null, oo.getCallUrlSnippet(), oo.getResult().name(), oo.getResultDescription()); } }
UI error due to NPE; broken as part of CONNECTORS-335, fixed now. git-svn-id: 0503cfb7d358eaa9bd718f348f448f10022ea703@1225560 13f79535-47bb-0310-9956-ffa450edef68
connectors/opensearchserver/connector/src/main/java/org/apache/manifoldcf/agents/output/opensearchserver/OpenSearchServerConnector.java
UI error due to NPE; broken as part of CONNECTORS-335, fixed now.
<ide><path>onnectors/opensearchserver/connector/src/main/java/org/apache/manifoldcf/agents/output/opensearchserver/OpenSearchServerConnector.java <ide> */ <ide> private static void outputResource(String resName, IHTTPOutput out, <ide> Locale locale, OpenSearchServerParam params) throws ManifoldCFException { <del> Messages.outputResource(out,locale,resName,params.buildMap(),false); <add> Messages.outputResource(out,locale,resName,(params==null)?null:params.buildMap(),false); <ide> } <ide> <ide> @Override
Java
apache-2.0
39ed7bdf558cd8286e62492f6c91d2af73f807aa
0
apache/commons-beanutils,mohanaraosv/commons-beanutils,apache/commons-beanutils,apache/commons-beanutils,mohanaraosv/commons-beanutils,mohanaraosv/commons-beanutils
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//beanutils/src/java/org/apache/commons/beanutils/BeanUtils.java,v 1.4 2001/05/21 04:20:21 craigmcc Exp $ * $Revision: 1.4 $ * $Date: 2001/05/21 04:20:21 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.beanutils; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Utility methods for populating JavaBeans properties via reflection. * * @author Craig R. McClanahan * @author Ralph Schaer * @author Chris Audley * @version $Revision: 1.4 $ $Date: 2001/05/21 04:20:21 $ */ public class BeanUtils { // ------------------------------------------------------ Private Variables /** * The debugging detail level for this component. */ private static int debug = 0; public static int getDebug() { return (debug); } public static void setDebug(int newDebug) { debug = newDebug; } // --------------------------------------------------------- Public Classes /** * Clone a bean based on the available property getters and setters, * even if the bean class itself does not implement Cloneable. * * @param bean Bean to be cloned * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InstantiationException if a new instance of the bean's * class cannot be instantiated * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static Object cloneBean(Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { Class clazz = bean.getClass(); Object newBean = clazz.newInstance(); PropertyUtils.copyProperties(newBean, bean); return (newBean); } /** * Return the entire set of properties for which the specified bean * provides a read method. This map can be fed back to a call to * <code>BeanUtils.populate()</code> to reconsitute the same set of * properties, modulo differences for read-only and write-only * properties. * * @param bean Bean whose properties are to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) // return (Collections.EMPTY_MAP); return (new java.util.HashMap()); PropertyDescriptor descriptors[] = PropertyUtils.getPropertyDescriptors(bean); Map description = new HashMap(descriptors.length); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (descriptors[i].getReadMethod() != null) description.put(name, getProperty(bean, name)); } return (description); } /** * Return the value of the specified array property of the specified * bean, as a String array. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String[] getArrayProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getProperty(bean, name); if (value == null) { return (null); } else if (value instanceof Collection) { ArrayList values = new ArrayList(); Iterator items = ((Collection) value).iterator(); while (items.hasNext()) { Object item = items.next(); if (item == null) values.add((String) null); else values.add(item.toString()); } return ((String[]) values.toArray(new String[values.size()])); } else if (value.getClass().isArray()) { ArrayList values = new ArrayList(); try { int n = Array.getLength(value); for (int i = 0; i < n; i++) { values.add(Array.get(value, i).toString()); } } catch (ArrayIndexOutOfBoundsException e) { ; } return ((String[]) values.toArray(new String[values.size()])); } else { String results[] = new String[1]; results[0] = value.toString(); return (results); } } /** * Return the value of the specified indexed property of the specified * bean, as a String. The zero-relative index of the * required value must be included (in square brackets) as a suffix to * the property name, or <code>IllegalArgumentException</code> will be * thrown. * * @param bean Bean whose property is to be extracted * @param name <code>propertyname[index]</code> of the property value * to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getIndexedProperty(bean, name); return (ConvertUtils.convert(value)); } /** * Return the value of the specified indexed property of the specified * bean, as a String. The index is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { StringBuffer sb = new StringBuffer(name); sb.append(PropertyUtils.INDEXED_DELIM); sb.append(index); sb.append(PropertyUtils.INDEXED_DELIM2); Object value = PropertyUtils.getIndexedProperty(bean, sb.toString()); return (ConvertUtils.convert(value)); } /** * Return the value of the (possibly nested) property of the specified * name, for the specified bean, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getNestedProperty(bean, name); return (ConvertUtils.convert(value)); } /** * Return the value of the specified property of the specified bean, * no matter which property reference format is used, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (getNestedProperty(bean, name)); } /** * Return the value of the specified simple property of the specified * bean, converted to a String. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getSimpleProperty(bean, name); return (ConvertUtils.convert(value)); } /** * Populate the JavaBeans properties of the specified bean, based on * the specified name/value pairs. This method uses Java reflection APIs * to identify corresponding "property setter" method names, and deals * with setter arguments of type <code>String</code>, <code>boolean</code>, * <code>int</code>, <code>long</code>, <code>float</code>, and * <code>double</code>. In addition, array setters for these types (or the * corresponding primitive types) can also be identified. * <p> * The particular setter method to be called for each property is * determined using the usual JavaBeans introspection mechanisms. Thus, * you may identify custom setter methods using a BeanInfo class that is * associated with the class of the bean itself. If no such BeanInfo * class is available, the standard method name conversion ("set" plus * the capitalized name of the property in question) is used. * <p> * <strong>NOTE</strong>: It is contrary to the JavaBeans Specification * to have more than one setter method (with different argument * signatures) for the same property. * * @param bean JavaBean whose properties are being populated * @param properties Map keyed by property name, with the * corresponding (String or String[]) value(s) to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public static void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { if ((bean == null) || (properties == null)) return; /* if (debug >= 1) System.out.println("BeanUtils.populate(" + bean + ", " + properties + ")"); */ // Loop through the property name/value pairs to be set Iterator names = properties.keySet().iterator(); while (names.hasNext()) { // Identify the property name and value(s) to be assigned String name = (String) names.next(); if (name == null) continue; Object value = properties.get(name); // String or String[] /* if (debug >= 1) System.out.println(" name='" + name + "', value.class='" + (value == null ? "NONE" : value.getClass().getName()) + "'"); */ // Get the property descriptor of the requested property (if any) PropertyDescriptor descriptor = null; try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); } catch (Throwable t) { /* if (debug >= 1) System.out.println(" getPropertyDescriptor: " + t); */ descriptor = null; } if (descriptor == null) { /* if (debug >= 1) System.out.println(" No such property, skipping"); */ continue; } /* if (debug >= 1) System.out.println(" Property descriptor is '" + descriptor + "'"); */ // Identify the relevant setter method (if there is one) Method setter = null; if (descriptor instanceof IndexedPropertyDescriptor) setter = ((IndexedPropertyDescriptor) descriptor). getIndexedWriteMethod(); if (setter == null) setter = descriptor.getWriteMethod(); if (setter == null) { /* if (debug >= 1) System.out.println(" No setter method, skipping"); */ continue; } Class parameterTypes[] = setter.getParameterTypes(); /* if (debug >= 1) System.out.println(" Setter method is '" + setter.getName() + "(" + parameterTypes[0].getName() + (parameterTypes.length > 1 ? ", " + parameterTypes[1].getName() : "" ) + ")'"); */ Class parameterType = parameterTypes[0]; if (parameterTypes.length > 1) parameterType = parameterTypes[1]; // Indexed setter // Convert the parameter value as required for this setter method Object parameters[] = new Object[1]; if (parameterTypes[0].isArray()) { if (value instanceof String) { String values[] = new String[1]; values[0] = (String) value; parameters[0] = ConvertUtils.convert((String[]) values, parameterType); } else if (value instanceof String[]) { parameters[0] = ConvertUtils.convert((String[]) value, parameterType); } else { parameters[0] = value; } } else { if (value instanceof String) { parameters[0] = ConvertUtils.convert((String) value, parameterType); } else if (value instanceof String[]) { parameters[0] = ConvertUtils.convert(((String[]) value)[0], parameterType); } else { parameters[0] = value; } } // Invoke the setter method /* if (debug >= 1) System.out.println(" Setting to " + (parameters[0] == null ? "NULL" : "'" + parameters[0] + "'")); */ try { PropertyUtils.setProperty(bean, name, parameters[0]); } catch (NoSuchMethodException e) { /* if (debug >= 1) { System.out.println(" CANNOT HAPPEN: " + e); e.printStackTrace(System.out); } */ } } /* if (debug >= 1) System.out.println("============================================"); */ } }
src/java/org/apache/commons/beanutils/BeanUtils.java
/* * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//beanutils/src/java/org/apache/commons/beanutils/BeanUtils.java,v 1.3 2001/04/16 16:30:12 craigmcc Exp $ * $Revision: 1.3 $ * $Date: 2001/04/16 16:30:12 $ * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.commons.beanutils; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Utility methods for populating JavaBeans properties via reflection. * * @author Craig R. McClanahan * @author Ralph Schaer * @author Chris Audley * @version $Revision: 1.3 $ $Date: 2001/04/16 16:30:12 $ */ public class BeanUtils { // ------------------------------------------------------ Private Variables /** * The debugging detail level for this component. */ private static int debug = 0; public static int getDebug() { return (debug); } public static void setDebug(int newDebug) { debug = newDebug; } // --------------------------------------------------------- Public Classes /** * Clone a bean based on the available property getters and setters, * even if the bean class itself does not implement Cloneable. * * @param bean Bean to be cloned * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InstantiationException if a new instance of the bean's * class cannot be instantiated * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static Object cloneBean(Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { Class clazz = bean.getClass(); Object newBean = clazz.newInstance(); PropertyUtils.copyProperties(newBean, bean); return (newBean); } /** * Return the entire set of properties for which the specified bean * provides a read method. This map can be fed back to a call to * <code>BeanUtils.populate()</code> to reconsitute the same set of * properties, modulo differences for read-only and write-only * properties. * * @param bean Bean whose properties are to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) return (Collections.EMPTY_MAP); PropertyDescriptor descriptors[] = PropertyUtils.getPropertyDescriptors(bean); Map description = new HashMap(descriptors.length); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (descriptors[i].getReadMethod() != null) description.put(name, getProperty(bean, name)); } return (description); } /** * Return the value of the specified array property of the specified * bean, as a String array. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String[] getArrayProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getProperty(bean, name); if (value == null) { return (null); } else if (value instanceof Collection) { ArrayList values = new ArrayList(); Iterator items = ((Collection) value).iterator(); while (items.hasNext()) { Object item = items.next(); if (item == null) values.add((String) null); else values.add(item.toString()); } return ((String[]) values.toArray(new String[values.size()])); } else if (value.getClass().isArray()) { ArrayList values = new ArrayList(); try { int n = Array.getLength(value); for (int i = 0; i < n; i++) { values.add(Array.get(value, i).toString()); } } catch (ArrayIndexOutOfBoundsException e) { ; } return ((String[]) values.toArray(new String[values.size()])); } else { String results[] = new String[1]; results[0] = value.toString(); return (results); } } /** * Return the value of the specified indexed property of the specified * bean, as a String. The zero-relative index of the * required value must be included (in square brackets) as a suffix to * the property name, or <code>IllegalArgumentException</code> will be * thrown. * * @param bean Bean whose property is to be extracted * @param name <code>propertyname[index]</code> of the property value * to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getIndexedProperty(bean, name); return (ConvertUtils.convert(value)); } /** * Return the value of the specified indexed property of the specified * bean, as a String. The index is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { StringBuffer sb = new StringBuffer(name); sb.append(PropertyUtils.INDEXED_DELIM); sb.append(index); sb.append(PropertyUtils.INDEXED_DELIM2); Object value = PropertyUtils.getIndexedProperty(bean, sb.toString()); return (ConvertUtils.convert(value)); } /** * Return the value of the (possibly nested) property of the specified * name, for the specified bean, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getNestedProperty(bean, name); return (ConvertUtils.convert(value)); } /** * Return the value of the specified property of the specified bean, * no matter which property reference format is used, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (getNestedProperty(bean, name)); } /** * Return the value of the specified simple property of the specified * bean, converted to a String. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public static String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getSimpleProperty(bean, name); return (ConvertUtils.convert(value)); } /** * Populate the JavaBeans properties of the specified bean, based on * the specified name/value pairs. This method uses Java reflection APIs * to identify corresponding "property setter" method names, and deals * with setter arguments of type <code>String</code>, <code>boolean</code>, * <code>int</code>, <code>long</code>, <code>float</code>, and * <code>double</code>. In addition, array setters for these types (or the * corresponding primitive types) can also be identified. * <p> * The particular setter method to be called for each property is * determined using the usual JavaBeans introspection mechanisms. Thus, * you may identify custom setter methods using a BeanInfo class that is * associated with the class of the bean itself. If no such BeanInfo * class is available, the standard method name conversion ("set" plus * the capitalized name of the property in question) is used. * <p> * <strong>NOTE</strong>: It is contrary to the JavaBeans Specification * to have more than one setter method (with different argument * signatures) for the same property. * * @param bean JavaBean whose properties are being populated * @param properties Map keyed by property name, with the * corresponding (String or String[]) value(s) to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception */ public static void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { if ((bean == null) || (properties == null)) return; /* if (debug >= 1) System.out.println("BeanUtils.populate(" + bean + ", " + properties + ")"); */ // Loop through the property name/value pairs to be set Iterator names = properties.keySet().iterator(); while (names.hasNext()) { // Identify the property name and value(s) to be assigned String name = (String) names.next(); if (name == null) continue; Object value = properties.get(name); // String or String[] /* if (debug >= 1) System.out.println(" name='" + name + "', value.class='" + (value == null ? "NONE" : value.getClass().getName()) + "'"); */ // Get the property descriptor of the requested property (if any) PropertyDescriptor descriptor = null; try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); } catch (Throwable t) { /* if (debug >= 1) System.out.println(" getPropertyDescriptor: " + t); */ descriptor = null; } if (descriptor == null) { /* if (debug >= 1) System.out.println(" No such property, skipping"); */ continue; } /* if (debug >= 1) System.out.println(" Property descriptor is '" + descriptor + "'"); */ // Identify the relevant setter method (if there is one) Method setter = null; if (descriptor instanceof IndexedPropertyDescriptor) setter = ((IndexedPropertyDescriptor) descriptor). getIndexedWriteMethod(); if (setter == null) setter = descriptor.getWriteMethod(); if (setter == null) { /* if (debug >= 1) System.out.println(" No setter method, skipping"); */ continue; } Class parameterTypes[] = setter.getParameterTypes(); /* if (debug >= 1) System.out.println(" Setter method is '" + setter.getName() + "(" + parameterTypes[0].getName() + (parameterTypes.length > 1 ? ", " + parameterTypes[1].getName() : "" ) + ")'"); */ Class parameterType = parameterTypes[0]; if (parameterTypes.length > 1) parameterType = parameterTypes[1]; // Indexed setter // Convert the parameter value as required for this setter method Object parameters[] = new Object[1]; if (parameterTypes[0].isArray()) { if (value instanceof String) { String values[] = new String[1]; values[0] = (String) value; parameters[0] = ConvertUtils.convert((String[]) values, parameterType); } else if (value instanceof String[]) { parameters[0] = ConvertUtils.convert((String[]) value, parameterType); } else { parameters[0] = value; } } else { if (value instanceof String) { parameters[0] = ConvertUtils.convert((String) value, parameterType); } else if (value instanceof String[]) { parameters[0] = ConvertUtils.convert(((String[]) value)[0], parameterType); } else { parameters[0] = value; } } // Invoke the setter method /* if (debug >= 1) System.out.println(" Setting to " + (parameters[0] == null ? "NULL" : "'" + parameters[0] + "'")); */ try { PropertyUtils.setProperty(bean, name, parameters[0]); } catch (NoSuchMethodException e) { /* if (debug >= 1) { System.out.println(" CANNOT HAPPEN: " + e); e.printStackTrace(System.out); } */ } } /* if (debug >= 1) System.out.println("============================================"); */ } }
Collections.EMPTY_MAP was added in JDK 1.3. Replace it with something that will compile in JDK 1.2 environments. Submitted by: Kelvin Ho <[email protected]> git-svn-id: 695e8515a9258845e6163903654874b217615ba0@128478 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/beanutils/BeanUtils.java
Collections.EMPTY_MAP was added in JDK 1.3. Replace it with something that will compile in JDK 1.2 environments. Submitted by: Kelvin Ho <[email protected]>
<ide><path>rc/java/org/apache/commons/beanutils/BeanUtils.java <ide> /* <del> * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//beanutils/src/java/org/apache/commons/beanutils/BeanUtils.java,v 1.3 2001/04/16 16:30:12 craigmcc Exp $ <del> * $Revision: 1.3 $ <del> * $Date: 2001/04/16 16:30:12 $ <add> * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//beanutils/src/java/org/apache/commons/beanutils/BeanUtils.java,v 1.4 2001/05/21 04:20:21 craigmcc Exp $ <add> * $Revision: 1.4 $ <add> * $Date: 2001/05/21 04:20:21 $ <ide> * <ide> * ==================================================================== <ide> * <ide> * @author Craig R. McClanahan <ide> * @author Ralph Schaer <ide> * @author Chris Audley <del> * @version $Revision: 1.3 $ $Date: 2001/04/16 16:30:12 $ <add> * @version $Revision: 1.4 $ $Date: 2001/05/21 04:20:21 $ <ide> */ <ide> <ide> public class BeanUtils { <ide> NoSuchMethodException { <ide> <ide> if (bean == null) <del> return (Collections.EMPTY_MAP); <add> // return (Collections.EMPTY_MAP); <add> return (new java.util.HashMap()); <ide> PropertyDescriptor descriptors[] = <ide> PropertyUtils.getPropertyDescriptors(bean); <ide> Map description = new HashMap(descriptors.length);
Java
apache-2.0
45a6a3505cb6da87c316abac5a294b4a4aaf9089
0
KouChengjian/acg12-android
package com.acg12.lib.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.acg12.lib.R; import java.util.List; public class TipLayoutView extends RelativeLayout implements View.OnClickListener { private ViewStub mLayoutNull, mLayoutError, mLayoutLoading; private LinearLayout mLLTipviewNull, mLLTipviewError, mLLTipviewLoading; private ImageView tv_tiplayout_pic; private TextView tv_tiplayout_msg; private BGButton mReloadButton; private OnReloadClick onReloadClick; public TipLayoutView(Context context) { super(context); initView(); } public TipLayoutView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public TipLayoutView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } private void initView() { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.common_tiplayout_view, this); view.setOnClickListener(null); mLayoutNull = (ViewStub)findViewById(R.id.layout_null); mLayoutError = (ViewStub)findViewById(R.id.layout_error); mLayoutLoading = (ViewStub)findViewById(R.id.layout_loading); showLoading(); } /** * 现实文本内容 */ public void showContent() { if (this.getVisibility() == View.VISIBLE) { this.setVisibility(GONE); } } /** * 显示加载中布局 */ public void showLoading() { resetStatus(); if (mLLTipviewLoading == null) { View view = mLayoutLoading.inflate(); mLLTipviewLoading = (LinearLayout) view.findViewById(R.id.ll_tipview_loading); mLLTipviewLoading.setBackgroundResource(R.color.white); } if (mLLTipviewLoading.getVisibility() == View.GONE) { mLLTipviewLoading.setVisibility(View.VISIBLE); } } public void showRestLoading() { resetStatus(); if (mLLTipviewLoading == null) { View view = mLayoutLoading.inflate(); mLLTipviewLoading = (LinearLayout) view.findViewById(R.id.ll_tipview_loading); } mLLTipviewLoading.setBackgroundResource(R.color.transparent); if (mLLTipviewLoading.getVisibility() == View.GONE) { mLLTipviewLoading.setVisibility(View.VISIBLE); } } /** * 显示没有网络 */ public void showNetError() { resetStatus(); if (mLLTipviewError == null) { View view = mLayoutError.inflate(); mLLTipviewError = (LinearLayout) view.findViewById(R.id.ll_tipview_error); tv_tiplayout_pic = (ImageView) view.findViewById(R.id.tv_tiplayout_pic); tv_tiplayout_msg = (TextView) view.findViewById(R.id.tv_tiplayout_msg); mReloadButton = (BGButton) view.findViewById(R.id.bg_refush); mReloadButton.setOnClickListener(this); } if (mLLTipviewError.getVisibility() == View.GONE) { mLLTipviewError.setVisibility(View.VISIBLE); } } /** * 显示加载失败 */ public void showLoginError() { resetStatus(); if (mLLTipviewError == null) { View view = mLayoutError.inflate(); mLLTipviewError = (LinearLayout) view.findViewById(R.id.ll_tipview_error); tv_tiplayout_pic = (ImageView) view.findViewById(R.id.tv_tiplayout_pic); tv_tiplayout_msg = (TextView) view.findViewById(R.id.tv_tiplayout_msg); mReloadButton = (BGButton) view.findViewById(R.id.bg_refush); mReloadButton.setOnClickListener(this); } tv_tiplayout_msg.setText("获取消息失败,点击重新获取"); mReloadButton.setText("重新获取"); if (mLLTipviewError.getVisibility() == View.GONE) { mLLTipviewError.setVisibility(View.VISIBLE); } } /** * 显示空数据且存在刷新按钮 */ public void showEmptyOrRefresh() { resetStatus(); if (mLLTipviewError == null) { View view = mLayoutError.inflate(); mLLTipviewError = (LinearLayout) view.findViewById(R.id.ll_tipview_error); tv_tiplayout_pic = (ImageView) view.findViewById(R.id.tv_tiplayout_pic); tv_tiplayout_msg = (TextView) view.findViewById(R.id.tv_tiplayout_msg); mReloadButton = (BGButton) view.findViewById(R.id.bg_refush); mReloadButton.setOnClickListener(this); } tv_tiplayout_pic.setImageResource(R.mipmap.bg_loading_null); tv_tiplayout_msg.setText(""); tv_tiplayout_msg.setVisibility(View.GONE); mReloadButton.setText("再次获取"); if (mLLTipviewError.getVisibility() == View.GONE) { mLLTipviewError.setVisibility(View.VISIBLE); } } /** * 显示空数据 */ public void showEmpty() { resetStatus(); if (mLLTipviewNull == null) { View view = mLayoutNull.inflate(); mLLTipviewNull = (LinearLayout) view.findViewById(R.id.ll_tipview_null); } if (mLLTipviewNull.getVisibility() == View.GONE) { mLLTipviewNull.setVisibility(View.VISIBLE); } } /** * 隐藏所有布局 */ public void resetStatus() { this.setVisibility(VISIBLE); if (mLLTipviewNull != null) { mLLTipviewNull.setVisibility(View.GONE); } if (mLLTipviewError != null) { mLLTipviewError.setVisibility(View.GONE); } if (mLLTipviewLoading != null) { mLLTipviewLoading.setVisibility(View.GONE); } } @Override public void onClick(View v) { if(v.getId() == R.id.bg_refush){ if(onReloadClick != null){ resetStatus(); showLoading(); onReloadClick.onReload(); } } } /** * 重新加载点击事件 */ public void setOnReloadClick(OnReloadClick onReloadClick) { this.onReloadClick = onReloadClick; } public interface OnReloadClick { void onReload(); } }
acg12/lib_common/src/main/java/com/acg12/lib/widget/TipLayoutView.java
package com.acg12.lib.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.acg12.lib.R; import java.util.List; public class TipLayoutView extends RelativeLayout implements View.OnClickListener { private ViewStub mLayoutNull, mLayoutError, mLayoutLoading; private LinearLayout mLLTipviewNull, mLLTipviewError, mLLTipviewLoading; private ImageView tv_tiplayout_pic; private TextView tv_tiplayout_msg; private BGButton mReloadButton; private OnReloadClick onReloadClick; public TipLayoutView(Context context) { super(context); initView(); } public TipLayoutView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public TipLayoutView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } private void initView() { LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.common_tiplayout_view, this); view.setOnClickListener(null); mLayoutNull = (ViewStub)findViewById(R.id.layout_null); mLayoutError = (ViewStub)findViewById(R.id.layout_error); mLayoutLoading = (ViewStub)findViewById(R.id.layout_loading); showLoading(); } /** * 现实文本内容 */ public void showContent() { if (this.getVisibility() == View.VISIBLE) { this.setVisibility(GONE); } } /** * 显示加载中布局 */ public void showLoading() { resetStatus(); if (mLLTipviewLoading == null) { View view = mLayoutLoading.inflate(); mLLTipviewLoading = (LinearLayout) view.findViewById(R.id.ll_tipview_loading); mLLTipviewLoading.setBackgroundResource(R.color.white); } if (mLLTipviewLoading.getVisibility() == View.GONE) { mLLTipviewLoading.setVisibility(View.VISIBLE); } } public void showRestLoading() { resetStatus(); if (mLLTipviewLoading == null) { View view = mLayoutLoading.inflate(); mLLTipviewLoading = (LinearLayout) view.findViewById(R.id.ll_tipview_loading); } mLLTipviewLoading.setBackgroundResource(R.color.transparent); if (mLLTipviewLoading.getVisibility() == View.GONE) { mLLTipviewLoading.setVisibility(View.VISIBLE); } } /** * 显示没有网络 */ public void showNetError() { resetStatus(); if (mLLTipviewError == null) { View view = mLayoutError.inflate(); mLLTipviewError = (LinearLayout) view.findViewById(R.id.ll_tipview_error); tv_tiplayout_pic = (ImageView) view.findViewById(R.id.tv_tiplayout_pic); tv_tiplayout_msg = (TextView) view.findViewById(R.id.tv_tiplayout_msg); mReloadButton = (BGButton) view.findViewById(R.id.bg_refush); mReloadButton.setOnClickListener(this); } if (mLLTipviewError.getVisibility() == View.GONE) { mLLTipviewError.setVisibility(View.VISIBLE); } } /** * 显示没有网络 */ public void showLoginError() { resetStatus(); if (mLLTipviewError == null) { View view = mLayoutError.inflate(); mLLTipviewError = (LinearLayout) view.findViewById(R.id.ll_tipview_error); tv_tiplayout_pic = (ImageView) view.findViewById(R.id.tv_tiplayout_pic); tv_tiplayout_msg = (TextView) view.findViewById(R.id.tv_tiplayout_msg); mReloadButton = (BGButton) view.findViewById(R.id.bg_refush); mReloadButton.setOnClickListener(this); } tv_tiplayout_msg.setText("获取消息失败,点击重新获取"); mReloadButton.setText("重新获取"); if (mLLTipviewError.getVisibility() == View.GONE) { mLLTipviewError.setVisibility(View.VISIBLE); } } /** * 显示空数据 */ public void showEmpty() { resetStatus(); if (mLLTipviewNull == null) { View view = mLayoutNull.inflate(); mLLTipviewNull = (LinearLayout) view.findViewById(R.id.ll_tipview_null); } if (mLLTipviewNull.getVisibility() == View.GONE) { mLLTipviewNull.setVisibility(View.VISIBLE); } } /** * 隐藏所有布局 */ public void resetStatus() { this.setVisibility(VISIBLE); if (mLLTipviewNull != null) { mLLTipviewNull.setVisibility(View.GONE); } if (mLLTipviewError != null) { mLLTipviewError.setVisibility(View.GONE); } if (mLLTipviewLoading != null) { mLLTipviewLoading.setVisibility(View.GONE); } } @Override public void onClick(View v) { if(v.getId() == R.id.bg_refush){ if(onReloadClick != null){ resetStatus(); onReloadClick.onReload(); } } } /** * 重新加载点击事件 */ public void setOnReloadClick(OnReloadClick onReloadClick) { this.onReloadClick = onReloadClick; } public interface OnReloadClick { void onReload(); } }
fix:修改占位布局
acg12/lib_common/src/main/java/com/acg12/lib/widget/TipLayoutView.java
fix:修改占位布局
<ide><path>cg12/lib_common/src/main/java/com/acg12/lib/widget/TipLayoutView.java <ide> } <ide> <ide> /** <del> * 显示没有网络 <add> * 显示加载失败 <ide> */ <ide> public void showLoginError() { <ide> resetStatus(); <ide> } <ide> <ide> /** <add> * 显示空数据且存在刷新按钮 <add> */ <add> public void showEmptyOrRefresh() { <add> resetStatus(); <add> if (mLLTipviewError == null) { <add> View view = mLayoutError.inflate(); <add> mLLTipviewError = (LinearLayout) view.findViewById(R.id.ll_tipview_error); <add> tv_tiplayout_pic = (ImageView) view.findViewById(R.id.tv_tiplayout_pic); <add> tv_tiplayout_msg = (TextView) view.findViewById(R.id.tv_tiplayout_msg); <add> mReloadButton = (BGButton) view.findViewById(R.id.bg_refush); <add> mReloadButton.setOnClickListener(this); <add> } <add> tv_tiplayout_pic.setImageResource(R.mipmap.bg_loading_null); <add> tv_tiplayout_msg.setText(""); <add> tv_tiplayout_msg.setVisibility(View.GONE); <add> mReloadButton.setText("再次获取"); <add> if (mLLTipviewError.getVisibility() == View.GONE) { <add> mLLTipviewError.setVisibility(View.VISIBLE); <add> } <add> } <add> <add> /** <ide> * 显示空数据 <ide> */ <ide> public void showEmpty() { <ide> if(v.getId() == R.id.bg_refush){ <ide> if(onReloadClick != null){ <ide> resetStatus(); <add> showLoading(); <ide> onReloadClick.onReload(); <ide> } <ide> }
JavaScript
apache-2.0
a7eff4d520f70533d2534a796b8249ac47cc951e
0
DuoSoftware/DVP-Apps,DuoSoftware/DVP-Apps
/** * Created by Pawan on 1/14/2016. */ (function () { var Userobj; var dbservice = function ($http,$mdDialog,$mdMedia){ var getUserList = function () { return $http({ method: 'GET', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUsers", headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var getUser = function (uID) { return $http({ method: 'GET', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUser/"+uID, headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var userDelete = function (user) { return $http({ method: 'DELETE', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/1.0/CloudConfiguration/CloudEndUser/"+user, headers: { 'authorization': '1#1' } }).then(function(response) { response.id=user; return response; }); }; var updateUser = function (user) { return $http({ method: 'PUT', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUser/"+user.id, headers: { 'authorization': '1#1' }, data:user }).then(function(response) { return response; }); }; var newUser = function (user) { return $http({ method: 'PUT', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUser", headers: { 'authorization': '1#1' }, data:user }).then(function(response) { return response; }); }; var loadClusterDetails = function() { return $http({ method: 'GET', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/Clouds", headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var getContextList = function () { return $http({ method: 'GET', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Contexts", headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var newContext = function(newObj) { return $http({ method: 'POST', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context", headers: { 'authorization': '1#1' }, data:newObj }).then(function(response) { return response; }); }; var getContext = function (context) { return $http({ method: 'GET', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context/"+context, headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var updateContext = function (contextObj) { return $http({ method: 'PUT', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context/"+contextObj.Context, headers: { 'authorization': '1#1' }, data:contextObj }).then(function(response) { return response; }); }; var deleteContext = function (contextObj) { return $http({ method: 'DELETE', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context/"+contextObj.Context, headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; return{ Userobj:Userobj, userDelete:userDelete, getUserList:getUserList, updateUser:updateUser, newUser:newUser, getUser:getUser, loadClusterDetails:loadClusterDetails, getContextList:getContextList, newContext:newContext, getContext:getContext, updateContext:updateContext, deleteContext:deleteContext }; }; var module = angular.module("clduserapp"); module.factory("dbservice",dbservice); }());
DVP-CloudEnduserManager/scripts/services/DBservice.js
/** * Created by Pawan on 1/14/2016. */ (function () { var Userobj; var dbservice = function ($http,$mdDialog,$mdMedia){ var getUserList = function () { return $http({ method: 'GET', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUsers", headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var getUser = function (uID) { return $http({ method: 'GET', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUser/"+uID, headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var userDelete = function (user) { return $http({ method: 'DELETE', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/1.0/CloudConfiguration/CloudEndUser/"+user, headers: { 'authorization': '1#1' } }).then(function(response) { response.id=user; return response; }); }; var updateUser = function (user) { return $http({ method: 'PUT', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUser/"+user.id, headers: { 'authorization': '1#1' }, data:user }).then(function(response) { response.id=user; return response; }); }; var newUser = function (user) { return $http({ method: 'PUT', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/CloudEndUser", headers: { 'authorization': '1#1' }, data:user }).then(function(response) { return response; }); }; var loadClusterDetails = function() { return $http({ method: 'GET', url: "http://clusterconfig.104.131.67.21.xip.io/DVP/API/1.0.0.0/CloudConfiguration/Clouds", headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var getContextList = function () { return $http({ method: 'GET', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Contexts", headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var newContext = function(newObj) { return $http({ method: 'POST', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context", headers: { 'authorization': '1#1' }, data:newObj }).then(function(response) { return response; }); }; var getContext = function (context) { return $http({ method: 'GET', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context/"+context, headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; var updateContext = function (contextObj) { return $http({ method: 'PUT', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context/"+contextObj.Context, headers: { 'authorization': '1#1' }, data:contextObj }).then(function(response) { return response; }); }; var deleteContext = function (contextObj) { return $http({ method: 'DELETE', url: "http://sipuserendpointservice.104.131.67.21.xip.io/DVP/API/1.0.0.0/SipUser/Context/"+contextObj.Context, headers: { 'authorization': '1#1' } }).then(function(response) { return response; }); }; return{ Userobj:Userobj, userDelete:userDelete, getUserList:getUserList, updateUser:updateUser, newUser:newUser, getUser:getUser, loadClusterDetails:loadClusterDetails, getContextList:getContextList, newContext:newContext, getContext:getContext, updateContext:updateContext, deleteContext:deleteContext }; }; var module = angular.module("clduserapp"); module.factory("dbservice",dbservice); }());
updated
DVP-CloudEnduserManager/scripts/services/DBservice.js
updated
<ide><path>VP-CloudEnduserManager/scripts/services/DBservice.js <ide> data:user <ide> }).then(function(response) <ide> { <del> response.id=user; <ide> return response; <ide> }); <ide>
JavaScript
mit
dd51e9b6dce8d2ec9e603355032405ab1c2f2cdd
0
GGAlanSmithee/Entities,GGAlanSmithee/Entities
import EntityManager from './Entity'; export default class EventHandler { constructor() { this.events = new Map(); } emptyPromise() { return new Promise(function(resolve, reject) { resolve(); }); } promise(callback, context, args, timeout) { if (timeout) { return new Promise(function(resolve, reject) { setTimeout(function(){ resolve(typeof context === 'object' ? callback.call(context, ...args) : callback.apply(context, ...args)); }, timeout); }); } return new Promise(function(resolve, reject) { resolve(typeof context === 'object' ? callback.call(context, ...args) : callback.apply(context, ...args)); }); } getNextEventId() { let max = -1; this.events.forEach(event => { max = Math.max(max, ...event.keys()); }); return max + 1; } listen(event, callback) { if (typeof event !== 'string' || typeof callback !== 'function') { return; } if (!this.events.has(event)) { this.events.set(event, new Map()); } let eventId = this.getNextEventId(); this.events.get(event).set(eventId, callback); return eventId; } stopListen(eventId) { if (!Number.isInteger(eventId)) { return false; } for (let events of this.events.values()) { for (let id of events.keys()) { if (id === eventId) { return events.delete(eventId); } } } return false; } trigger() { let args = arguments; let event = Array.prototype.splice.call(args, 0, 1)[0]; let self = this instanceof EntityManager ? this.eventHandler : this; let context = this; if (typeof event !== 'string' || !self.events.has(event)) { return self.emptyPromise(); } let promises = []; for (let callback of self.events.get(event).values()) { promises.push(self.promise(callback, context, args)); } return Promise.all(promises); } triggerDelayed() { let args = arguments; let event = Array.prototype.splice.call(args, 0, 1)[0]; let timeout = Array.prototype.splice.call(args, 0, 1)[0]; let self = this instanceof EntityManager ? this.eventHandler : this; let context = this; if (typeof event !== 'string' || !Number.isInteger(timeout) || !self.events.has(event)) { return self.emptyPromise(); } let promises = []; for (let callback of self.events.get(event).values()) { promises.push(self.promise(callback, context, args, timeout)); } return Promise.all(promises); } }
src/core/Event.js
import EntityManager from './Entity'; export default class EventHandler { constructor() { this.events = new Map(); } emptyPromise() { return new Promise(function(resolve, reject) { resolve(); }); } promise(callback, context, args, timeout) { if (timeout) { return new Promise(function(resolve, reject) { setTimeout(function(){ resolve(typeof context === 'object' ? callback.call(context, ...args) : callback.apply(context, ...args)); }, timeout); }); } return new Promise(function(resolve, reject) { resolve(typeof context === 'object' ? callback.call(context, ...args) : callback.apply(context, ...args)); }); } getNextEventId() { let max = -1; this.events.forEach(event => { max = Math.max(max, ...event.keys()); }); return max + 1; } listen(event, callback) { if (typeof event !== 'string' || typeof callback !== 'function') { return; } if (!this.events.has(event)) { this.events.set(event, new Map()); } let eventId = this.getNextEventId(); this.events.get(event).set(eventId, callback); return eventId; } stopListen(eventId) { if (!Number.isInteger(eventId)) { return false; } for (let events of this.events.values()) { for (let id of events.keys()) { if (id === eventId) { return events.delete(eventId); } } } return false; } trigger() { let args = arguments; let event = Array.prototype.splice.call(args, 0, 1)[0]; let self = this instanceof EntityManager ? this.eventHandler : this; let context = this; if (typeof event !== 'string' || !self.events.has(event)) { return self.emptyPromise(); } let promises = []; for (let callback of self.events.get(event).values()) { promises.push(self.promise(callback, context, args)); } return Promise.all(promises); } triggerDelayed() { let args = arguments; let event = Array.prototype.splice.call(args, 0, 1)[0]; let timeout = Array.prototype.splice.call(args, 0, 1)[0]; console.log(event, timeout); let self = this instanceof EntityManager ? this.eventHandler : this; let context = this; if (typeof event !== 'string' || !Number.isInteger(timeout) || !self.events.has(event)) { return self.emptyPromise(); } let promises = []; for (let callback of self.events.get(event).values()) { promises.push(self.promise(callback, context, args, timeout)); } return Promise.all(promises); } }
removes left over console.log
src/core/Event.js
removes left over console.log
<ide><path>rc/core/Event.js <ide> let event = Array.prototype.splice.call(args, 0, 1)[0]; <ide> let timeout = Array.prototype.splice.call(args, 0, 1)[0]; <ide> <del> console.log(event, timeout); <del> <ide> let self = this instanceof EntityManager ? this.eventHandler : this; <ide> let context = this; <ide>
Java
apache-2.0
ba728b2a2b0d70cf526a0a54fbcdc7ce889b36b3
0
MuirDH/Miwok
package com.example.android.miwok; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import static com.example.android.miwok.R.id.rootView; public class NumbersActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_numbers); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Find the root view of the layout LinearLayout foundRootView = (LinearLayout)findViewById(rootView); printNumbers(foundRootView); } private void printNumbers (LinearLayout rootView){ //Create an ArrayList containing the words for the numbers 1-10 ArrayList<String> words = new ArrayList<>(); words.add("one"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten"); // loops until we get to the end of the ArrayList for (int index = 0; index < words.size(); index++){ // Create a new TextView TextView wordView = new TextView(this); // Set the text to be the number word at the current index wordView.setText(words.get(index)); // Add this view as another child to the root view of this layout rootView.addView(wordView); } } }
app/src/main/java/com/example/android/miwok/NumbersActivity.java
package com.example.android.miwok; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; public class NumbersActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_numbers); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //Create an ArrayList containing the words for the numbers 1-10 ArrayList<String> words = new ArrayList<>(); words.add("one"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten"); // Find the root view of the layout LinearLayout rootView = (LinearLayout)findViewById(R.id.rootView); // Create a new TextView that displays the number word at the index position and adds the // view as a child to the rootView then loops until we get to the end of the ArrayList for (int index = 0; index < words.size(); index++){ TextView wordView = new TextView(this); wordView.setText(words.get(index)); rootView.addView(wordView); } } }
Pull out the ArrayList and for loop into its own method
app/src/main/java/com/example/android/miwok/NumbersActivity.java
Pull out the ArrayList and for loop into its own method
<ide><path>pp/src/main/java/com/example/android/miwok/NumbersActivity.java <ide> <ide> import java.util.ArrayList; <ide> <add>import static com.example.android.miwok.R.id.rootView; <add> <ide> public class NumbersActivity extends AppCompatActivity { <ide> <ide> @Override <ide> setContentView(R.layout.activity_numbers); <ide> Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); <ide> setSupportActionBar(toolbar); <add> <add> // Find the root view of the layout <add> LinearLayout foundRootView = (LinearLayout)findViewById(rootView); <add> printNumbers(foundRootView); <add> <add> } <add> <add> private void printNumbers (LinearLayout rootView){ <ide> <ide> //Create an ArrayList containing the words for the numbers 1-10 <ide> ArrayList<String> words = new ArrayList<>(); <ide> words.add("eight"); <ide> words.add("nine"); <ide> words.add("ten"); <del> <del> // Find the root view of the layout <del> LinearLayout rootView = (LinearLayout)findViewById(R.id.rootView); <del> <del> // Create a new TextView that displays the number word at the index position and adds the <del> // view as a child to the rootView then loops until we get to the end of the ArrayList <add> // loops until we get to the end of the ArrayList <ide> for (int index = 0; index < words.size(); index++){ <ide> <add> // Create a new TextView <ide> TextView wordView = new TextView(this); <add> <add> // Set the text to be the number word at the current index <ide> wordView.setText(words.get(index)); <add> <add> // Add this view as another child to the root view of this layout <ide> rootView.addView(wordView); <ide> } <add> } <ide> <ide> <del> } <ide> <ide> }
JavaScript
mit
f3e0dc9cefc18e2b0c9f12cd06551534d59a96bf
0
plaid/plaid-node,hellodigit/plaid-node-1
var _ = require('underscore') , async = require('async') , request = require('request') , qs = require('querystring') , defaults = require('./defaults') , forms = require('forms') , fields = forms.fields; /* TODO Getting options from multiple functions Handle MFA have testing feature with commandline enter User built in funcitions like that ironio one Have built in convert to HTML forms */ /** * Plaid.io node client driver * * @param {Object} config * @param {String} client_id - Plaid.io "client_id" * @param {String} secret - Plaid.io "secret" * */ var Client = module.exports = function (config) { this.initialized = false; if (config) this.init(config); }; /** * Initializes this client. * * @param {Object} config * @param {String} client_id - Plaid.io "client_id" * @param {String} secret - Plaid.io "secret" * */ Client.prototype.init = function (config) { if (config.secret.length<0 || config.client_id.length<0) throw new Error('plaid-node client must be initialized with a '+ 'non-empty API "secret" and "client_id" parameter.'); if (typeof(config.secret)!='string' || typeof(config.client_id)!='string') throw new Error('plaid-node client must be initialized with a '+ 'non-empty API "secret" and "client_id" parameter.'); this.secret = config.secret; this.client_id = config.client_id; this.config = _.defaults(config || {}, defaults); this.initialized = true; }; /** * Internal method to check whether the client has been initialized. * @private */ Client.prototype._checkInitialized = function () { if (!this.initialized) throw new Error('analytics-node client is not initialized. Please call ' + 'client.init(config).'); }; /** * Connect a card to the Plaid API * * * @param {Object} credentials - The credentials for that card * @param {String} username - id for logged in user * @param {Password} password - key/value object of tags for the user (optional) ... * * @param {Object} options - app provided context about the user (optional) * * @callback {Error, Object, Object} * */ Client.prototype.connect = function (credentials, type, email, options, callback) { this._checkInitialized(); if (!credentials || typeof(credentials)!= 'object') { throw new Error('[plaid]#connect: credentials must be an object'); } if(!callback && (typeof options ==='function')) { callback = options; options = {}; } if(!type || typeof(type)!='string'){ throw new Error('[plaid]#connect: Type missing or invalid'); } if(!email || typeof(email)!='string'){ throw new Error('[plaid]#connect: Email missing or invalid'); } if(!callback){ callback = function(){}; } this.options = options; this.credentials = credentials; this.type = type; this.email = email; return this._exec('submit', callback); }; Client.prototype.step = function (access_token, mfa, options, callback) { this._checkInitialized(); if(!callback && typeof(options)=='function'){ callback = options; options = {}; } if(!callback){ callback = function(){}; } this.options = options; this.access_token = access_token; this.mfa = mfa; return this._exec('step', callback); }; Client.prototype.get = function(access_token, options, callback) { this._checkInitialized(); if(!callback && typeof(options) == 'function') { callback = options; options = {}; } this.options = options; this.access_token = access_token; return this._exec('get', callback); } Client.prototype.remove = function(access_token, options, callback) { this._checkInitialized(); if(!callback && typeof(options) == 'function') { callback = options; options = {}; } this.options = options; this.access_token = access_token; return this._exec('remove', callback); } Client.prototype._exec = function (method, callback){ var uri = this.config.protocol + this.config.host + this.config.endpoint[method].route; var query = { client_id : this.client_id , secret : this.secret , credentials : JSON.stringify(this.credentials) , type : this.type , email : this.email , access_token: this.access_token , options : JSON.stringify(this.options) , mfa : this.mfa } // the login option has to be set a separate parameter if (this.options.login) { query.login = this.options.login; } uri += "?"+qs.stringify(query); var self = this; request( { method: this.config.endpoint[method].method , uri: uri //, qs : qs.stringify(query) } , function (error, response, body) { if(!response) response = {}; if(error || ( response.statusCode > 299 ) ) return self._handleError(error, response.statusCode, body, callback); self.body = body; return self._handleSuccess(callback); } ) } Client.prototype._handleSuccess = function(callback){ try{ this.body = JSON.parse(this.body); }catch(err){ return callback("Couldn't parse body"); } if(this.body.status === 'MFA') return this._handleMFA(callback); return callback(null, this.body, (typeof this.body.mfa !== 'undefined')); } Client.prototype._handleError = function(error, status, body, callback){ if(error) return callback(error) try{ body = JSON.parse(body); }catch(err){ return callback("Couldn't parse body"); } return callback(body); } Client.prototype._handleMFA = function(callback){ this.config.endpoint = '/connect/submit/step'; this.access_token = this.access_token || this.body.accessToken; this.options.itemID = this.options.itemID || this.body.message.itemID; var self = this; //helper var step = function(credentials, callback){ if(self.options.mfaCL) return self._mfaCL(credentials, callback); return self.connect(credentials, self.type, self.email, self.options, callback); } var html = function(){ return self._formToHTML(self.body.message.form); } this.body.message.step = step; if(this.body.message.form) this.body.message.form.html = html; else console.log(this.body.message); return callback(null, this.body, true) } /* MFA testing CL */ Client.prototype._mfaCL = function(credentials, callback){ var readline = require('readline'); var credentials = {}; //Making sure there is a valid form object if(this.body.message.form) var holder = this.body.message.form; else{ return console.log("Unknown message"); } var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); //The function that is called for every question var read = function(question, cbk){ var display = question.display + ": "; rl.question(display, function(answer) { credentials[display]=answer; return cbk(); }); } var self = this; async.forEachSeries(holder, read, function(err, result){ //Closing the readline interface rl.close(); self.credentials = credentials; return self.connect(self.credentials, self.type, self.email, self.options, callback); }); } Client.prototype._formToHTML = function(raw){ var form = {}; for(i in raw){ if(raw[i].type=='text') form[raw[i].display]=fields.string(); } var form = forms.create(form).toHTML(); return '<form>'+form+'</form>'; }
lib/client.js
var _ = require('underscore') , async = require('async') , request = require('request') , qs = require('querystring') , defaults = require('./defaults') , forms = require('forms') , fields = forms.fields; /* TODO Getting options from multiple functions Handle MFA have testing feature with commandline enter User built in funcitions like that ironio one Have built in convert to HTML forms */ /** * Plaid.io node client driver * * @param {Object} config * @param {String} client_id - Plaid.io "client_id" * @param {String} secret - Plaid.io "secret" * */ var Client = module.exports = function (config) { this.initialized = false; if (config) this.init(config); }; /** * Initializes this client. * * @param {Object} config * @param {String} client_id - Plaid.io "client_id" * @param {String} secret - Plaid.io "secret" * */ Client.prototype.init = function (config) { if (config.secret.length<0 || config.client_id.length<0) throw new Error('plaid-node client must be initialized with a '+ 'non-empty API "secret" and "client_id" parameter.'); if (typeof(config.secret)!='string' || typeof(config.client_id)!='string') throw new Error('plaid-node client must be initialized with a '+ 'non-empty API "secret" and "client_id" parameter.'); this.secret = config.secret; this.client_id = config.client_id; this.config = _.defaults(config || {}, defaults); this.initialized = true; }; /** * Internal method to check whether the client has been initialized. * @private */ Client.prototype._checkInitialized = function () { if (!this.initialized) throw new Error('analytics-node client is not initialized. Please call ' + 'client.init(config).'); }; /** * Connect a card to the Plaid API * * * @param {Object} credentials - The credentials for that card * @param {String} username - id for logged in user * @param {Password} password - key/value object of tags for the user (optional) ... * * @param {Object} options - app provided context about the user (optional) * * @callback {Error, Object, Object} * */ Client.prototype.connect = function (credentials, type, email, options, callback) { this._checkInitialized(); if (!credentials || typeof(credentials)!= 'object') { throw new Error('[plaid]#connect: credentials must be an object'); } if(!callback && (typeof options ==='function')) { callback = options; options = {}; } if(!type || typeof(type)!='string'){ throw new Error('[plaid]#connect: Type missing or invalid'); } if(!email || typeof(email)!='string'){ throw new Error('[plaid]#connect: Email missing or invalid'); } if(!callback){ callback = function(){}; } this.options = options; this.credentials = credentials; this.type = type; this.email = email; return this._exec('submit', callback); }; Client.prototype.step = function (access_token, mfa, options, callback) { this._checkInitialized(); if(!callback && typeof(options)=='function'){ callback = options; options = {}; } if(!callback){ callback = function(){}; } this.options = options; this.access_token = access_token; this.mfa = mfa; return this._exec('step', callback); }; Client.prototype.get = function(access_token, options, callback) { this._checkInitialized(); if(!callback && typeof(options) == 'function') { callback = options; options = {}; } this.options = options; this.access_token = access_token; return this._exec('get', callback); } Client.prototype.remove = function(access_token, options, callback) { this._checkInitialized(); if(!callback && typeof(options) == 'function') { callback = options; options = {}; } this.options = options; this.access_token = access_token; return this._exec('remove', callback); } Client.prototype._exec = function (method, callback){ var uri = this.config.protocol + this.config.host + this.config.endpoint[method].route; var query = { client_id : this.client_id , secret : this.secret , credentials : JSON.stringify(this.credentials) , type : this.type , email : this.email , access_token: this.access_token , options : JSON.stringify(this.options) , mfa : this.mfa } // the login option has to be set a separate parameter if (this.options.login) { query.login = this.options.login; } uri += "?"+qs.stringify(query); var self = this; request( { method: this.config.endpoint[method].method , uri: uri //, qs : qs.stringify(query) } , function (error, response, body) { if(!response) response = {}; if(error || ( response.statusCode > 299 ) ) return self._handleError(error, response.statusCode, body, callback); self.body = body; return self._handleSuccess(callback); } ) } Client.prototype._handleSuccess = function(callback){ try{ this.body = JSON.parse(this.body); }catch(err){ return callback("Couldn't parse body"); } if(this.body.status === 'MFA') return this._handleMFA(callback); return callback(null, this.body, (this.body.mfa !== 'undefined')); } Client.prototype._handleError = function(error, status, body, callback){ if(error) return callback(error) try{ body = JSON.parse(body); }catch(err){ return callback("Couldn't parse body"); } return callback(body); } Client.prototype._handleMFA = function(callback){ this.config.endpoint = '/connect/submit/step'; this.access_token = this.access_token || this.body.accessToken; this.options.itemID = this.options.itemID || this.body.message.itemID; var self = this; //helper var step = function(credentials, callback){ if(self.options.mfaCL) return self._mfaCL(credentials, callback); return self.connect(credentials, self.type, self.email, self.options, callback); } var html = function(){ return self._formToHTML(self.body.message.form); } this.body.message.step = step; if(this.body.message.form) this.body.message.form.html = html; else console.log(this.body.message); return callback(null, this.body, true) } /* MFA testing CL */ Client.prototype._mfaCL = function(credentials, callback){ var readline = require('readline'); var credentials = {}; //Making sure there is a valid form object if(this.body.message.form) var holder = this.body.message.form; else{ return console.log("Unknown message"); } var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); //The function that is called for every question var read = function(question, cbk){ var display = question.display + ": "; rl.question(display, function(answer) { credentials[display]=answer; return cbk(); }); } var self = this; async.forEachSeries(holder, read, function(err, result){ //Closing the readline interface rl.close(); self.credentials = credentials; return self.connect(self.credentials, self.type, self.email, self.options, callback); }); } Client.prototype._formToHTML = function(raw){ var form = {}; for(i in raw){ if(raw[i].type=='text') form[raw[i].display]=fields.string(); } var form = forms.create(form).toHTML(); return '<form>'+form+'</form>'; }
fix mfa response
lib/client.js
fix mfa response
<ide><path>ib/client.js <ide> uri += "?"+qs.stringify(query); <ide> <ide> var self = this; <del> <add> <ide> request( <ide> { method: this.config.endpoint[method].method <ide> , uri: uri <ide> <ide> if(this.body.status === 'MFA') <ide> return this._handleMFA(callback); <del> <del> return callback(null, this.body, (this.body.mfa !== 'undefined')); <add> <add> return callback(null, this.body, (typeof this.body.mfa !== 'undefined')); <ide> } <ide> <ide> Client.prototype._handleError = function(error, status, body, callback){
Java
apache-2.0
51a205920f241eb5fa91d5f220e3ee0a7a573190
0
ChunPIG/sigar,abhinavmishra14/sigar,monicasarbu/sigar,scouter-project/sigar,OlegYch/sigar,monicasarbu/sigar,hyperic/sigar,scouter-project/sigar,hyperic/sigar,ruleless/sigar,monicasarbu/sigar,ruleless/sigar,ruleless/sigar,racker/sigar,hyperic/sigar,formicary/sigar,hyperic/sigar,kaustavha/sigar,monicasarbu/sigar,lsjeng/sigar,lsjeng/sigar,racker/sigar,OlegYch/sigar,ChunPIG/sigar,kaustavha/sigar,ChunPIG/sigar,scouter-project/sigar,OlegYch/sigar,cit-lab/sigar,lsjeng/sigar,kaustavha/sigar,ruleless/sigar,abhinavmishra14/sigar,abhinavmishra14/sigar,boundary/sigar,ChunPIG/sigar,monicasarbu/sigar,ChunPIG/sigar,boundary/sigar,kaustavha/sigar,formicary/sigar,formicary/sigar,abhinavmishra14/sigar,kaustavha/sigar,hyperic/sigar,kaustavha/sigar,ChunPIG/sigar,kaustavha/sigar,boundary/sigar,couchbase/sigar,lsjeng/sigar,scouter-project/sigar,scouter-project/sigar,cit-lab/sigar,ruleless/sigar,OlegYch/sigar,abhinavmishra14/sigar,cit-lab/sigar,formicary/sigar,monicasarbu/sigar,abhinavmishra14/sigar,cit-lab/sigar,scouter-project/sigar,OlegYch/sigar,ChunPIG/sigar,kaustavha/sigar,monicasarbu/sigar,abhinavmishra14/sigar,cit-lab/sigar,ruleless/sigar,monicasarbu/sigar,boundary/sigar,ruleless/sigar,boundary/sigar,boundary/sigar,hyperic/sigar,formicary/sigar,OlegYch/sigar,hyperic/sigar,ruleless/sigar,cit-lab/sigar,formicary/sigar,cit-lab/sigar,racker/sigar,hyperic/sigar,ChunPIG/sigar,scouter-project/sigar,cit-lab/sigar,racker/sigar,boundary/sigar,formicary/sigar,lsjeng/sigar,lsjeng/sigar,cit-lab/sigar,boundary/sigar,kaustavha/sigar,racker/sigar,formicary/sigar,monicasarbu/sigar,boundary/sigar,kaustavha/sigar,ruleless/sigar,monicasarbu/sigar,lsjeng/sigar,OlegYch/sigar,formicary/sigar,scouter-project/sigar,ChunPIG/sigar,racker/sigar,cit-lab/sigar,ChunPIG/sigar,hyperic/sigar,boundary/sigar,racker/sigar,hyperic/sigar,abhinavmishra14/sigar,hyperic/sigar,lsjeng/sigar,abhinavmishra14/sigar,racker/sigar,OlegYch/sigar,scouter-project/sigar,abhinavmishra14/sigar,ruleless/sigar,scouter-project/sigar,formicary/sigar,racker/sigar,lsjeng/sigar,kaustavha/sigar,abhinavmishra14/sigar,couchbase/sigar,scouter-project/sigar,OlegYch/sigar,monicasarbu/sigar,cit-lab/sigar,racker/sigar,lsjeng/sigar,OlegYch/sigar
/* * Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * This file is part of SIGAR. * * SIGAR is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.sigar.test; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Mem; public class TestMem extends SigarTestCase { public TestMem(String name) { super(name); } public void testCreate() throws Exception { Sigar sigar = getSigar(); Mem mem = sigar.getMem(); assertGtZeroTrace("Total", mem.getTotal()); assertGtZeroTrace("Used", mem.getUsed()); traceln("UsedPercent=" + mem.getUsedPercent()); assertGtZeroTrace("(long)UsedPercent", (long)mem.getUsedPercent()); assertTrue(mem.getUsedPercent() <= 100); traceln("FreePercent=" + mem.getFreePercent()); assertGtEqZeroTrace("(long)FreePercent", (long)mem.getFreePercent()); assertTrue(mem.getFreePercent() < 100); assertGtZeroTrace("Free", mem.getFree()); assertGtZeroTrace("ActualUsed", mem.getUsed()); assertGtZeroTrace("ActualFree", mem.getFree()); assertGtZeroTrace("Ram", mem.getRam()); assertTrue((mem.getRam() % 8) == 0); } }
bindings/java/src/org/hyperic/sigar/test/TestMem.java
/* * Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * This file is part of SIGAR. * * SIGAR is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.sigar.test; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Mem; public class TestMem extends SigarTestCase { public TestMem(String name) { super(name); } public void testCreate() throws Exception { Sigar sigar = getSigar(); Mem mem = sigar.getMem(); assertGtZeroTrace("Total", mem.getTotal()); assertGtZeroTrace("Used", mem.getUsed()); traceln("UsedPercent=" + mem.getUsedPercent()); traceln("FreePercent=" + mem.getFreePercent()); assertGtZeroTrace("Free", mem.getFree()); assertGtZeroTrace("ActualUsed", mem.getUsed()); assertGtZeroTrace("ActualFree", mem.getFree()); assertGtZeroTrace("Ram", mem.getRam()); assertTrue((mem.getRam() % 8) == 0); } }
add assertions
bindings/java/src/org/hyperic/sigar/test/TestMem.java
add assertions
<ide><path>indings/java/src/org/hyperic/sigar/test/TestMem.java <ide> assertGtZeroTrace("Used", mem.getUsed()); <ide> <ide> traceln("UsedPercent=" + mem.getUsedPercent()); <add> assertGtZeroTrace("(long)UsedPercent", (long)mem.getUsedPercent()); <add> <add> assertTrue(mem.getUsedPercent() <= 100); <ide> <ide> traceln("FreePercent=" + mem.getFreePercent()); <add> assertGtEqZeroTrace("(long)FreePercent", (long)mem.getFreePercent()); <add> <add> assertTrue(mem.getFreePercent() < 100); <ide> <ide> assertGtZeroTrace("Free", mem.getFree()); <ide>
Java
apache-2.0
error: pathspec 'src/com/xnx3/LocationUtil.java' did not match any file(s) known to git
5155eae345d3b864098d3299e64f43bd5c746ee8
1
xnx3/xnx3
package com.xnx3; /** * 位置、定位相关 * @author 管雷鸣 */ public class LocationUtil { private static double EARTH_RADIUS = 6378.137; private static double rad(double d) { return d * Math.PI / 180.0; } /** * 通过经纬度获取距离(单位:米) * @param lat1 * @param lng1 * @param lat2 * @param lng2 * @return 米 */ public static double distance(double lat1, double lng1, double lat2,double lng2) { double radLat1 = rad(lat1); double radLat2 = rad(lat2); double a = radLat1 - radLat2; double b = rad(lng1) - rad(lng2); double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2))); s = s * EARTH_RADIUS; s = Math.round(s * 10000d) / 10000d; s = s*1000; return s; } }
src/com/xnx3/LocationUtil.java
xnx3 add LocationUtil
src/com/xnx3/LocationUtil.java
xnx3
<ide><path>rc/com/xnx3/LocationUtil.java <add>package com.xnx3; <add> <add>/** <add> * 位置、定位相关 <add> * @author 管雷鸣 <add> */ <add>public class LocationUtil { <add> private static double EARTH_RADIUS = 6378.137; <add> <add> private static double rad(double d) { <add> return d * Math.PI / 180.0; <add> } <add> <add> /** <add> * 通过经纬度获取距离(单位:米) <add> * @param lat1 <add> * @param lng1 <add> * @param lat2 <add> * @param lng2 <add> * @return 米 <add> */ <add> public static double distance(double lat1, double lng1, double lat2,double lng2) { <add> double radLat1 = rad(lat1); <add> double radLat2 = rad(lat2); <add> double a = radLat1 - radLat2; <add> double b = rad(lng1) - rad(lng2); <add> double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) <add> + Math.cos(radLat1) * Math.cos(radLat2) <add> * Math.pow(Math.sin(b / 2), 2))); <add> s = s * EARTH_RADIUS; <add> s = Math.round(s * 10000d) / 10000d; <add> s = s*1000; <add> return s; <add> } <add>}
Java
agpl-3.0
fde60cbfb700324be1f9a2b634b318f8dae94bb2
0
quikkian-ua-devops/kfs,ua-eas/kfs,bhutchinson/kfs,bhutchinson/kfs,bhutchinson/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,kkronenb/kfs,kuali/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kuali/kfs,kuali/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,kkronenb/kfs,smith750/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,kuali/kfs,UniversityOfHawaii/kfs
/* * Copyright 2005-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.gl.batch.service.impl; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.ojb.broker.metadata.MetadataManager; import org.kuali.kfs.gl.GeneralLedgerConstants; import org.kuali.kfs.gl.batch.service.EncumbranceCalculator; import org.kuali.kfs.gl.batch.service.PostTransaction; import org.kuali.kfs.gl.batch.service.VerifyTransaction; import org.kuali.kfs.gl.businessobject.Encumbrance; import org.kuali.kfs.gl.businessobject.Entry; import org.kuali.kfs.gl.businessobject.Transaction; import org.kuali.kfs.gl.dataaccess.EncumbranceDao; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.Message; import org.kuali.rice.kns.service.DateTimeService; import org.springframework.transaction.annotation.Transactional; /** * This implementation of PostTransaction posts a transaction that could be an encumbrance */ @Transactional public class PostEncumbrance implements PostTransaction, VerifyTransaction, EncumbranceCalculator { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PostEncumbrance.class); private EncumbranceDao encumbranceDao; private DateTimeService dateTimeService; public void setEncumbranceDao(EncumbranceDao ed) { encumbranceDao = ed; } /** * Constructs a PostEncumbrance instance */ public PostEncumbrance() { super(); } /** * Make sure the transaction is correct for posting. If there is an error, this will stop the transaction from posting in all * files. * * @param t the transaction to verify * @return a List of error messages, as Strings */ public List<Message> verifyTransaction(Transaction t) { LOG.debug("verifyTransaction() started"); //TODO: Shawn - need to check with Jeff because there is no this method in FIS List<Message> errors = new ArrayList(); // The encumbrance update code can only be space, N, R or D. Nothing else if ((StringUtils.isNotBlank(t.getTransactionEncumbranceUpdateCode())) && (!" ".equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_NO_ENCUMBRANCE_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()))) { errors.add(new Message("Invalid Encumbrance Update Code (" + t.getTransactionEncumbranceUpdateCode() + ")", Message.TYPE_FATAL)); } return errors; } /** * Called by the poster to post a transaction. The transaction might or might not be an encumbrance transaction. * * @param t the transaction which is being posted * @param mode the mode the poster is currently running in * @param postDate the date this transaction should post to * @return the accomplished post type */ public String post(Transaction t, int mode, Date postDate) { LOG.debug("post() started"); String returnCode = GeneralLedgerConstants.UPDATE_CODE; // If the encumbrance update code is space or N, or the object type code is FB // we don't need to post an encumbrance if ((StringUtils.isBlank(t.getTransactionEncumbranceUpdateCode())) || " ".equals(t.getTransactionEncumbranceUpdateCode()) || KFSConstants.ENCUMB_UPDT_NO_ENCUMBRANCE_CD.equals(t.getTransactionEncumbranceUpdateCode()) || t.getOption().getFinObjectTypeFundBalanceCd().equals(t.getFinancialObjectTypeCode())) { LOG.debug("post() not posting non-encumbrance transaction"); return ""; } // Get the current encumbrance record if there is one Entry e = new Entry(t, null); if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) { e.setDocumentNumber(t.getReferenceFinancialDocumentNumber()); e.setFinancialSystemOriginationCode(t.getReferenceFinancialSystemOriginationCode()); e.setFinancialDocumentTypeCode(t.getReferenceFinancialDocumentTypeCode()); } Encumbrance enc = encumbranceDao.getEncumbranceByTransaction(e); if (enc == null) { // Build a new encumbrance record enc = new Encumbrance(e); returnCode = GeneralLedgerConstants.INSERT_CODE; } else { // Use the one retrieved if (enc.getTransactionEncumbranceDate() == null) { enc.setTransactionEncumbranceDate(t.getTransactionDate()); } returnCode = GeneralLedgerConstants.UPDATE_CODE; } updateEncumbrance(t, enc); enc.setTimestamp(new Timestamp(postDate.getTime())); encumbranceDao.save(enc); return returnCode; } /** * Given a Collection of encumbrances, returns the encumbrance that would affected by the given transaction * * @param encumbranceList a Collection of encumbrances * @param t the transaction to find the appropriate encumbrance for * @return the encumbrance found from the list, or, if not found, a newly created encumbrance * @see org.kuali.kfs.gl.batch.service.EncumbranceCalculator#findEncumbrance(java.util.Collection, org.kuali.kfs.gl.businessobject.Transaction) */ public Encumbrance findEncumbrance(Collection encumbranceList, Transaction t) { // If it isn't an encumbrance transaction, skip it if ((!KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()))) { return null; } // Try to find one that already exists for (Iterator iter = encumbranceList.iterator(); iter.hasNext();) { Encumbrance e = (Encumbrance) iter.next(); if (KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()) && e.getUniversityFiscalYear().equals(t.getUniversityFiscalYear()) && e.getChartOfAccountsCode().equals(t.getChartOfAccountsCode()) && e.getAccountNumber().equals(t.getAccountNumber()) && e.getSubAccountNumber().equals(t.getSubAccountNumber()) && e.getObjectCode().equals(t.getFinancialObjectCode()) && e.getSubObjectCode().equals(t.getFinancialSubObjectCode()) && e.getBalanceTypeCode().equals(t.getFinancialBalanceTypeCode()) && e.getDocumentTypeCode().equals(t.getFinancialDocumentTypeCode()) && e.getOriginCode().equals(t.getFinancialSystemOriginationCode()) && e.getDocumentNumber().equals(t.getDocumentNumber())) { return e; } if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()) && e.getUniversityFiscalYear().equals(t.getUniversityFiscalYear()) && e.getChartOfAccountsCode().equals(t.getChartOfAccountsCode()) && e.getAccountNumber().equals(t.getAccountNumber()) && e.getSubAccountNumber().equals(t.getSubAccountNumber()) && e.getObjectCode().equals(t.getFinancialObjectCode()) && e.getSubObjectCode().equals(t.getFinancialSubObjectCode()) && e.getBalanceTypeCode().equals(t.getFinancialBalanceTypeCode()) && e.getDocumentTypeCode().equals(t.getReferenceFinancialDocumentTypeCode()) && e.getOriginCode().equals(t.getReferenceFinancialSystemOriginationCode()) && e.getDocumentNumber().equals(t.getReferenceFinancialDocumentNumber())) { return e; } } // If we couldn't find one that exists, create a new one // NOTE: the date doesn't matter so there is no need to call the date service // Changed to use the datetime service because of KULRNE-4183 Entry e = new Entry(t, dateTimeService.getCurrentDate()); if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) { e.setDocumentNumber(t.getReferenceFinancialDocumentNumber()); e.setFinancialSystemOriginationCode(t.getReferenceFinancialSystemOriginationCode()); e.setFinancialDocumentTypeCode(t.getReferenceFinancialDocumentTypeCode()); } Encumbrance enc = new Encumbrance(e); encumbranceList.add(enc); return enc; } /** * @param t * @param enc */ public void updateEncumbrance(Transaction t, Encumbrance enc) { if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) { // If using referring doc number, add or subtract transaction amount from // encumbrance closed amount if (KFSConstants.GL_DEBIT_CODE.equals(t.getTransactionDebitCreditCode())) { enc.setAccountLineEncumbranceClosedAmount(enc.getAccountLineEncumbranceClosedAmount().subtract(t.getTransactionLedgerEntryAmount())); } else { enc.setAccountLineEncumbranceClosedAmount(enc.getAccountLineEncumbranceClosedAmount().add(t.getTransactionLedgerEntryAmount())); } } else { // If not using referring doc number, add or subtract transaction amount from // encumbrance amount if (KFSConstants.GL_DEBIT_CODE.equals(t.getTransactionDebitCreditCode()) || KFSConstants.GL_BUDGET_CODE.equals(t.getTransactionDebitCreditCode())) { enc.setAccountLineEncumbranceAmount(enc.getAccountLineEncumbranceAmount().add(t.getTransactionLedgerEntryAmount())); } else { enc.setAccountLineEncumbranceAmount(enc.getAccountLineEncumbranceAmount().subtract(t.getTransactionLedgerEntryAmount())); } } } /** * @see org.kuali.kfs.gl.batch.service.PostTransaction#getDestinationName() */ public String getDestinationName() { return MetadataManager.getInstance().getGlobalRepository().getDescriptorFor(Encumbrance.class).getFullTableName(); } public void setDateTimeService(DateTimeService dateTimeService) { this.dateTimeService = dateTimeService; } }
work/src/org/kuali/kfs/gl/batch/service/impl/PostEncumbrance.java
/* * Copyright 2005-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.gl.batch.service.impl; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.ojb.broker.metadata.MetadataManager; import org.kuali.kfs.gl.GeneralLedgerConstants; import org.kuali.kfs.gl.batch.service.EncumbranceCalculator; import org.kuali.kfs.gl.batch.service.PostTransaction; import org.kuali.kfs.gl.batch.service.VerifyTransaction; import org.kuali.kfs.gl.businessobject.Encumbrance; import org.kuali.kfs.gl.businessobject.Entry; import org.kuali.kfs.gl.businessobject.Transaction; import org.kuali.kfs.gl.dataaccess.EncumbranceDao; import org.kuali.kfs.sys.KFSConstants; import org.kuali.rice.kns.service.DateTimeService; import org.springframework.transaction.annotation.Transactional; /** * This implementation of PostTransaction posts a transaction that could be an encumbrance */ @Transactional public class PostEncumbrance implements PostTransaction, VerifyTransaction, EncumbranceCalculator { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PostEncumbrance.class); private EncumbranceDao encumbranceDao; private DateTimeService dateTimeService; public void setEncumbranceDao(EncumbranceDao ed) { encumbranceDao = ed; } /** * Constructs a PostEncumbrance instance */ public PostEncumbrance() { super(); } /** * Make sure the transaction is correct for posting. If there is an error, this will stop the transaction from posting in all * files. * * @param t the transaction to verify * @return a List of error messages, as Strings */ public List verifyTransaction(Transaction t) { LOG.debug("verifyTransaction() started"); List errors = new ArrayList(); // The encumbrance update code can only be space, N, R or D. Nothing else if ((StringUtils.isNotBlank(t.getTransactionEncumbranceUpdateCode())) && (!" ".equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_NO_ENCUMBRANCE_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()))) { errors.add("Invalid Encumbrance Update Code (" + t.getTransactionEncumbranceUpdateCode() + ")"); } return errors; } /** * Called by the poster to post a transaction. The transaction might or might not be an encumbrance transaction. * * @param t the transaction which is being posted * @param mode the mode the poster is currently running in * @param postDate the date this transaction should post to * @return the accomplished post type */ public String post(Transaction t, int mode, Date postDate) { LOG.debug("post() started"); String returnCode = GeneralLedgerConstants.UPDATE_CODE; // If the encumbrance update code is space or N, or the object type code is FB // we don't need to post an encumbrance if ((StringUtils.isBlank(t.getTransactionEncumbranceUpdateCode())) || " ".equals(t.getTransactionEncumbranceUpdateCode()) || KFSConstants.ENCUMB_UPDT_NO_ENCUMBRANCE_CD.equals(t.getTransactionEncumbranceUpdateCode()) || t.getOption().getFinObjectTypeFundBalanceCd().equals(t.getFinancialObjectTypeCode())) { LOG.debug("post() not posting non-encumbrance transaction"); return ""; } // Get the current encumbrance record if there is one Entry e = new Entry(t, null); if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) { e.setDocumentNumber(t.getReferenceFinancialDocumentNumber()); e.setFinancialSystemOriginationCode(t.getReferenceFinancialSystemOriginationCode()); e.setFinancialDocumentTypeCode(t.getReferenceFinancialDocumentTypeCode()); } Encumbrance enc = encumbranceDao.getEncumbranceByTransaction(e); if (enc == null) { // Build a new encumbrance record enc = new Encumbrance(e); returnCode = GeneralLedgerConstants.INSERT_CODE; } else { // Use the one retrieved if (enc.getTransactionEncumbranceDate() == null) { enc.setTransactionEncumbranceDate(t.getTransactionDate()); } returnCode = GeneralLedgerConstants.UPDATE_CODE; } updateEncumbrance(t, enc); enc.setTimestamp(new Timestamp(postDate.getTime())); encumbranceDao.save(enc); return returnCode; } /** * Given a Collection of encumbrances, returns the encumbrance that would affected by the given transaction * * @param encumbranceList a Collection of encumbrances * @param t the transaction to find the appropriate encumbrance for * @return the encumbrance found from the list, or, if not found, a newly created encumbrance * @see org.kuali.kfs.gl.batch.service.EncumbranceCalculator#findEncumbrance(java.util.Collection, org.kuali.kfs.gl.businessobject.Transaction) */ public Encumbrance findEncumbrance(Collection encumbranceList, Transaction t) { // If it isn't an encumbrance transaction, skip it if ((!KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()))) { return null; } // Try to find one that already exists for (Iterator iter = encumbranceList.iterator(); iter.hasNext();) { Encumbrance e = (Encumbrance) iter.next(); if (KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()) && e.getUniversityFiscalYear().equals(t.getUniversityFiscalYear()) && e.getChartOfAccountsCode().equals(t.getChartOfAccountsCode()) && e.getAccountNumber().equals(t.getAccountNumber()) && e.getSubAccountNumber().equals(t.getSubAccountNumber()) && e.getObjectCode().equals(t.getFinancialObjectCode()) && e.getSubObjectCode().equals(t.getFinancialSubObjectCode()) && e.getBalanceTypeCode().equals(t.getFinancialBalanceTypeCode()) && e.getDocumentTypeCode().equals(t.getFinancialDocumentTypeCode()) && e.getOriginCode().equals(t.getFinancialSystemOriginationCode()) && e.getDocumentNumber().equals(t.getDocumentNumber())) { return e; } if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()) && e.getUniversityFiscalYear().equals(t.getUniversityFiscalYear()) && e.getChartOfAccountsCode().equals(t.getChartOfAccountsCode()) && e.getAccountNumber().equals(t.getAccountNumber()) && e.getSubAccountNumber().equals(t.getSubAccountNumber()) && e.getObjectCode().equals(t.getFinancialObjectCode()) && e.getSubObjectCode().equals(t.getFinancialSubObjectCode()) && e.getBalanceTypeCode().equals(t.getFinancialBalanceTypeCode()) && e.getDocumentTypeCode().equals(t.getReferenceFinancialDocumentTypeCode()) && e.getOriginCode().equals(t.getReferenceFinancialSystemOriginationCode()) && e.getDocumentNumber().equals(t.getReferenceFinancialDocumentNumber())) { return e; } } // If we couldn't find one that exists, create a new one // NOTE: the date doesn't matter so there is no need to call the date service // Changed to use the datetime service because of KULRNE-4183 Entry e = new Entry(t, dateTimeService.getCurrentDate()); if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) { e.setDocumentNumber(t.getReferenceFinancialDocumentNumber()); e.setFinancialSystemOriginationCode(t.getReferenceFinancialSystemOriginationCode()); e.setFinancialDocumentTypeCode(t.getReferenceFinancialDocumentTypeCode()); } Encumbrance enc = new Encumbrance(e); encumbranceList.add(enc); return enc; } /** * @param t * @param enc */ public void updateEncumbrance(Transaction t, Encumbrance enc) { if (KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) { // If using referring doc number, add or subtract transaction amount from // encumbrance closed amount if (KFSConstants.GL_DEBIT_CODE.equals(t.getTransactionDebitCreditCode())) { enc.setAccountLineEncumbranceClosedAmount(enc.getAccountLineEncumbranceClosedAmount().subtract(t.getTransactionLedgerEntryAmount())); } else { enc.setAccountLineEncumbranceClosedAmount(enc.getAccountLineEncumbranceClosedAmount().add(t.getTransactionLedgerEntryAmount())); } } else { // If not using referring doc number, add or subtract transaction amount from // encumbrance amount if (KFSConstants.GL_DEBIT_CODE.equals(t.getTransactionDebitCreditCode()) || KFSConstants.GL_BUDGET_CODE.equals(t.getTransactionDebitCreditCode())) { enc.setAccountLineEncumbranceAmount(enc.getAccountLineEncumbranceAmount().add(t.getTransactionLedgerEntryAmount())); } else { enc.setAccountLineEncumbranceAmount(enc.getAccountLineEncumbranceAmount().subtract(t.getTransactionLedgerEntryAmount())); } } } /** * @see org.kuali.kfs.gl.batch.service.PostTransaction#getDestinationName() */ public String getDestinationName() { return MetadataManager.getInstance().getGlobalRepository().getDescriptorFor(Encumbrance.class).getFullTableName(); } public void setDateTimeService(DateTimeService dateTimeService) { this.dateTimeService = dateTimeService; } }
update for error message
work/src/org/kuali/kfs/gl/batch/service/impl/PostEncumbrance.java
update for error message
<ide><path>ork/src/org/kuali/kfs/gl/batch/service/impl/PostEncumbrance.java <ide> import org.kuali.kfs.gl.businessobject.Transaction; <ide> import org.kuali.kfs.gl.dataaccess.EncumbranceDao; <ide> import org.kuali.kfs.sys.KFSConstants; <add>import org.kuali.kfs.sys.Message; <ide> import org.kuali.rice.kns.service.DateTimeService; <ide> import org.springframework.transaction.annotation.Transactional; <ide> <ide> * @param t the transaction to verify <ide> * @return a List of error messages, as Strings <ide> */ <del> public List verifyTransaction(Transaction t) { <add> public List<Message> verifyTransaction(Transaction t) { <ide> LOG.debug("verifyTransaction() started"); <ide> <del> List errors = new ArrayList(); <add> //TODO: Shawn - need to check with Jeff because there is no this method in FIS <add> List<Message> errors = new ArrayList(); <ide> <ide> // The encumbrance update code can only be space, N, R or D. Nothing else <ide> if ((StringUtils.isNotBlank(t.getTransactionEncumbranceUpdateCode())) && (!" ".equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_NO_ENCUMBRANCE_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_REFERENCE_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode())) && (!KFSConstants.ENCUMB_UPDT_DOCUMENT_CD.equals(t.getTransactionEncumbranceUpdateCode()))) { <del> errors.add("Invalid Encumbrance Update Code (" + t.getTransactionEncumbranceUpdateCode() + ")"); <add> errors.add(new Message("Invalid Encumbrance Update Code (" + t.getTransactionEncumbranceUpdateCode() + ")", Message.TYPE_FATAL)); <ide> } <ide> <ide> return errors;
Java
apache-2.0
8562915cffdc2540ce48b86c49e57da27de8bf9f
0
codeaudit/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,jeorme/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,nssales/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,ChinaQuants/OG-Platform
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.credit.underlyingpool.definition; import com.opengamma.analytics.financial.credit.CreditSpreadTenors; import com.opengamma.analytics.financial.credit.DebtSeniority; import com.opengamma.analytics.financial.credit.RestructuringClause; import com.opengamma.analytics.financial.credit.obligormodel.definition.Obligor; import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve; import com.opengamma.analytics.math.statistics.descriptive.MeanCalculator; import com.opengamma.analytics.math.statistics.descriptive.SampleSkewnessCalculator; import com.opengamma.analytics.math.statistics.descriptive.SampleStandardDeviationCalculator; import com.opengamma.analytics.math.statistics.descriptive.SampleVarianceCalculator; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * Class to specify the composition and characteristics of a 'pool' of obligors * In the credit index context the underlying pool is the set of obligors that constitute the index (e.g. CDX.NA.IG series 18) */ public class UnderlyingPool { // ---------------------------------------------------------------------------------------------------------------------------------------- // TODO : Work-in-Progress // TODO : Add the hashcode and equals methods // TODO : Add the arg checker for a null YieldCurve object (taken out for the purposes of testing) // TODO : Add an arg checker to ensure no two obligors are the same // TODO : Need to check the validity of the creditSpreadTenors and spreadTermStructures arguments // TODO : Will want to include calculations such as e.g. average T year spread of constituents and other descriptive statistics (std dev, var, skew, kurt, percentile) // NOTE : We input the individual obligor notionals as part of the underlying pool (the total pool notional is then calculated from this). // NOTE : e.g. suppose we have 100 names in the pool all equally weighted. If each obligor notional is $1mm then the total pool notional is $100mm // NOTE : Alternatively we can specify the total pool notional to be $100mm and then calculate by hand what the appropriate obligor notionals should be // ---------------------------------------------------------------------------------------------------------------------------------------- // A vector of obligors constituting the underlying pool private final Obligor[] _obligors; // The number of obligors in the underlying pool (usually 125 for CDX and iTraxx - although defaults can reduce this) private final int _numberOfObligors; // The currencies of the underlying obligors private final Currency[] _currency; // The seniority of the debt of the reference entities in the underlying pool private final DebtSeniority[] _debtSeniority; // The restructuring type in the event of a credit event deemed to be a restructuring of the reference entities debt private final RestructuringClause[] _restructuringClause; // Vector of tenors at which we have market observed par CDS spreads private final CreditSpreadTenors[] _creditSpreadTenors; // Matrix holding the term structure of market observed credit spreads (one term structure for each obligor in the underlying pool) private final double[][] _spreadTermStructures; // Vector holding the notional amounts of each obligor in the underlying pool private final double[] _obligorNotionals; // Vector holding the coupons to apply to the obligors in the underlying pool private final double[] _obligorCoupons; // Vector holding the recovery rates of the obligors in the underlying pool private final double[] _obligorRecoveryRates; // Vector holding the weights of the obligor in the underlying pool private final double[] _obligorWeights; // The yield curve objects (in principle each obligor can be in a different currency and therefore have a different discounting curve) private final YieldCurve[] _yieldCurve; // The total notional of all the obligors in the underlying pool private final double _poolNotional; // ---------------------------------------------------------------------------------------------------------------------------------------- // Ctor for the pool of obligor objects public UnderlyingPool( Obligor[] obligors, Currency[] currency, DebtSeniority[] debtSeniority, RestructuringClause[] restructuringClause, CreditSpreadTenors[] creditSpreadTenors, double[][] spreadTermStructures, double[] obligorNotionals, double[] obligorCoupons, double[] obligorRecoveryRates, double[] obligorWeights, YieldCurve[] yieldCurve) { // ---------------------------------------------------------------------------------------------------------------------------------------- // Check the validity of the input arguments ArgumentChecker.notNull(obligors, "Obligors"); ArgumentChecker.notNull(currency, "Currency"); ArgumentChecker.notNull(debtSeniority, "Debt Seniority"); ArgumentChecker.notNull(restructuringClause, "Restructuring Clause"); ArgumentChecker.notNull(creditSpreadTenors, "Credit spread tenors"); ArgumentChecker.notNull(spreadTermStructures, "Credit spread term structures"); ArgumentChecker.notNull(obligorCoupons, "Coupons"); ArgumentChecker.notNull(obligorRecoveryRates, "Recovery Rates"); ArgumentChecker.notNull(obligorWeights, "Obligor Weights"); //ArgumentChecker.notNull(yieldCurve, "Yield curve"); ArgumentChecker.isTrue(obligors.length == currency.length, "Number of obligors and number of obligor currencies should be equal"); ArgumentChecker.isTrue(obligors.length == debtSeniority.length, "Number of obligors and number of obligor debt seniorities should be equal"); ArgumentChecker.isTrue(obligors.length == restructuringClause.length, "Number of obligors and number of obligor restructuring clauses should be equal"); ArgumentChecker.isTrue(obligors.length == obligorCoupons.length, "Number of obligors and number of obligor coupons should be equal"); ArgumentChecker.isTrue(obligors.length == obligorRecoveryRates.length, "Number of obligors and number of obligor recovery rates should be equal"); ArgumentChecker.isTrue(obligors.length == obligorWeights.length, "Number of obligors and number of obligor weights should be equal"); ArgumentChecker.isTrue(obligors.length == yieldCurve.length, "Number of obligors and number of obligor yield curves should be equal"); double totalObligorWeightings = 0.0; for (int i = 0; i < obligorCoupons.length; i++) { ArgumentChecker.notNegative(obligorCoupons[i], "Coupons for obligor " + i); ArgumentChecker.notNegative(obligorRecoveryRates[i], "Recovery Rate for obligor " + i); ArgumentChecker.isTrue(obligorRecoveryRates[i] <= 1.0, "Recovery rate for obligor " + i + " should be less than or equal to 100%"); ArgumentChecker.notNegative(obligorWeights[i], "Index weighting for obligor " + i); ArgumentChecker.isTrue(obligorWeights[i] <= 1.0, "Index weighting for obligor " + i + " should be less than or equal to 100%"); totalObligorWeightings += obligorWeights[i]; } ArgumentChecker.isTrue(totalObligorWeightings == 1.0, "Index constituent weights must sum to unity"); // ---------------------------------------------------------------------------------------------------------------------------------------- _obligors = obligors; _numberOfObligors = obligors.length; _currency = currency; _debtSeniority = debtSeniority; _restructuringClause = restructuringClause; _creditSpreadTenors = creditSpreadTenors; _spreadTermStructures = spreadTermStructures; _obligorNotionals = obligorNotionals; _obligorCoupons = obligorCoupons; _obligorRecoveryRates = obligorRecoveryRates; _obligorWeights = obligorWeights; _yieldCurve = yieldCurve; // Calculate the total notional amount of the obligors in the pool double totalNotional = 0.0; for (int i = 0; i < _numberOfObligors; i++) { totalNotional += _obligorNotionals[i]; } _poolNotional = totalNotional; } // ---------------------------------------------------------------------------------------------------------------------------------------- public Obligor[] getObligors() { return _obligors; } public int getNumberOfObligors() { return _numberOfObligors; } public Currency[] getCurrency() { return _currency; } public DebtSeniority[] getDebtSeniority() { return _debtSeniority; } public RestructuringClause[] getRestructuringClause() { return _restructuringClause; } public CreditSpreadTenors[] getCreditSpreadTenors() { return _creditSpreadTenors; } public double[][] getSpreadTermStructures() { return _spreadTermStructures; } public double[] getObligorNotionals() { return _obligorNotionals; } public double[] getCoupons() { return _obligorCoupons; } public double[] getRecoveryRates() { return _obligorRecoveryRates; } public double[] getObligorWeights() { return _obligorWeights; } public YieldCurve[] getYieldCurves() { return _yieldCurve; } public double getPoolNotional() { return _poolNotional; } // ---------------------------------------------------------------------------------------------------------------------------------------- // Calculate the average spread of the obligors in the underlying pool for a given tenor public double calculateCreditSpreadAverage(CreditSpreadTenors creditSpreadTenor) { MeanCalculator mean = new MeanCalculator(); double[] spreads = getSpreads(creditSpreadTenor); return mean.evaluate(spreads); } // ---------------------------------------------------------------------------------------------------------------------------------------- // Calculate the variance of the spread of the obligors in the underlying pool for a given tenor public double calculateCreditSpreadVariance(CreditSpreadTenors creditSpreadTenor) { SampleVarianceCalculator variance = new SampleVarianceCalculator(); double[] spreads = getSpreads(creditSpreadTenor); return variance.evaluate(spreads); } // ---------------------------------------------------------------------------------------------------------------------------------------- // Calculate the standard deviation of the spread of the obligors in the underlying pool for a given tenor public double calculateCreditSpreadStandardDeviation(CreditSpreadTenors creditSpreadTenor) { SampleStandardDeviationCalculator standardDeviation = new SampleStandardDeviationCalculator(); double[] spreads = getSpreads(creditSpreadTenor); return standardDeviation.evaluate(spreads); } // ---------------------------------------------------------------------------------------------------------------------------------------- // Calculate the skewness of the spread of the obligors in the underlying pool for a given tenor public double calculateCreditSpreadSkewness(CreditSpreadTenors creditSpreadTenor) { SampleSkewnessCalculator skewness = new SampleSkewnessCalculator(); double[] spreads = getSpreads(creditSpreadTenor); return skewness.evaluate(spreads); } // ---------------------------------------------------------------------------------------------------------------------------------------- // fix // Calculate the skewness of the spread of the obligors in the underlying pool for a given tenor public double calculateCreditSpreadKurtosis(CreditSpreadTenors creditSpreadTenor) { SampleSkewnessCalculator skewness = new SampleSkewnessCalculator(); double[] spreads = getSpreads(creditSpreadTenor); return skewness.evaluate(spreads); } // ---------------------------------------------------------------------------------------------------------------------------------------- // Fix // Calculate the skewness of the spread of the obligors in the underlying pool for a given tenor public double calculateCreditSpreadPercentile(CreditSpreadTenors creditSpreadTenor, double q) { SampleSkewnessCalculator skewness = new SampleSkewnessCalculator(); double[] spreads = getSpreads(creditSpreadTenor); return skewness.evaluate(spreads); } // ---------------------------------------------------------------------------------------------------------------------------------------- private double[] getSpreads(CreditSpreadTenors creditSpreadTenor) { int counter = 0; double[] spreads = new double[this._numberOfObligors]; while (this.getCreditSpreadTenors()[counter] != creditSpreadTenor) { counter++; } for (int i = 0; i < this._numberOfObligors; i++) { spreads[i] = this.getSpreadTermStructures()[i][counter]; } return spreads; } // ---------------------------------------------------------------------------------------------------------------------------------------- }
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/credit/underlyingpool/definition/UnderlyingPool.java
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.credit.underlyingpool.definition; import com.opengamma.analytics.financial.credit.CreditSpreadTenors; import com.opengamma.analytics.financial.credit.DebtSeniority; import com.opengamma.analytics.financial.credit.RestructuringClause; import com.opengamma.analytics.financial.credit.obligormodel.definition.Obligor; import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * Class to specify the composition and characteristics of a 'pool' of obligors * In the credit index context the underlying pool is the set of obligors that constitute the index (e.g. CDX.NA.IG series 18) */ public class UnderlyingPool { // ---------------------------------------------------------------------------------------------------------------------------------------- // TODO : Work-in-Progress // TODO : Add the hashcode and equals methods // TODO : Add the arg checker for a null YieldCurve object (taken out for the purposes of testing) // TODO : Need to check the validity of the creditSpreadTenors and spreadTermStructures arguments // TODO : Will want to include calculations such as e.g. average T year spread of constituents and other descriptive statistics // NOTE : We input the individual obligor notionals as part of the underlying pool (the total pool notional is then calculated from this). // NOTE : e.g. suppose we have 100 names in the pool all equally weighted. If each obligor notional is $1mm then the total pool notional is $100mm // NOTE : Alternatively we can specify the total pool notional to be $100mm and then calculate by hand what the appropriate obligor notionals should be // ---------------------------------------------------------------------------------------------------------------------------------------- // A vector of obligors constituting the underlying pool private final Obligor[] _obligors; // The number of obligors in the underlying pool (usually 125 for CDX and iTraxx - although defaults can reduce this) private final int _numberOfObligors; // The currencies of the underlying obligors private final Currency[] _currency; // The seniority of the debt of the reference entities in the underlying pool private final DebtSeniority[] _debtSeniority; // The restructuring type in the event of a credit event deemed to be a restructuring of the reference entities debt private final RestructuringClause[] _restructuringClause; // Vector of tenors at which we have market observed par CDS spreads private final CreditSpreadTenors[] _creditSpreadTenors; // Matrix holding the term structure of market observed credit spreads (one term structure for each obligor in the underlying pool) private final double[][] _spreadTermStructures; // Vector holding the notional amounts of each obligor in the underlying pool private final double[] _obligorNotionals; // Vector holding the coupons to apply to the obligors in the underlying pool private final double[] _obligorCoupons; // Vector holding the recovery rates of the obligors in the underlying pool private final double[] _obligorRecoveryRates; // Vector holding the weights of the obligor in the underlying pool private final double[] _obligorWeights; // The yield curve objects (in principle each obligor can be in a different currency and therefore have a different discounting curve) private final YieldCurve[] _yieldCurve; // The total notional of all the obligors in the underlying pool private final double _poolNotional; // ---------------------------------------------------------------------------------------------------------------------------------------- // Ctor for the pool of obligor objects public UnderlyingPool( Obligor[] obligors, Currency[] currency, DebtSeniority[] debtSeniority, RestructuringClause[] restructuringClause, CreditSpreadTenors[] creditSpreadTenors, double[][] spreadTermStructures, double[] obligorNotionals, double[] obligorCoupons, double[] obligorRecoveryRates, double[] obligorWeights, YieldCurve[] yieldCurve) { // ---------------------------------------------------------------------------------------------------------------------------------------- // Check the validity of the input arguments ArgumentChecker.notNull(obligors, "Obligors"); ArgumentChecker.notNull(currency, "Currency"); ArgumentChecker.notNull(debtSeniority, "Debt Seniority"); ArgumentChecker.notNull(restructuringClause, "Restructuring Clause"); ArgumentChecker.notNull(creditSpreadTenors, "Credit spread tenors"); ArgumentChecker.notNull(spreadTermStructures, "Credit spread term structures"); ArgumentChecker.notNull(obligorCoupons, "Coupons"); ArgumentChecker.notNull(obligorRecoveryRates, "Recovery Rates"); ArgumentChecker.notNull(obligorWeights, "Obligor Weights"); //ArgumentChecker.notNull(yieldCurve, "Yield curve"); ArgumentChecker.isTrue(obligors.length == currency.length, "Number of obligors and number of obligor currencies should be equal"); ArgumentChecker.isTrue(obligors.length == debtSeniority.length, "Number of obligors and number of obligor debt seniorities should be equal"); ArgumentChecker.isTrue(obligors.length == restructuringClause.length, "Number of obligors and number of obligor restructuring clauses should be equal"); ArgumentChecker.isTrue(obligors.length == obligorCoupons.length, "Number of obligors and number of obligor coupons should be equal"); ArgumentChecker.isTrue(obligors.length == obligorRecoveryRates.length, "Number of obligors and number of obligor recovery rates should be equal"); ArgumentChecker.isTrue(obligors.length == obligorWeights.length, "Number of obligors and number of obligor weights should be equal"); ArgumentChecker.isTrue(obligors.length == yieldCurve.length, "Number of obligors and number of obligor yield curves should be equal"); double totalObligorWeightings = 0.0; for (int i = 0; i < obligorCoupons.length; i++) { ArgumentChecker.notNegative(obligorCoupons[i], "Coupons for obligor " + i); ArgumentChecker.notNegative(obligorRecoveryRates[i], "Recovery Rate for obligor " + i); ArgumentChecker.isTrue(obligorRecoveryRates[i] <= 1.0, "Recovery rate for obligor " + i + " should be less than or equal to 100%"); ArgumentChecker.notNegative(obligorWeights[i], "Index weighting for obligor " + i); ArgumentChecker.isTrue(obligorWeights[i] <= 1.0, "Index weighting for obligor " + i + " should be less than or equal to 100%"); totalObligorWeightings += obligorWeights[i]; } ArgumentChecker.isTrue(totalObligorWeightings == 1.0, "Index constituent weights must sum to unity"); // ---------------------------------------------------------------------------------------------------------------------------------------- _obligors = obligors; _numberOfObligors = obligors.length; _currency = currency; _debtSeniority = debtSeniority; _restructuringClause = restructuringClause; _creditSpreadTenors = creditSpreadTenors; _spreadTermStructures = spreadTermStructures; _obligorNotionals = obligorNotionals; _obligorCoupons = obligorCoupons; _obligorRecoveryRates = obligorRecoveryRates; _obligorWeights = obligorWeights; _yieldCurve = yieldCurve; // Calculate the total notional amount of the obligors in the pool double totalNotional = 0.0; for (int i = 0; i < _numberOfObligors; i++) { totalNotional += _obligorNotionals[i]; } _poolNotional = totalNotional; } // ---------------------------------------------------------------------------------------------------------------------------------------- public Obligor[] getObligors() { return _obligors; } public int getNumberOfObligors() { return _numberOfObligors; } public Currency[] getCurrency() { return _currency; } public DebtSeniority[] getDebtSeniority() { return _debtSeniority; } public RestructuringClause[] getRestructuringClause() { return _restructuringClause; } public CreditSpreadTenors[] getCreditSpreadTenors() { return _creditSpreadTenors; } public double[][] getSpreadTermStructures() { return _spreadTermStructures; } public double[] getObligorNotionals() { return _obligorNotionals; } public double[] getCoupons() { return _obligorCoupons; } public double[] getRecoveryRates() { return _obligorRecoveryRates; } public double[] getObligorWeights() { return _obligorWeights; } public YieldCurve[] getYieldCurves() { return _yieldCurve; } public double getPoolNotional() { return _poolNotional; } // ---------------------------------------------------------------------------------------------------------------------------------------- }
Added calculation of descriptive statistics for UnderlyinPool class e.g. average T year credit spread
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/credit/underlyingpool/definition/UnderlyingPool.java
Added calculation of descriptive statistics for UnderlyinPool class e.g. average T year credit spread
<ide><path>rojects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/credit/underlyingpool/definition/UnderlyingPool.java <ide> import com.opengamma.analytics.financial.credit.RestructuringClause; <ide> import com.opengamma.analytics.financial.credit.obligormodel.definition.Obligor; <ide> import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve; <add>import com.opengamma.analytics.math.statistics.descriptive.MeanCalculator; <add>import com.opengamma.analytics.math.statistics.descriptive.SampleSkewnessCalculator; <add>import com.opengamma.analytics.math.statistics.descriptive.SampleStandardDeviationCalculator; <add>import com.opengamma.analytics.math.statistics.descriptive.SampleVarianceCalculator; <ide> import com.opengamma.util.ArgumentChecker; <ide> import com.opengamma.util.money.Currency; <ide> <ide> <ide> // TODO : Add the hashcode and equals methods <ide> // TODO : Add the arg checker for a null YieldCurve object (taken out for the purposes of testing) <add> // TODO : Add an arg checker to ensure no two obligors are the same <ide> // TODO : Need to check the validity of the creditSpreadTenors and spreadTermStructures arguments <del> // TODO : Will want to include calculations such as e.g. average T year spread of constituents and other descriptive statistics <add> // TODO : Will want to include calculations such as e.g. average T year spread of constituents and other descriptive statistics (std dev, var, skew, kurt, percentile) <ide> <ide> // NOTE : We input the individual obligor notionals as part of the underlying pool (the total pool notional is then calculated from this). <ide> // NOTE : e.g. suppose we have 100 names in the pool all equally weighted. If each obligor notional is $1mm then the total pool notional is $100mm <ide> } <ide> <ide> // ---------------------------------------------------------------------------------------------------------------------------------------- <add> <add> // Calculate the average spread of the obligors in the underlying pool for a given tenor <add> public double calculateCreditSpreadAverage(CreditSpreadTenors creditSpreadTenor) { <add> <add> MeanCalculator mean = new MeanCalculator(); <add> <add> double[] spreads = getSpreads(creditSpreadTenor); <add> <add> return mean.evaluate(spreads); <add> } <add> <add> // ---------------------------------------------------------------------------------------------------------------------------------------- <add> <add> // Calculate the variance of the spread of the obligors in the underlying pool for a given tenor <add> public double calculateCreditSpreadVariance(CreditSpreadTenors creditSpreadTenor) { <add> <add> SampleVarianceCalculator variance = new SampleVarianceCalculator(); <add> <add> double[] spreads = getSpreads(creditSpreadTenor); <add> <add> return variance.evaluate(spreads); <add> } <add> <add> // ---------------------------------------------------------------------------------------------------------------------------------------- <add> <add> // Calculate the standard deviation of the spread of the obligors in the underlying pool for a given tenor <add> public double calculateCreditSpreadStandardDeviation(CreditSpreadTenors creditSpreadTenor) { <add> <add> SampleStandardDeviationCalculator standardDeviation = new SampleStandardDeviationCalculator(); <add> <add> double[] spreads = getSpreads(creditSpreadTenor); <add> <add> return standardDeviation.evaluate(spreads); <add> } <add> <add> // ---------------------------------------------------------------------------------------------------------------------------------------- <add> <add> // Calculate the skewness of the spread of the obligors in the underlying pool for a given tenor <add> public double calculateCreditSpreadSkewness(CreditSpreadTenors creditSpreadTenor) { <add> <add> SampleSkewnessCalculator skewness = new SampleSkewnessCalculator(); <add> <add> double[] spreads = getSpreads(creditSpreadTenor); <add> <add> return skewness.evaluate(spreads); <add> } <add> <add> // ---------------------------------------------------------------------------------------------------------------------------------------- <add> <add> // fix <add> // Calculate the skewness of the spread of the obligors in the underlying pool for a given tenor <add> public double calculateCreditSpreadKurtosis(CreditSpreadTenors creditSpreadTenor) { <add> <add> SampleSkewnessCalculator skewness = new SampleSkewnessCalculator(); <add> <add> double[] spreads = getSpreads(creditSpreadTenor); <add> <add> return skewness.evaluate(spreads); <add> } <add> <add> // ---------------------------------------------------------------------------------------------------------------------------------------- <add> <add> // Fix <add> // Calculate the skewness of the spread of the obligors in the underlying pool for a given tenor <add> public double calculateCreditSpreadPercentile(CreditSpreadTenors creditSpreadTenor, double q) { <add> <add> SampleSkewnessCalculator skewness = new SampleSkewnessCalculator(); <add> <add> double[] spreads = getSpreads(creditSpreadTenor); <add> <add> return skewness.evaluate(spreads); <add> } <add> <add> // ---------------------------------------------------------------------------------------------------------------------------------------- <add> <add> private double[] getSpreads(CreditSpreadTenors creditSpreadTenor) { <add> <add> int counter = 0; <add> <add> double[] spreads = new double[this._numberOfObligors]; <add> <add> while (this.getCreditSpreadTenors()[counter] != creditSpreadTenor) { <add> counter++; <add> } <add> <add> for (int i = 0; i < this._numberOfObligors; i++) { <add> spreads[i] = this.getSpreadTermStructures()[i][counter]; <add> } <add> <add> return spreads; <add> } <add> <add> // ---------------------------------------------------------------------------------------------------------------------------------------- <ide> }
Java
apache-2.0
7277785834de485ae6f4d2c2959f91055ce8d76f
0
hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak
package com.sequenceiq.it.cloudbreak.testcase.mock; import static com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.Status.AVAILABLE; import java.util.Collections; import javax.inject.Inject; import org.testng.annotations.Test; import com.sequenceiq.environment.api.v1.environment.model.response.EnvironmentStatus; import com.sequenceiq.it.cloudbreak.client.DistroXTestClient; import com.sequenceiq.it.cloudbreak.client.EnvironmentTestClient; import com.sequenceiq.it.cloudbreak.client.FreeIPATestClient; import com.sequenceiq.it.cloudbreak.client.SdxTestClient; import com.sequenceiq.it.cloudbreak.context.Description; import com.sequenceiq.it.cloudbreak.context.MockedTestContext; import com.sequenceiq.it.cloudbreak.context.RunningParameter; import com.sequenceiq.it.cloudbreak.context.TestContext; import com.sequenceiq.it.cloudbreak.dto.distrox.DistroXTestDto; import com.sequenceiq.it.cloudbreak.dto.environment.EnvironmentNetworkTestDto; import com.sequenceiq.it.cloudbreak.dto.environment.EnvironmentTestDto; import com.sequenceiq.it.cloudbreak.dto.freeipa.FreeIPATestDto; import com.sequenceiq.it.cloudbreak.dto.sdx.SdxInternalTestDto; import com.sequenceiq.it.cloudbreak.mock.freeipa.ServerConnCheckFreeipaRpcResponse; import com.sequenceiq.it.cloudbreak.testcase.AbstractIntegrationTest; import com.sequenceiq.sdx.api.model.SdxClusterStatusResponse; public class EnvironmentStartStopTest extends AbstractIntegrationTest { @Inject private EnvironmentTestClient environmentTestClient; @Inject private FreeIPATestClient freeIPATestClient; @Inject private SdxTestClient sdxTestClient; @Inject private DistroXTestClient distroXTestClient; @Override protected void setupTest(TestContext testContext) { createDefaultUser(testContext); createDefaultCredential(testContext); createDefaultImageCatalog(testContext); initializeDefaultBlueprints(testContext); } @Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running cloudbreak", when = "create an attached SDX and Datahub", then = "should be stopped first and started after it") public void testCreateStopStartEnvironment(TestContext testContext) { MockedTestContext mockedTestContext = (MockedTestContext) testContext; setUpFreeIpaRouteStubbing(mockedTestContext); testContext .given(EnvironmentNetworkTestDto.class) .given(EnvironmentTestDto.class).withNetwork().withCreateFreeIpa(false) .when(environmentTestClient.create()) .await(EnvironmentStatus.AVAILABLE) .given(FreeIPATestDto.class).withCatalog(mockedTestContext.getImageCatalogMockServerSetup().getFreeIpaImageCatalogUrl()) .when(freeIPATestClient.create()) .await(AVAILABLE) .given(SdxInternalTestDto.class) .when(sdxTestClient.createInternal()) .await(SdxClusterStatusResponse.RUNNING) .given("dx1", DistroXTestDto.class) .when(distroXTestClient.create(), RunningParameter.key("dx1")) .given("dx2", DistroXTestDto.class) .when(distroXTestClient.create(), RunningParameter.key("dx2")) .await(STACK_AVAILABLE, RunningParameter.key("dx1")) .await(STACK_AVAILABLE, RunningParameter.key("dx2")) .given(EnvironmentTestDto.class) .when(environmentTestClient.stop()) .await(EnvironmentStatus.ENV_STOPPED); getFreeIpaRouteHandler().updateResponse("server_conncheck", new ServerConnCheckFreeipaRpcResponse(false, Collections.emptyList())); testContext.given(EnvironmentTestDto.class) .when(environmentTestClient.start()) .await(EnvironmentStatus.AVAILABLE) .validate(); getFreeIpaRouteHandler().updateResponse("server_conncheck", new ServerConnCheckFreeipaRpcResponse()); } }
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/testcase/mock/EnvironmentStartStopTest.java
package com.sequenceiq.it.cloudbreak.testcase.mock; import static com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.Status.AVAILABLE; import java.util.Collections; import javax.inject.Inject; import org.testng.annotations.Test; import com.sequenceiq.environment.api.v1.environment.model.response.EnvironmentStatus; import com.sequenceiq.it.cloudbreak.client.DistroXTestClient; import com.sequenceiq.it.cloudbreak.client.EnvironmentTestClient; import com.sequenceiq.it.cloudbreak.client.FreeIPATestClient; import com.sequenceiq.it.cloudbreak.client.SdxTestClient; import com.sequenceiq.it.cloudbreak.context.Description; import com.sequenceiq.it.cloudbreak.context.MockedTestContext; import com.sequenceiq.it.cloudbreak.context.RunningParameter; import com.sequenceiq.it.cloudbreak.context.TestContext; import com.sequenceiq.it.cloudbreak.dto.distrox.DistroXTestDto; import com.sequenceiq.it.cloudbreak.dto.environment.EnvironmentNetworkTestDto; import com.sequenceiq.it.cloudbreak.dto.environment.EnvironmentTestDto; import com.sequenceiq.it.cloudbreak.dto.freeipa.FreeIPATestDto; import com.sequenceiq.it.cloudbreak.dto.sdx.SdxInternalTestDto; import com.sequenceiq.it.cloudbreak.mock.freeipa.ServerConnCheckFreeipaRpcResponse; import com.sequenceiq.it.cloudbreak.testcase.AbstractIntegrationTest; import com.sequenceiq.sdx.api.model.SdxClusterStatusResponse; public class EnvironmentStartStopTest extends AbstractIntegrationTest { @Inject private EnvironmentTestClient environmentTestClient; @Inject private FreeIPATestClient freeIPATestClient; @Inject private SdxTestClient sdxTestClient; @Inject private DistroXTestClient distroXTestClient; @Override protected void setupTest(TestContext testContext) { createDefaultUser(testContext); createDefaultCredential(testContext); createDefaultImageCatalog(testContext); initializeDefaultBlueprints(testContext); } @Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running cloudbreak", when = "create an attached SDX and Datahub", then = "should be stopped first and started after it") public void testCreateStopStartEnvironment(TestContext testContext) { MockedTestContext mockedTestContext = (MockedTestContext) testContext; setUpFreeIpaRouteStubbing(mockedTestContext); testContext .given(EnvironmentNetworkTestDto.class) .given(EnvironmentTestDto.class).withNetwork().withCreateFreeIpa(false) .when(environmentTestClient.create()) .await(EnvironmentStatus.AVAILABLE) .given(FreeIPATestDto.class).withCatalog(mockedTestContext.getImageCatalogMockServerSetup().getFreeIpaImageCatalogUrl()) .when(freeIPATestClient.create()) .await(AVAILABLE) .given(SdxInternalTestDto.class) .when(sdxTestClient.createInternal()) .await(SdxClusterStatusResponse.RUNNING) .given("dx1", DistroXTestDto.class) .when(distroXTestClient.create(), RunningParameter.key("dx1")) .given("dx2", DistroXTestDto.class) .when(distroXTestClient.create(), RunningParameter.key("dx2")) .await(STACK_AVAILABLE, RunningParameter.key("dx1")) .await(STACK_AVAILABLE, RunningParameter.key("dx2")) .given(EnvironmentTestDto.class) .when(environmentTestClient.stop()) .await(EnvironmentStatus.ENV_STOPPED); getFreeIpaRouteHandler().updateResponse("server_conncheck", new ServerConnCheckFreeipaRpcResponse(false, Collections.emptyList())); testContext.given(EnvironmentTestDto.class) .when(environmentTestClient.start()) .await(EnvironmentStatus.AVAILABLE) .validate(); } }
CB-4966 set freeipa response in it
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/testcase/mock/EnvironmentStartStopTest.java
CB-4966 set freeipa response in it
<ide><path>ntegration-test/src/main/java/com/sequenceiq/it/cloudbreak/testcase/mock/EnvironmentStartStopTest.java <ide> .when(environmentTestClient.start()) <ide> .await(EnvironmentStatus.AVAILABLE) <ide> .validate(); <add> getFreeIpaRouteHandler().updateResponse("server_conncheck", new ServerConnCheckFreeipaRpcResponse()); <ide> } <ide> }
Java
apache-2.0
090bdd0c56d1466586857d344dd41f65b5a01817
0
uoa-group-applications/hooks-its
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.hooks.workflow; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.server.data.AccountAttribute; import com.google.gerrit.server.events.*; import com.google.gwtorm.server.OrmException; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gerrit.server.config.SitePath; import com.google.gerrit.server.data.ApprovalAttribute; import com.google.gerrit.server.data.ChangeAttribute; import com.google.inject.Inject; import com.googlesource.gerrit.plugins.hooks.its.InvalidTransitionException; import com.googlesource.gerrit.plugins.hooks.its.ItsFacade; import com.googlesource.gerrit.plugins.hooks.util.IssueExtractor; public class GerritHookFilterChangeState extends GerritHookFilter { private static final Logger log = LoggerFactory .getLogger(GerritHookFilterChangeState.class); @Inject private ItsFacade its; @Inject @SitePath private File sitePath; @Inject private IssueExtractor issueExtractor; @Override public void doFilter(PatchSetCreatedEvent hook) throws IOException { log.info("status is " + hook.change.status.toString().toLowerCase()); performAction(hook.change, hook.uploader, new Condition("change", "created"), new Condition("status", hook.change.status.toString().toLowerCase())); } @Override public void doFilter(CommentAddedEvent hook) throws IOException { try { List<Condition> conditions = new ArrayList<Condition>(); conditions.add(new Condition("change", "commented")); if (hook.approvals != null) { for (ApprovalAttribute approval : hook.approvals) { addApprovalCategoryCondition(conditions, approval.type, approval.value); } } performAction(hook.change, hook.author, conditions.toArray(new Condition[conditions.size()])); } catch (InvalidTransitionException ex) { log.warn(ex.getMessage()); } } @Override public void doFilter(ReviewerAddedEvent hook) throws IOException, OrmException { performAction(hook.change, hook.reviewer, new Condition("change", "reviewer-added")); } @Override public void doFilter(ChangeMergedEvent hook) throws IOException { performAction(hook.change, hook.submitter, new Condition("change", "merged")); } @Override public void doFilter(ChangeAbandonedEvent hook) throws IOException { performAction(hook.change, hook.abandoner, new Condition("change", "abandoned")); } @Override public void doFilter(ChangeRestoredEvent hook) throws IOException { performAction(hook.change, hook.restorer, new Condition("change", "restored")); } private void addApprovalCategoryCondition(List<Condition> conditions, String name, String value) { value = toConditionValue(value); if (value == null) return; conditions.add(new Condition(name, value)); } private String toConditionValue(String text) { if (text == null) return null; try { int val = Integer.parseInt(text); if (val > 0) return "+" + val; else return text; } catch (Exception any) { return null; } } private void performAction(ChangeAttribute change, AccountAttribute author, Condition... conditionArgs) throws IOException { List<Condition> conditions = Arrays.asList(conditionArgs); log.debug("Checking suitable transition for: " + conditions); Transition transition = null; List<Transition> transitions = loadTransitions(); for (Transition tx : transitions) { log.debug("Checking transition: " + tx); if (tx.matches(conditions)) { log.debug("Transition FOUND > " + tx.getAction()); transition = tx; break; } } if (transition == null) { log.debug("Nothing to perform, transition not found for conditions " + conditions); return; } String gitComment = change.subject; String[] issues = issueExtractor.getIssueIds(gitComment); for (String issue : issues) { its.performAction(issue, author, transition.getAction()); } } private List<Transition> loadTransitions() { File configFile = new File(sitePath, "etc/issue-state-transition.config"); FileBasedConfig cfg = new FileBasedConfig(configFile, FS.DETECTED); try { cfg.load(); } catch (IOException e) { log.error("Cannot load transitions configuration file " + cfg, e); return Collections.emptyList(); } catch (ConfigInvalidException e) { log.error("Invalid transitions configuration file" + cfg, e); return Collections.emptyList(); } List<Transition> transitions = new ArrayList<Transition>(); Set<String> sections = cfg.getSubsections("action"); for (String section : sections) { List<Condition> conditions = new ArrayList<Condition>(); Set<String> keys = cfg.getNames("action", section); for (String key : keys) { String val = cfg.getString("action", section, key); conditions.add(new Condition(key.trim(), val.trim().split(","))); } transitions.add(new Transition(toAction(section), conditions)); } return transitions; } private String toAction(String name) { name = name.trim(); try { int i = name.lastIndexOf(' '); Integer.parseInt(name.substring(i + 1)); name = name.substring(0, i); } catch (Exception ignore) { } return name; } public class Condition { private String key; private String[] val; public Condition(String key, String[] values) { super(); this.key = key.toLowerCase(); this.val = values; } public Condition(String key, String value) { this(key, new String[] {value}); } public String getKey() { return key; } public String[] getVal() { return val; } @Override public boolean equals(Object o) { try { Condition other = (Condition) o; if (!(key.equals(other.key))) return false; boolean valMatch = false; List<String> otherVals = Arrays.asList(other.val); for (String value : val) { if (otherVals.contains(value)) valMatch = true; } return valMatch; } catch (Exception any) { return false; } } @Override public String toString() { return key + "=" + Arrays.asList(val); } } public class Transition { private String action; private List<Condition> conditions; public Transition(String action, List<Condition> conditions) { super(); this.action = action; this.conditions = conditions; } public String getAction() { return action; } public List<Condition> getCondition() { return conditions; } public boolean matches(List<Condition> eventConditions) { for (Condition condition : conditions) { if (!eventConditions.contains(condition)) return false; } return true; } @Override public String toString() { return "action=\"" + action + "\", conditions=" + conditions; } } }
hooks-its/src/main/java/com/googlesource/gerrit/plugins/hooks/workflow/GerritHookFilterChangeState.java
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.googlesource.gerrit.plugins.hooks.workflow; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import com.google.gerrit.server.data.AccountAttribute; import com.google.gerrit.server.events.*; import com.google.gwtorm.server.OrmException; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.util.FS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gerrit.server.config.SitePath; import com.google.gerrit.server.data.ApprovalAttribute; import com.google.gerrit.server.data.ChangeAttribute; import com.google.inject.Inject; import com.googlesource.gerrit.plugins.hooks.its.InvalidTransitionException; import com.googlesource.gerrit.plugins.hooks.its.ItsFacade; import com.googlesource.gerrit.plugins.hooks.util.IssueExtractor; public class GerritHookFilterChangeState extends GerritHookFilter { private static final Logger log = LoggerFactory .getLogger(GerritHookFilterChangeState.class); @Inject private ItsFacade its; @Inject @SitePath private File sitePath; @Inject private IssueExtractor issueExtractor; @Override public void doFilter(PatchSetCreatedEvent hook) throws IOException { performAction(hook.change, hook.uploader, new Condition("change", "created")); } @Override public void doFilter(CommentAddedEvent hook) throws IOException { try { List<Condition> conditions = new ArrayList<Condition>(); conditions.add(new Condition("change", "commented")); if (hook.approvals != null) { for (ApprovalAttribute approval : hook.approvals) { addApprovalCategoryCondition(conditions, approval.type, approval.value); } } performAction(hook.change, hook.author, conditions.toArray(new Condition[conditions.size()])); } catch (InvalidTransitionException ex) { log.warn(ex.getMessage()); } } @Override public void doFilter(ReviewerAddedEvent hook) throws IOException, OrmException { performAction(hook.change, hook.reviewer, new Condition("change", "reviewer-added")); } @Override public void doFilter(ChangeMergedEvent hook) throws IOException { performAction(hook.change, hook.submitter, new Condition("change", "merged")); } @Override public void doFilter(ChangeAbandonedEvent hook) throws IOException { performAction(hook.change, hook.abandoner, new Condition("change", "abandoned")); } @Override public void doFilter(ChangeRestoredEvent hook) throws IOException { performAction(hook.change, hook.restorer, new Condition("change", "restored")); } private void addApprovalCategoryCondition(List<Condition> conditions, String name, String value) { value = toConditionValue(value); if (value == null) return; conditions.add(new Condition(name, value)); } private String toConditionValue(String text) { if (text == null) return null; try { int val = Integer.parseInt(text); if (val > 0) return "+" + val; else return text; } catch (Exception any) { return null; } } private void performAction(ChangeAttribute change, AccountAttribute author, Condition... conditionArgs) throws IOException { List<Condition> conditions = Arrays.asList(conditionArgs); log.debug("Checking suitable transition for: " + conditions); Transition transition = null; List<Transition> transitions = loadTransitions(); for (Transition tx : transitions) { log.debug("Checking transition: " + tx); if (tx.matches(conditions)) { log.debug("Transition FOUND > " + tx.getAction()); transition = tx; break; } } if (transition == null) { log.debug("Nothing to perform, transition not found for conditions " + conditions); return; } String gitComment = change.subject; String[] issues = issueExtractor.getIssueIds(gitComment); for (String issue : issues) { its.performAction(issue, author, transition.getAction()); } } private List<Transition> loadTransitions() { File configFile = new File(sitePath, "etc/issue-state-transition.config"); FileBasedConfig cfg = new FileBasedConfig(configFile, FS.DETECTED); try { cfg.load(); } catch (IOException e) { log.error("Cannot load transitions configuration file " + cfg, e); return Collections.emptyList(); } catch (ConfigInvalidException e) { log.error("Invalid transitions configuration file" + cfg, e); return Collections.emptyList(); } List<Transition> transitions = new ArrayList<Transition>(); Set<String> sections = cfg.getSubsections("action"); for (String section : sections) { List<Condition> conditions = new ArrayList<Condition>(); Set<String> keys = cfg.getNames("action", section); for (String key : keys) { String val = cfg.getString("action", section, key); conditions.add(new Condition(key.trim(), val.trim().split(","))); } transitions.add(new Transition(toAction(section), conditions)); } return transitions; } private String toAction(String name) { name = name.trim(); try { int i = name.lastIndexOf(' '); Integer.parseInt(name.substring(i + 1)); name = name.substring(0, i); } catch (Exception ignore) { } return name; } public class Condition { private String key; private String[] val; public Condition(String key, String[] values) { super(); this.key = key.toLowerCase(); this.val = values; } public Condition(String key, String value) { this(key, new String[] {value}); } public String getKey() { return key; } public String[] getVal() { return val; } @Override public boolean equals(Object o) { try { Condition other = (Condition) o; if (!(key.equals(other.key))) return false; boolean valMatch = false; List<String> otherVals = Arrays.asList(other.val); for (String value : val) { if (otherVals.contains(value)) valMatch = true; } return valMatch; } catch (Exception any) { return false; } } @Override public String toString() { return key + "=" + Arrays.asList(val); } } public class Transition { private String action; private List<Condition> conditions; public Transition(String action, List<Condition> conditions) { super(); this.action = action; this.conditions = conditions; } public String getAction() { return action; } public List<Condition> getCondition() { return conditions; } public boolean matches(List<Condition> eventConditions) { for (Condition condition : conditions) { if (!eventConditions.contains(condition)) return false; } return true; } @Override public String toString() { return "action=\"" + action + "\", conditions=" + conditions; } } }
added support for changeset status (new, draft, etc)
hooks-its/src/main/java/com/googlesource/gerrit/plugins/hooks/workflow/GerritHookFilterChangeState.java
added support for changeset status (new, draft, etc)
<ide><path>ooks-its/src/main/java/com/googlesource/gerrit/plugins/hooks/workflow/GerritHookFilterChangeState.java <ide> import java.util.List; <ide> import java.util.Set; <ide> <add>import com.google.gerrit.reviewdb.client.Change; <ide> import com.google.gerrit.server.data.AccountAttribute; <ide> import com.google.gerrit.server.events.*; <ide> import com.google.gwtorm.server.OrmException; <ide> <ide> @Override <ide> public void doFilter(PatchSetCreatedEvent hook) throws IOException { <del> performAction(hook.change, hook.uploader, new Condition("change", "created")); <add> log.info("status is " + hook.change.status.toString().toLowerCase()); <add> <add> performAction(hook.change, hook.uploader, <add> new Condition("change", "created"), <add> new Condition("status", <add> hook.change.status.toString().toLowerCase())); <ide> } <ide> <ide> @Override
Java
apache-2.0
7f462bb89bb96bd9a8dc33a1fa1ca04fe27376de
0
samthor/intellij-community,Distrotech/intellij-community,kool79/intellij-community,diorcety/intellij-community,adedayo/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,signed/intellij-community,youdonghai/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,ernestp/consulo,asedunov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,ernestp/consulo,ryano144/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,semonte/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,xfournet/intellij-community,ibinti/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,signed/intellij-community,wreckJ/intellij-community,samthor/intellij-community,adedayo/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,blademainer/intellij-community,asedunov/intellij-community,jexp/idea2,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,kdwink/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,allotria/intellij-community,signed/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,dslomov/intellij-community,slisson/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,fnouama/intellij-community,slisson/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,signed/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,holmes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,ivan-fedorov/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,consulo/consulo,alphafoobar/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,semonte/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,clumsy/intellij-community,FHannes/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,fitermay/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,ryano144/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,Distrotech/intellij-community,slisson/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,fitermay/intellij-community,retomerz/intellij-community,holmes/intellij-community,nicolargo/intellij-community,jexp/idea2,suncycheng/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,da1z/intellij-community,clumsy/intellij-community,supersven/intellij-community,semonte/intellij-community,robovm/robovm-studio,signed/intellij-community,supersven/intellij-community,consulo/consulo,ibinti/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,kool79/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,supersven/intellij-community,kdwink/intellij-community,fnouama/intellij-community,signed/intellij-community,ibinti/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,consulo/consulo,tmpgit/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,joewalnes/idea-community,allotria/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,caot/intellij-community,asedunov/intellij-community,robovm/robovm-studio,izonder/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,signed/intellij-community,holmes/intellij-community,da1z/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,allotria/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,robovm/robovm-studio,slisson/intellij-community,semonte/intellij-community,jagguli/intellij-community,asedunov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,kool79/intellij-community,holmes/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,samthor/intellij-community,jexp/idea2,jagguli/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,consulo/consulo,lucafavatella/intellij-community,holmes/intellij-community,consulo/consulo,salguarnieri/intellij-community,petteyg/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,diorcety/intellij-community,FHannes/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,robovm/robovm-studio,xfournet/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,caot/intellij-community,supersven/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,blademainer/intellij-community,caot/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,allotria/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,izonder/intellij-community,samthor/intellij-community,clumsy/intellij-community,kool79/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ibinti/intellij-community,izonder/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ernestp/consulo,adedayo/intellij-community,ibinti/intellij-community,xfournet/intellij-community,hurricup/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,vvv1559/intellij-community,supersven/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,signed/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,kool79/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,samthor/intellij-community,kdwink/intellij-community,hurricup/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,allotria/intellij-community,retomerz/intellij-community,semonte/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,apixandru/intellij-community,caot/intellij-community,caot/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,kdwink/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,da1z/intellij-community,izonder/intellij-community,samthor/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,kdwink/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,diorcety/intellij-community,ernestp/consulo,signed/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,caot/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,hurricup/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,asedunov/intellij-community,apixandru/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,jexp/idea2,ol-loginov/intellij-community,kdwink/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,holmes/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,kool79/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,supersven/intellij-community,adedayo/intellij-community,signed/intellij-community,supersven/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,da1z/intellij-community,xfournet/intellij-community,slisson/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,supersven/intellij-community,asedunov/intellij-community,jexp/idea2,nicolargo/intellij-community,vladmm/intellij-community,clumsy/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,ryano144/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,ernestp/consulo,orekyuu/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,jagguli/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,caot/intellij-community,hurricup/intellij-community,fnouama/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,allotria/intellij-community,blademainer/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,xfournet/intellij-community,jexp/idea2,kool79/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,supersven/intellij-community,holmes/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,clumsy/intellij-community,robovm/robovm-studio,diorcety/intellij-community,fitermay/intellij-community,izonder/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,slisson/intellij-community,robovm/robovm-studio,adedayo/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,signed/intellij-community,FHannes/intellij-community,izonder/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,da1z/intellij-community,caot/intellij-community,petteyg/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,blademainer/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,jexp/idea2,fnouama/intellij-community,asedunov/intellij-community,hurricup/intellij-community,supersven/intellij-community,kool79/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,samthor/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,semonte/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,jexp/idea2,TangHao1987/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,hurricup/intellij-community,amith01994/intellij-community,xfournet/intellij-community,asedunov/intellij-community,holmes/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ernestp/consulo,xfournet/intellij-community,ibinti/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,izonder/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,da1z/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,vladmm/intellij-community,hurricup/intellij-community,petteyg/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,petteyg/intellij-community,apixandru/intellij-community,asedunov/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community
package com.theoryinpractice.testng.util; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.impl.source.jsp.jspJava.JspClass; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.util.PsiElementFilter; import com.intellij.psi.util.PsiTreeUtil; import com.theoryinpractice.testng.model.TestClassFilter; import org.testng.TestNG; import org.testng.annotations.*; /** * @author Hani Suleiman Date: Jul 20, 2005 Time: 1:37:36 PM */ public class TestNGUtil { private static final Logger LOGGER = Logger.getInstance("TestNG Runner"); private static final String TEST_ANNOTATION_FQN = Test.class.getName(); private static final String[] CONFIG_ANNOTATIONS_FQN = { Configuration.class.getName(), BeforeClass.class.getName(), BeforeGroups.class.getName(), BeforeMethod.class.getName(), BeforeSuite.class.getName(), BeforeTest.class.getName(), AfterClass.class.getName(), AfterGroups.class.getName(), AfterMethod.class.getName(), AfterSuite.class.getName(), AfterTest.class.getName() }; private static final String[] CONFIG_JAVADOC_TAGS = { "testng.configuration", "testng.before-class", "testng.before-groups", "testng.before-method", "testng.before-suite", "testng.before-test", "testng.after-class", "testng.after-groups", "testng.after-method", "testng.after-suite", "testng.after-test" }; public static PsiClass findPsiClass(String className, Module module, Project project, boolean global) { GlobalSearchScope scope; if (module != null) scope = global ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : GlobalSearchScope.moduleWithDependenciesScope(module); else scope = global ? GlobalSearchScope.allScope(project) : GlobalSearchScope.projectScope(project); return PsiManager.getInstance(project).findClass(className, scope); } public static PsiPackage getContainingPackage(PsiClass psiclass) { return psiclass.getContainingFile().getContainingDirectory().getPackage(); } public static boolean testNGExists(GlobalSearchScope globalsearchscope, Project project) { PsiClass found = PsiManager.getInstance(project).findClass(TestNG.class.getName(), globalsearchscope); return found != null; } public static boolean hasConfig(PsiModifierListOwner element) { PsiMethod[] methods; if (element instanceof PsiClass) { methods = ((PsiClass) element).getMethods(); } else { methods = new PsiMethod[] {(PsiMethod) element}; } for (PsiMethod method : methods) { for (String fqn : CONFIG_ANNOTATIONS_FQN) { if (AnnotationUtil.isAnnotated(method, fqn, false)) return true; } for (PsiElement child : method.getChildren()) { if (child instanceof PsiDocComment) { PsiDocComment doc = (PsiDocComment) child; for (String javadocTag : CONFIG_JAVADOC_TAGS) { if (doc.findTagByName(javadocTag) != null) return true; } } } } return false; } public static boolean hasTest(PsiModifierListOwner element) { //LanguageLevel effectiveLanguageLevel = element.getManager().getEffectiveLanguageLevel(); //boolean is15 = effectiveLanguageLevel != LanguageLevel.JDK_1_4 && effectiveLanguageLevel != LanguageLevel.JDK_1_3; boolean hasAnnotation = AnnotationUtil.isAnnotated(element, TEST_ANNOTATION_FQN, false); if (hasAnnotation) { PsiAnnotation annotation = AnnotationUtil.findAnnotation(element, TEST_ANNOTATION_FQN); PsiNameValuePair[] attribs = annotation.getParameterList().getAttributes(); for (PsiNameValuePair attrib : attribs) { if(attrib.getName().equals("enabled") && attrib.getValue().textMatches("false")) return false; } return true; } if (hasTestJavaDoc(element)) return true; //now we check all methods for the test annotation if (element instanceof PsiClass) { PsiClass psiClass = (PsiClass) element; for (PsiMethod method : psiClass.getAllMethods()) { if (AnnotationUtil.isAnnotated(method, TEST_ANNOTATION_FQN, false)) return true; if (hasTestJavaDoc(method)) return true; } } else if (element instanceof PsiMethod) { //if it's a method, we check if the class it's in has a global @Test annotation PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (AnnotationUtil.isAnnotated(psiClass, TEST_ANNOTATION_FQN, false)) { //even if it has a global test, we ignore private methods boolean isPrivate = element.getModifierList().hasModifierProperty(PsiModifier.PRIVATE); return !isPrivate; } if (hasTestJavaDoc(psiClass)) return true; } return false; } private static boolean hasTestJavaDoc(PsiElement element) { return getTextJavaDoc(element) != null; } private static PsiDocTag getTextJavaDoc(PsiElement element) { for (PsiElement child : element.getChildren()) { if (child instanceof PsiDocComment) { PsiDocComment doc = (PsiDocComment) child; PsiDocTag testTag = doc.findTagByName("testng.test"); if (testTag != null) return testTag; } } return null; } /** * Ignore these, they cause an NPE inside of AnnotationUtil */ private static boolean isBrokenPsiClass(PsiClass psiClass) { return (psiClass == null || psiClass instanceof PsiAnonymousClass || psiClass instanceof JspClass); } /** * Filter the specified collection of classes to return only ones that contain any of the specified values in the * specified annotation parameter. For example, this method can be used to return all classes that contain all tesng * annotations that are in the groups 'foo' or 'bar'. */ public static Map<PsiClass, Collection<PsiMethod>> filterAnnotations(String parameter, Set<String> values, PsiClass[] classes) { Map<PsiClass, Collection<PsiMethod>> results = new HashMap<PsiClass, Collection<PsiMethod>>(); Set<String> test = new HashSet<String>(1); test.add(TEST_ANNOTATION_FQN); test.addAll(Arrays.asList(CONFIG_ANNOTATIONS_FQN)); for (PsiClass psiClass : classes) { if (isBrokenPsiClass(psiClass)) continue; PsiAnnotation annotation; try { annotation = AnnotationUtil.findAnnotation(psiClass, test); } catch (Exception e) { LOGGER.error("Exception trying to findAnnotation on " + psiClass.getClass().getName() + ".\n\n" + e.getMessage()); annotation = null; } if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); OUTER: for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { Collection<String> matches = extractValuesFromParameter(aPair); //check if any matches are in our values for (String s : matches) { if (values.contains(s)) { results.put(psiClass, new HashSet<PsiMethod>()); break OUTER; } } } } } else { Collection<String> matches = extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter); for (String s : matches) { if (values.contains(s)) { results.put(psiClass, new HashSet<PsiMethod>()); break; } } } //we already have the class, no need to look through its methods PsiMethod[] methods = psiClass.getMethods(); for (PsiMethod method : methods) { if (method != null) { annotation = AnnotationUtil.findAnnotation(method, test); if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); OUTER: for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { Collection<String> matches = extractValuesFromParameter(aPair); for (String s : matches) { if (values.contains(s)) { if (results.get(psiClass) == null) results.put(psiClass, new HashSet<PsiMethod>()); results.get(psiClass).add(method); break OUTER; } } } } } else { Collection<String> matches = extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter); for (String s : matches) { if (values.contains(s)) { results.get(psiClass).add(method); } } } } } } return results; } public static Set<String> getAnnotationValues(String parameter, PsiClass... classes) { Set<String> results = new HashSet<String>(); Set<String> test = new HashSet<String>(1); test.add(TEST_ANNOTATION_FQN); test.addAll(Arrays.asList(CONFIG_ANNOTATIONS_FQN)); for (PsiClass psiClass : classes) { if (psiClass != null && hasTest(psiClass)) { PsiAnnotation annotation = AnnotationUtil.findAnnotation(psiClass, test); if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { results.addAll(extractValuesFromParameter(aPair)); } } } else { results.addAll(extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter)); } PsiMethod[] methods = psiClass.getMethods(); for (PsiMethod method : methods) { if (method != null) { annotation = AnnotationUtil.findAnnotation(method, test); if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { results.addAll(extractValuesFromParameter(aPair)); } } } else { results.addAll(extractAnnotationValuesFromJavaDoc(getTextJavaDoc(method), parameter)); } } } } } return results; } private static Collection<String> extractAnnotationValuesFromJavaDoc(PsiDocTag tag, String parameter) { if (tag == null) return Collections.emptyList(); Collection<String> results = new ArrayList<String>(); Matcher matcher = Pattern.compile("\\@testng.test(?:.*)" + parameter + "\\s*=\\s*\"(.*)\".*").matcher(tag.getText()); if (matcher.matches()) { String groupTag = matcher.group(1); String[] groups = groupTag.split("[,\\s]"); for (String group : groups) { results.add(group.trim()); } } return results; } private static Collection<String> extractValuesFromParameter(PsiNameValuePair aPair) { Collection<String> results = new ArrayList<String>(); PsiAnnotationMemberValue value = aPair.getValue(); if (value instanceof PsiArrayInitializerMemberValue) { for (PsiElement child : value.getChildren()) { if (child instanceof PsiLiteralExpression) { results.add((String) ((PsiLiteralExpression) child).getValue()); } } } else { if (value instanceof PsiLiteralExpression) { results.add((String) ((PsiLiteralExpression) value).getValue()); } } return results; } public static PsiClass[] getAllTestClasses(final TestClassFilter filter) { final PsiClass holder[][] = new PsiClass[1][]; ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); Collection<PsiClass> set = new HashSet<PsiClass>(); PsiManager manager = PsiManager.getInstance(filter.getProject()); PsiSearchHelper helper = manager.getSearchHelper(); GlobalSearchScope scope = filter.getScope(); GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject()); scope = projectScope.intersectWith(scope); PsiClass apsiclass[] = helper.findAllClasses(scope); for (PsiClass psiClass : apsiclass) { if (filter.isAccepted(psiClass)) { indicator.setText2("Found test class " + psiClass.getQualifiedName()); set.add(psiClass); } } holder[0] = set.toArray(new PsiClass[set.size()]); } }, "Searching For Tests...", true, filter.getProject()); return holder[0]; } public static PsiAnnotation[] getTestNGAnnotations(PsiElement element) { PsiElement[] annotations = PsiTreeUtil.collectElements(element, new PsiElementFilter() { public boolean isAccepted(PsiElement element) { if (!(element instanceof PsiAnnotation)) return false; String name = ((PsiAnnotation) element).getQualifiedName(); if (name.startsWith("org.testng.annotations")) { return true; } return false; } }); PsiAnnotation[] array = new PsiAnnotation[annotations.length]; System.arraycopy(annotations, 0, array, 0, annotations.length); return array; } }
plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java
package com.theoryinpractice.testng.util; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.impl.source.jsp.jspJava.JspClass; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.util.PsiElementFilter; import com.intellij.psi.util.PsiTreeUtil; import com.theoryinpractice.testng.model.TestClassFilter; import org.testng.TestNG; import org.testng.annotations.*; /** * @author Hani Suleiman Date: Jul 20, 2005 Time: 1:37:36 PM */ public class TestNGUtil { private static final Logger LOGGER = Logger.getInstance("TestNG Runner"); private static final String TEST_ANNOTATION_FQN = Test.class.getName(); private static final String[] CONFIG_ANNOTATIONS_FQN = { Configuration.class.getName(), BeforeClass.class.getName(), BeforeGroups.class.getName(), BeforeMethod.class.getName(), BeforeSuite.class.getName(), BeforeTest.class.getName(), AfterClass.class.getName(), AfterGroups.class.getName(), AfterMethod.class.getName(), AfterSuite.class.getName(), AfterTest.class.getName() }; private static final String[] CONFIG_JAVADOC_TAGS = { "testng.configuration", "testng.before-class", "testng.before-groups", "testng.before-method", "testng.before-suite", "testng.before-test", "testng.after-class", "testng.after-groups", "testng.after-method", "testng.after-suite", "testng.after-test" }; public static PsiClass findPsiClass(String className, Module module, Project project, boolean global) { GlobalSearchScope scope; if (module != null) scope = global ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : GlobalSearchScope.moduleWithDependenciesScope(module); else scope = global ? GlobalSearchScope.allScope(project) : GlobalSearchScope.projectScope(project); return PsiManager.getInstance(project).findClass(className, scope); } public static PsiPackage getContainingPackage(PsiClass psiclass) { return psiclass.getContainingFile().getContainingDirectory().getPackage(); } public static boolean testNGExists(GlobalSearchScope globalsearchscope, Project project) { PsiClass found = PsiManager.getInstance(project).findClass(TestNG.class.getName(), globalsearchscope); return found != null; } public static boolean hasConfig(PsiModifierListOwner element) { PsiMethod[] methods; if (element instanceof PsiClass) { methods = ((PsiClass) element).getMethods(); } else { methods = new PsiMethod[] {(PsiMethod) element}; } for (PsiMethod method : methods) { for (String fqn : CONFIG_ANNOTATIONS_FQN) { if (AnnotationUtil.isAnnotated(method, fqn, false)) return true; } for (PsiElement child : method.getChildren()) { if (child instanceof PsiDocComment) { PsiDocComment doc = (PsiDocComment) child; for (String javadocTag : CONFIG_JAVADOC_TAGS) { if (doc.findTagByName(javadocTag) != null) return true; } } } } return false; } public static boolean hasTest(PsiModifierListOwner element) { //LanguageLevel effectiveLanguageLevel = element.getManager().getEffectiveLanguageLevel(); //boolean is15 = effectiveLanguageLevel != LanguageLevel.JDK_1_4 && effectiveLanguageLevel != LanguageLevel.JDK_1_3; if (AnnotationUtil.isAnnotated(element, TEST_ANNOTATION_FQN, false)) return true; if (hasTestJavaDoc(element)) return true; //now we check all methods for the test annotation if (element instanceof PsiClass) { PsiClass psiClass = (PsiClass) element; for (PsiMethod method : psiClass.getAllMethods()) { if (AnnotationUtil.isAnnotated(method, TEST_ANNOTATION_FQN, false)) return true; if (hasTestJavaDoc(method)) return true; } } else if (element instanceof PsiMethod) { //if it's a method, we check if the class it's in has a global @Test annotation PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); if (AnnotationUtil.isAnnotated(psiClass, TEST_ANNOTATION_FQN, false)) return true; if (hasTestJavaDoc(psiClass)) return true; } return false; } private static boolean hasTestJavaDoc(PsiElement element) { return getTextJavaDoc(element) != null; } private static PsiDocTag getTextJavaDoc(PsiElement element) { for (PsiElement child : element.getChildren()) { if (child instanceof PsiDocComment) { PsiDocComment doc = (PsiDocComment) child; PsiDocTag testTag = doc.findTagByName("testng.test"); if (testTag != null) return testTag; } } return null; } /** * Ignore these, they cause an NPE inside of AnnotationUtil */ private static boolean isBrokenPsiClass(PsiClass psiClass) { return (psiClass == null || psiClass instanceof PsiAnonymousClass || psiClass instanceof JspClass); } /** * Filter the specified collection of classes to return only ones that contain any of the specified values in the * specified annotation parameter. For example, this method can be used to return all classes that contain all tesng * annotations that are in the groups 'foo' or 'bar'. */ public static Map<PsiClass, Collection<PsiMethod>> filterAnnotations(String parameter, Set<String> values, PsiClass[] classes) { Map<PsiClass, Collection<PsiMethod>> results = new HashMap<PsiClass, Collection<PsiMethod>>(); Set<String> test = new HashSet<String>(1); test.add(TEST_ANNOTATION_FQN); test.addAll(Arrays.asList(CONFIG_ANNOTATIONS_FQN)); for (PsiClass psiClass : classes) { if (isBrokenPsiClass(psiClass)) continue; PsiAnnotation annotation; try { annotation = AnnotationUtil.findAnnotation(psiClass, test); } catch (Exception e) { LOGGER.error("Exception trying to findAnnotation on " + psiClass.getClass().getName() + ".\n\n" + e.getMessage()); annotation = null; } if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); OUTER: for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { Collection<String> matches = extractValuesFromParameter(aPair); //check if any matches are in our values for (String s : matches) { if (values.contains(s)) { results.put(psiClass, new HashSet<PsiMethod>()); break OUTER; } } } } } else { Collection<String> matches = extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter); for (String s : matches) { if (values.contains(s)) { results.put(psiClass, new HashSet<PsiMethod>()); break; } } } //we already have the class, no need to look through its methods PsiMethod[] methods = psiClass.getMethods(); for (PsiMethod method : methods) { if (method != null) { annotation = AnnotationUtil.findAnnotation(method, test); if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); OUTER: for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { Collection<String> matches = extractValuesFromParameter(aPair); for (String s : matches) { if (values.contains(s)) { if (results.get(psiClass) == null) results.put(psiClass, new HashSet<PsiMethod>()); results.get(psiClass).add(method); break OUTER; } } } } } else { Collection<String> matches = extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter); for (String s : matches) { if (values.contains(s)) { results.get(psiClass).add(method); } } } } } } return results; } public static Set<String> getAnnotationValues(String parameter, PsiClass... classes) { Set<String> results = new HashSet<String>(); Set<String> test = new HashSet<String>(1); test.add(TEST_ANNOTATION_FQN); test.addAll(Arrays.asList(CONFIG_ANNOTATIONS_FQN)); for (PsiClass psiClass : classes) { if (psiClass != null && hasTest(psiClass)) { PsiAnnotation annotation = AnnotationUtil.findAnnotation(psiClass, test); if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { results.addAll(extractValuesFromParameter(aPair)); } } } else { results.addAll(extractAnnotationValuesFromJavaDoc(getTextJavaDoc(psiClass), parameter)); } PsiMethod[] methods = psiClass.getMethods(); for (PsiMethod method : methods) { if (method != null) { annotation = AnnotationUtil.findAnnotation(method, test); if (annotation != null) { PsiNameValuePair[] pair = annotation.getParameterList().getAttributes(); for (PsiNameValuePair aPair : pair) { if (parameter.equals(aPair.getName())) { results.addAll(extractValuesFromParameter(aPair)); } } } else { results.addAll(extractAnnotationValuesFromJavaDoc(getTextJavaDoc(method), parameter)); } } } } } return results; } private static Collection<String> extractAnnotationValuesFromJavaDoc(PsiDocTag tag, String parameter) { if (tag == null) return Collections.emptyList(); Collection<String> results = new ArrayList<String>(); Matcher matcher = Pattern.compile("\\@testng.test(?:.*)" + parameter + "\\s*=\\s*\"(.*)\".*").matcher(tag.getText()); if (matcher.matches()) { String groupTag = matcher.group(1); String[] groups = groupTag.split("[,\\s]"); for (String group : groups) { results.add(group.trim()); } } return results; } private static Collection<String> extractValuesFromParameter(PsiNameValuePair aPair) { Collection<String> results = new ArrayList<String>(); PsiAnnotationMemberValue value = aPair.getValue(); if (value instanceof PsiArrayInitializerMemberValue) { for (PsiElement child : value.getChildren()) { if (child instanceof PsiLiteralExpression) { results.add((String) ((PsiLiteralExpression) child).getValue()); } } } else { if (value instanceof PsiLiteralExpression) { results.add((String) ((PsiLiteralExpression) value).getValue()); } } return results; } public static PsiClass[] getAllTestClasses(final TestClassFilter filter) { final PsiClass holder[][] = new PsiClass[1][]; ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { public void run() { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); Collection<PsiClass> set = new HashSet<PsiClass>(); PsiManager manager = PsiManager.getInstance(filter.getProject()); PsiSearchHelper helper = manager.getSearchHelper(); GlobalSearchScope scope = filter.getScope(); GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject()); scope = projectScope.intersectWith(scope); PsiClass apsiclass[] = helper.findAllClasses(scope); for (PsiClass psiClass : apsiclass) { if (filter.isAccepted(psiClass)) { indicator.setText2("Found test class " + psiClass.getQualifiedName()); set.add(psiClass); } } holder[0] = set.toArray(new PsiClass[set.size()]); } }, "Searching For Tests...", true, filter.getProject()); return holder[0]; } public static PsiAnnotation[] getTestNGAnnotations(PsiElement element) { PsiElement[] annotations = PsiTreeUtil.collectElements(element, new PsiElementFilter() { public boolean isAccepted(PsiElement element) { if (!(element instanceof PsiAnnotation)) return false; String name = ((PsiAnnotation) element).getQualifiedName(); if (name.startsWith("org.testng.annotations")) { return true; } return false; } }); PsiAnnotation[] array = new PsiAnnotation[annotations.length]; System.arraycopy(annotations, 0, array, 0, annotations.length); return array; } }
Fix method popup if we have a class level @Test: Don't include private methods and don't include methods with @Test(enabled = false)
plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java
Fix method popup if we have a class level @Test: Don't include private methods and don't include methods with @Test(enabled = false)
<ide><path>lugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java <ide> public static boolean hasTest(PsiModifierListOwner element) { <ide> //LanguageLevel effectiveLanguageLevel = element.getManager().getEffectiveLanguageLevel(); <ide> //boolean is15 = effectiveLanguageLevel != LanguageLevel.JDK_1_4 && effectiveLanguageLevel != LanguageLevel.JDK_1_3; <del> if (AnnotationUtil.isAnnotated(element, TEST_ANNOTATION_FQN, false)) return true; <add> boolean hasAnnotation = AnnotationUtil.isAnnotated(element, TEST_ANNOTATION_FQN, false); <add> if (hasAnnotation) { <add> PsiAnnotation annotation = AnnotationUtil.findAnnotation(element, TEST_ANNOTATION_FQN); <add> PsiNameValuePair[] attribs = annotation.getParameterList().getAttributes(); <add> for (PsiNameValuePair attrib : attribs) { <add> if(attrib.getName().equals("enabled") && attrib.getValue().textMatches("false")) <add> return false; <add> } <add> return true; <add> } <ide> if (hasTestJavaDoc(element)) return true; <ide> //now we check all methods for the test annotation <ide> if (element instanceof PsiClass) { <ide> } else if (element instanceof PsiMethod) { <ide> //if it's a method, we check if the class it's in has a global @Test annotation <ide> PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class); <del> if (AnnotationUtil.isAnnotated(psiClass, TEST_ANNOTATION_FQN, false)) return true; <add> if (AnnotationUtil.isAnnotated(psiClass, TEST_ANNOTATION_FQN, false)) { <add> //even if it has a global test, we ignore private methods <add> boolean isPrivate = element.getModifierList().hasModifierProperty(PsiModifier.PRIVATE); <add> return !isPrivate; <add> } <ide> if (hasTestJavaDoc(psiClass)) return true; <ide> } <ide> return false;
Java
mit
cd2b89eb6b84e23f70859d5783f5f8c82e7eff5c
0
opentdc/users-service-opencrx
/** * The MIT License (MIT) * * Copyright (c) 2015 Arbalo AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opentdc.users.opencrx; import java.util.List; import java.util.logging.Logger; import javax.naming.NamingException; import javax.servlet.ServletContext; import org.openmdx.base.exception.ServiceException; import org.opentdc.opencrx.AbstractOpencrxServiceProvider; import org.opentdc.service.exception.*; import org.opentdc.users.ServiceProvider; import org.opentdc.users.UserModel; public class OpencrxServiceProvider extends AbstractOpencrxServiceProvider implements ServiceProvider { private static final Logger logger = Logger.getLogger(OpencrxServiceProvider.class.getName()); public OpencrxServiceProvider( ServletContext context, String prefix ) throws ServiceException, NamingException { super(context, prefix); } @Override public List<UserModel> list( String queryType, String query, long position, long size ) { // TODO Auto-generated method stub return null; } @Override public UserModel create( UserModel user) throws DuplicateException, ValidationException { // TODO Auto-generated method stub return null; } @Override public UserModel read( String id) throws NotFoundException { // TODO Auto-generated method stub return null; } @Override public UserModel update( String id, UserModel user) throws NotFoundException, ValidationException { // TODO Auto-generated method stub return null; } @Override public void delete( String id) throws NotFoundException, InternalServerErrorException { // TODO Auto-generated method stub } }
src/java/org/opentdc/users/opencrx/OpencrxServiceProvider.java
/** * The MIT License (MIT) * * Copyright (c) 2015 Arbalo AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.opentdc.users.opencrx; import java.util.List; import java.util.logging.Logger; import javax.naming.NamingException; import javax.servlet.ServletContext; import org.openmdx.base.exception.ServiceException; import org.opentdc.opencrx.AbstractOpencrxServiceProvider; import org.opentdc.service.exception.*; import org.opentdc.users.ServiceProvider; import org.opentdc.users.UserModel; public class OpencrxServiceProvider extends AbstractOpencrxServiceProvider implements ServiceProvider { private static final Logger logger = Logger.getLogger(OpencrxServiceProvider.class.getName()); public OpencrxServiceProvider( ServletContext context, String prefix ) throws ServiceException, NamingException { super(context, prefix); } @Override public List<UserModel> list( String queryType, String query, long position, long size ) { // TODO Auto-generated method stub return null; } @Override public UserModel create( UserModel user) throws DuplicateException, ValidationException { // TODO Auto-generated method stub return null; } @Override public UserModel read( String id) throws NotFoundException { // TODO Auto-generated method stub return null; } @Override public UserModel update( String id, UserModel user) throws NotFoundException, NotAllowedException { // TODO Auto-generated method stub return null; } @Override public void delete( String id) throws NotFoundException, InternalServerErrorException { // TODO Auto-generated method stub } }
switched from NotAllowedException to ValidationException (on client-side: BAD_REQUEST/400)
src/java/org/opentdc/users/opencrx/OpencrxServiceProvider.java
switched from NotAllowedException to ValidationException (on client-side: BAD_REQUEST/400)
<ide><path>rc/java/org/opentdc/users/opencrx/OpencrxServiceProvider.java <ide> public UserModel update( <ide> String id, <ide> UserModel user) <del> throws NotFoundException, NotAllowedException { <add> throws NotFoundException, ValidationException { <ide> // TODO Auto-generated method stub <ide> return null; <ide> }
Java
apache-2.0
ff275ac9fb0ddba7f45d20db0ac7976aa0c26c42
0
ieb/sling,awadheshv/sling,mmanski/sling,wimsymons/sling,anchela/sling,ieb/sling,headwirecom/sling,mcdan/sling,labertasch/sling,mmanski/sling,cleliameneghin/sling,roele/sling,Nimco/sling,trekawek/sling,roele/sling,vladbailescu/sling,awadheshv/sling,Nimco/sling,tyge68/sling,Nimco/sling,cleliameneghin/sling,ieb/sling,trekawek/sling,tteofili/sling,vladbailescu/sling,tyge68/sling,cleliameneghin/sling,headwirecom/sling,ist-dresden/sling,tyge68/sling,ist-dresden/sling,anchela/sling,trekawek/sling,trekawek/sling,tyge68/sling,cleliameneghin/sling,wimsymons/sling,wimsymons/sling,awadheshv/sling,JEBailey/sling,trekawek/sling,ist-dresden/sling,mikibrv/sling,JEBailey/sling,mikibrv/sling,anchela/sling,mikibrv/sling,tteofili/sling,awadheshv/sling,mcdan/sling,cleliameneghin/sling,mcdan/sling,vladbailescu/sling,trekawek/sling,mcdan/sling,wimsymons/sling,tmaret/sling,tteofili/sling,anchela/sling,mikibrv/sling,ist-dresden/sling,labertasch/sling,roele/sling,JEBailey/sling,ist-dresden/sling,mmanski/sling,headwirecom/sling,anchela/sling,Nimco/sling,mcdan/sling,awadheshv/sling,tmaret/sling,tyge68/sling,ieb/sling,mmanski/sling,tmaret/sling,roele/sling,headwirecom/sling,vladbailescu/sling,tteofili/sling,labertasch/sling,roele/sling,tmaret/sling,awadheshv/sling,Nimco/sling,ieb/sling,tyge68/sling,Nimco/sling,labertasch/sling,tteofili/sling,mmanski/sling,headwirecom/sling,JEBailey/sling,vladbailescu/sling,mmanski/sling,labertasch/sling,wimsymons/sling,tteofili/sling,mcdan/sling,tmaret/sling,mikibrv/sling,JEBailey/sling,ieb/sling,wimsymons/sling,mikibrv/sling
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.launchpad.webapp.integrationtest.servlets.post; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.sling.commons.testing.integration.HttpTestBase; import org.apache.sling.servlets.post.SlingPostConstants; /** Test switching the output content-type of the POST servlet using * either an Accept header or :http-equiv-accept parameter */ public class PostServletOutputContentTypeTest extends HttpTestBase { private final String MY_TEST_PATH = TEST_PATH + "/" + getClass().getSimpleName() + "/" + System.currentTimeMillis(); private void runTest(String acceptHeaderValue, boolean useHttpEquiv, String expectedContentType) throws Exception { final String info = (useHttpEquiv ? "Using http-equiv parameter" : "Using Accept header") + ": "; final String url = HTTP_BASE_URL + MY_TEST_PATH; final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); if(acceptHeaderValue != null) { if(useHttpEquiv) { post.addParameter(":http-equiv-accept", acceptHeaderValue); } else { post.addRequestHeader("Accept", acceptHeaderValue); } } final int status = httpClient.executeMethod(post) / 100; assertEquals(info + "Expected status 20x for POST at " + url, 2, status); final Header h = post.getResponseHeader("Content-Type"); assertNotNull(info + "Expected Content-Type header", h); final String ct = h.getValue(); assertTrue(info + "Expected Content-Type '" + expectedContentType + "' for Accept header=" + acceptHeaderValue + " but got '" + ct + "'", ct.startsWith(expectedContentType)); } public void runTest(String acceptHeaderValue, String expectedContentType) throws Exception { runTest(acceptHeaderValue, false, expectedContentType); runTest(acceptHeaderValue, true, expectedContentType); } public void testDefaultContentType() throws Exception { runTest(null, CONTENT_TYPE_HTML); } public void testJsonContentType() throws Exception { runTest("application/json,*/*;q=0.9", CONTENT_TYPE_JSON); } public void testHtmlContentType() throws Exception { runTest("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", CONTENT_TYPE_HTML); } public void testHtmlContentTypeWithQ() throws Exception { runTest("text/plain; q=0.5, text/html,application/xhtml+xml,application/xml;q=0.9, application/json;q=0.8", CONTENT_TYPE_HTML); } public void testJsonContentTypeWithQ() throws Exception { runTest("text/plain; q=0.5, text/html; q=0.8, application/json; q=0.9", CONTENT_TYPE_JSON); } public void testJsonContentTypeException() throws Exception { // Perform a POST that fails: invalid PostServlet operation // with Accept header set to JSON final String url = HTTP_BASE_URL + MY_TEST_PATH; final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); post.addParameter(new NameValuePair( SlingPostConstants.RP_OPERATION, "InvalidTestOperationFor" + getClass().getSimpleName())); post.addRequestHeader("Accept", CONTENT_TYPE_JSON); final int status = httpClient.executeMethod(post); assertEquals(500, status); final String contentType = post.getResponseHeader("Content-Type").getValue(); final String expected = CONTENT_TYPE_JSON; assertTrue("Expecting content-type " + expected + " for failed POST request, got " + contentType, contentType!=null && contentType.startsWith(expected)); } }
launchpad/integration-tests/src/main/java/org/apache/sling/launchpad/webapp/integrationtest/servlets/post/PostServletOutputContentTypeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.launchpad.webapp.integrationtest.servlets.post; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.sling.commons.testing.integration.HttpTestBase; import org.apache.sling.servlets.post.SlingPostConstants; /** Test switching the output content-type of the POST servlet using * either an Accept header or :http-equiv-accept parameter */ public class PostServletOutputContentTypeTest extends HttpTestBase { private final String MY_TEST_PATH = TEST_PATH + "/" + getClass().getSimpleName() + "/" + System.currentTimeMillis(); private void runTest(String acceptHeaderValue, boolean useHttpEquiv, String expectedContentType) throws Exception { final String info = (useHttpEquiv ? "Using http-equiv parameter" : "Using Accept header") + ": "; final String url = HTTP_BASE_URL + MY_TEST_PATH; final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); if(acceptHeaderValue != null) { if(useHttpEquiv) { post.addParameter(":http-equiv-accept", acceptHeaderValue); } else { post.addRequestHeader("Accept", acceptHeaderValue); } } final int status = httpClient.executeMethod(post) / 100; assertEquals(info + "Expected status 20x for POST at " + url, 2, status); final Header h = post.getResponseHeader("Content-Type"); assertNotNull(info + "Expected Content-Type header", h); final String ct = h.getValue(); assertTrue(info + "Expected Content-Type '" + expectedContentType + "' for Accept header=" + acceptHeaderValue + " but got '" + ct + "'", ct.startsWith(expectedContentType)); } public void runTest(String acceptHeaderValue, String expectedContentType) throws Exception { runTest(acceptHeaderValue, false, expectedContentType); runTest(acceptHeaderValue, true, expectedContentType); } public void testDefaultContentType() throws Exception { runTest(null, CONTENT_TYPE_HTML); } public void testJsonContentType() throws Exception { runTest("application/json,*/*;q=0.9", CONTENT_TYPE_JSON); } public void testHtmlContentType() throws Exception { runTest("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", CONTENT_TYPE_HTML); } public void testHtmlContentTypeWithQ() throws Exception { runTest("text/plain; q=0.5, text/html,application/xhtml+xml,application/xml;q=0.9, application/json;q=0.8", CONTENT_TYPE_HTML); } public void testJsonContentTypeWithQ() throws Exception { runTest("text/plain; q=0.5, text/html; q=0.8, application/json; q=0.9", CONTENT_TYPE_JSON); } public void testJsonContentTypeException() throws Exception { // Perform a POST that fails: invalid PostServlet operation // with Accept header set to JSON final String url = HTTP_BASE_URL + "/" + MY_TEST_PATH; final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); post.addParameter(new NameValuePair( SlingPostConstants.RP_OPERATION, "InvalidTestOperationFor" + getClass().getSimpleName())); post.addRequestHeader("Accept", CONTENT_TYPE_JSON); final int status = httpClient.executeMethod(post); assertEquals(500, status); final String contentType = post.getResponseHeader("Content-Type").getValue(); final String expected = CONTENT_TYPE_JSON; assertTrue("Expecting content-type " + expected + " for failed POST request, got " + contentType, contentType!=null && contentType.startsWith(expected)); } }
SLING-5463 - that bug exposed another bug in this test...fixed. git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1727949 13f79535-47bb-0310-9956-ffa450edef68
launchpad/integration-tests/src/main/java/org/apache/sling/launchpad/webapp/integrationtest/servlets/post/PostServletOutputContentTypeTest.java
SLING-5463 - that bug exposed another bug in this test...fixed.
<ide><path>aunchpad/integration-tests/src/main/java/org/apache/sling/launchpad/webapp/integrationtest/servlets/post/PostServletOutputContentTypeTest.java <ide> <ide> // Perform a POST that fails: invalid PostServlet operation <ide> // with Accept header set to JSON <del> final String url = HTTP_BASE_URL + "/" + MY_TEST_PATH; <add> final String url = HTTP_BASE_URL + MY_TEST_PATH; <ide> final PostMethod post = new PostMethod(url); <ide> post.setFollowRedirects(false); <ide> post.addParameter(new NameValuePair(
Java
bsd-3-clause
055c70b4552724bcc7c8ed88234825d780c98a66
0
bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,arurke/contiki,arurke/contiki,arurke/contiki,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,MohamedSeliem/contiki,bluerover/6lbr,arurke/contiki,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,bluerover/6lbr,arurke/contiki,arurke/contiki
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.contikios.cooja; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyVetoException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessControlException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Properties; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultDesktopManager; import javax.swing.InputMap; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileFilter; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.contikios.cooja.MoteType.MoteTypeCreationException; import org.contikios.cooja.VisPlugin.PluginRequiresVisualizationException; import org.contikios.cooja.contikimote.ContikiMoteType; import org.contikios.cooja.dialogs.AddMoteDialog; import org.contikios.cooja.dialogs.BufferSettings; import org.contikios.cooja.dialogs.ConfigurationWizard; import org.contikios.cooja.dialogs.CreateSimDialog; import org.contikios.cooja.dialogs.ExternalToolsDialog; import org.contikios.cooja.dialogs.MessageList; import org.contikios.cooja.dialogs.ProjectDirectoriesDialog; import org.contikios.cooja.plugins.MoteTypeInformation; import org.contikios.cooja.plugins.ScriptRunner; import org.contikios.cooja.plugins.SimControl; import org.contikios.cooja.plugins.SimInformation; import org.contikios.cooja.util.ExecuteJAR; /** * Main file of COOJA Simulator. Typically contains a visualizer for the * simulator, but can also be started without visualizer. * * This class loads external Java classes (in extension directories), and handles the * COOJA plugins as well as the configuration system. If provides a number of * help methods for the rest of the COOJA system, and is the starting point for * loading and saving simulation configs. * * @author Fredrik Osterlind */ public class Cooja extends Observable { private static JFrame frame = null; private static JApplet applet = null; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(Cooja.class); /** * External tools configuration. */ public static final String EXTERNAL_TOOLS_SETTINGS_FILENAME = "/external_tools.config"; /** * External tools default Win32 settings filename. */ public static final String EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME = "/external_tools_win32.config"; /** * External tools default Mac OS X settings filename. */ public static final String EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME = "/external_tools_macosx.config"; /** * External tools default FreeBSD settings filename. */ public static final String EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME = "/external_tools_freebsd.config"; /** * External tools default Linux/Unix settings filename. */ public static final String EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME = "/external_tools_linux.config"; /** * External tools default Linux/Unix settings filename for 64 bit architectures. * Tested on Intel 64-bit Gentoo Linux. */ public static final String EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME = "/external_tools_linux_64.config"; /** * External tools user settings filename. */ public static final String EXTERNAL_TOOLS_USER_SETTINGS_FILENAME = ".cooja.user.properties"; public static File externalToolsUserSettingsFile; private static boolean externalToolsUserSettingsFileReadOnly = false; private static String specifiedContikiPath = null; /** * Logger settings filename. */ public static final String LOG_CONFIG_FILE = "log4j_config.xml"; /** * Default extension configuration filename. */ public static String PROJECT_DEFAULT_CONFIG_FILENAME = null; /** * User extension configuration filename. */ public static final String PROJECT_CONFIG_FILENAME = "cooja.config"; /** * File filter only showing saved simulations files (*.csc). */ public static final FileFilter SAVED_SIMULATIONS_FILES = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".csc")) { return true; } if (file.getName().endsWith(".csc.gz")) { return true; } return false; } public String getDescription() { return "Cooja simulation (.csc, .csc.gz)"; } public String toString() { return ".csc"; } }; // External tools setting names public static Properties defaultExternalToolsSettings; public static Properties currentExternalToolsSettings; private static final String externalToolsSettingNames[] = new String[] { "PATH_CONTIKI", "PATH_COOJA_CORE_RELATIVE","PATH_COOJA","PATH_APPS", "PATH_APPSEARCH", "PATH_MAKE", "PATH_SHELL", "PATH_C_COMPILER", "COMPILER_ARGS", "PATH_LINKER", "LINK_COMMAND_1", "LINK_COMMAND_2", "PATH_AR", "AR_COMMAND_1", "AR_COMMAND_2", "PATH_OBJDUMP", "OBJDUMP_ARGS", "PATH_OBJCOPY", "PATH_JAVAC", "CONTIKI_STANDARD_PROCESSES", "CMD_GREP_PROCESSES", "REGEXP_PARSE_PROCESSES", "CMD_GREP_INTERFACES", "REGEXP_PARSE_INTERFACES", "CMD_GREP_SENSORS", "REGEXP_PARSE_SENSORS", "DEFAULT_PROJECTDIRS", "CORECOMM_TEMPLATE_FILENAME", "PARSE_WITH_COMMAND", "MAPFILE_DATA_START", "MAPFILE_DATA_SIZE", "MAPFILE_BSS_START", "MAPFILE_BSS_SIZE", "MAPFILE_COMMON_START", "MAPFILE_COMMON_SIZE", "MAPFILE_VAR_NAME", "MAPFILE_VAR_ADDRESS_1", "MAPFILE_VAR_ADDRESS_2", "MAPFILE_VAR_SIZE_1", "MAPFILE_VAR_SIZE_2", "PARSE_COMMAND", "COMMAND_VAR_NAME_ADDRESS", "COMMAND_DATA_START", "COMMAND_DATA_END", "COMMAND_BSS_START", "COMMAND_BSS_END", "COMMAND_COMMON_START", "COMMAND_COMMON_END", "HIDE_WARNINGS" }; private static final int FRAME_NEW_OFFSET = 30; private static final int FRAME_STANDARD_WIDTH = 150; private static final int FRAME_STANDARD_HEIGHT = 300; private static final String WINDOW_TITLE = "Cooja: The Contiki Network Simulator"; private Cooja cooja; private Simulation mySimulation; protected GUIEventHandler guiEventHandler = new GUIEventHandler(); private JMenu menuMoteTypeClasses, menuMoteTypes; private JMenu menuOpenSimulation; private boolean hasFileHistoryChanged; private Vector<Class<? extends Plugin>> menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); private JDesktopPane myDesktopPane; private Vector<Plugin> startedPlugins = new Vector<Plugin>(); private ArrayList<GUIAction> guiActions = new ArrayList<GUIAction>(); // Platform configuration variables // Maintained via method reparseProjectConfig() private ProjectConfig projectConfig; private ArrayList<COOJAProject> currentProjects = new ArrayList<COOJAProject>(); public ClassLoader projectDirClassLoader; private Vector<Class<? extends MoteType>> moteTypeClasses = new Vector<Class<? extends MoteType>>(); private Vector<Class<? extends Plugin>> pluginClasses = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends RadioMedium>> radioMediumClasses = new Vector<Class<? extends RadioMedium>>(); private Vector<Class<? extends Positioner>> positionerClasses = new Vector<Class<? extends Positioner>>(); private class HighlightObservable extends Observable { private void setChangedAndNotify(Mote mote) { setChanged(); notifyObservers(mote); } } private HighlightObservable moteHighlightObservable = new HighlightObservable(); private class MoteRelationsObservable extends Observable { private void setChangedAndNotify() { setChanged(); notifyObservers(); } } private MoteRelationsObservable moteRelationObservable = new MoteRelationsObservable(); private JTextPane quickHelpTextPane; private JScrollPane quickHelpScroll; private Properties quickHelpProperties = null; /* quickhelp.txt */ /** * Mote relation (directed). */ public static class MoteRelation { public Mote source; public Mote dest; public Color color; public MoteRelation(Mote source, Mote dest, Color color) { this.source = source; this.dest = dest; this.color = color; } } private ArrayList<MoteRelation> moteRelations = new ArrayList<MoteRelation>(); /** * Creates a new COOJA Simulator GUI. * * @param desktop Desktop pane */ public Cooja(JDesktopPane desktop) { cooja = this; mySimulation = null; myDesktopPane = desktop; /* Help panel */ quickHelpTextPane = new JTextPane(); quickHelpTextPane.setContentType("text/html"); quickHelpTextPane.setEditable(false); quickHelpTextPane.setVisible(false); quickHelpScroll = new JScrollPane(quickHelpTextPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); quickHelpScroll.setPreferredSize(new Dimension(200, 0)); quickHelpScroll.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(0, 3, 0, 0) )); quickHelpScroll.setVisible(false); loadQuickHelp("GETTING_STARTED"); // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); final boolean showQuickhelp = getExternalToolsSetting("SHOW_QUICKHELP", "true").equalsIgnoreCase("true"); if (showQuickhelp) { SwingUtilities.invokeLater(new Runnable() { public void run() { JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } }); } /* Debugging - Break on repaints outside EDT */ /*RepaintManager.setCurrentManager(new RepaintManager() { public void addDirtyRegion(JComponent comp, int a, int b, int c, int d) { if(!java.awt.EventQueue.isDispatchThread()) { throw new RuntimeException("Repainting outside EDT"); } super.addDirtyRegion(comp, a, b, c, d); } });*/ // Register default extension directories String defaultProjectDirs = getExternalToolsSetting("DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null && defaultProjectDirs.length() > 0) { String[] arr = defaultProjectDirs.split(";"); for (String p : arr) { File projectDir = restorePortablePath(new File(p)); currentProjects.add(new COOJAProject(projectDir)); } } //Scan for projects String searchProjectDirs = getExternalToolsSetting("PATH_APPSEARCH", null); if (searchProjectDirs != null && searchProjectDirs.length() > 0) { String[] arr = searchProjectDirs.split(";"); for (String d : arr) { File searchDir = restorePortablePath(new File(d)); File[] projects = COOJAProject.sarchProjects(searchDir, 3); if(projects == null) continue; for(File p : projects){ currentProjects.add(new COOJAProject(p)); } } } /* Parse current extension configuration */ try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading extensions: " + e.getMessage(), e); if (isVisualized()) { JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), "All Cooja extensions could not load.\n\n" + "To manage Cooja extensions:\n" + "Menu->Settings->Cooja extensions", "Reconfigure Cooja extensions", JOptionPane.INFORMATION_MESSAGE); showErrorDialog(getTopParentContainer(), "Cooja extensions load error", e, false); } } // Start all standard GUI plugins for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, null, null); } } } /** * Add mote highlight observer. * * @see #deleteMoteHighlightObserver(Observer) * @param newObserver * New observer */ public void addMoteHighlightObserver(Observer newObserver) { moteHighlightObservable.addObserver(newObserver); } /** * Delete mote highlight observer. * * @see #addMoteHighlightObserver(Observer) * @param observer * Observer to delete */ public void deleteMoteHighlightObserver(Observer observer) { moteHighlightObservable.deleteObserver(observer); } /** * @return True if simulator is visualized */ public static boolean isVisualized() { return isVisualizedInFrame() || isVisualizedInApplet(); } public static Container getTopParentContainer() { if (isVisualizedInFrame()) { return frame; } if (isVisualizedInApplet()) { /* Find parent frame for applet */ Container container = applet; while((container = container.getParent()) != null){ if (container instanceof Frame) { return container; } if (container instanceof Dialog) { return container; } if (container instanceof Window) { return container; } } logger.fatal("Returning null top owner container"); } return null; } public static boolean isVisualizedInFrame() { return frame != null; } public static URL getAppletCodeBase() { return applet.getCodeBase(); } public static boolean isVisualizedInApplet() { return applet != null; } /** * Tries to create/remove simulator visualizer. * * @param visualized Visualized */ public void setVisualizedInFrame(boolean visualized) { if (visualized) { if (!isVisualizedInFrame()) { configureFrame(cooja, false); } } else { if (frame != null) { frame.setVisible(false); frame.dispose(); frame = null; } } } public File getLastOpenedFile() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); return historyArray.length > 0 ? new File(historyArray[0]) : null; } public File[] getFileHistory() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); File[] history = new File[historyArray.length]; for (int i = 0; i < historyArray.length; i++) { history[i] = new File(historyArray[i]); } return history; } public void addToFileHistory(File file) { // Fetch current history String[] history = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); String newFile = file.getAbsolutePath(); if (history.length > 0 && history[0].equals(newFile)) { // File already added return; } // Create new history StringBuilder newHistory = new StringBuilder(); newHistory.append(newFile); for (int i = 0, count = 1; i < history.length && count < 10; i++) { String historyFile = history[i]; if (newFile.equals(historyFile) || historyFile.length() == 0) { // File already added or empty file name } else { newHistory.append(';').append(historyFile); count++; } } setExternalToolsSetting("SIMCFG_HISTORY", newHistory.toString()); saveExternalToolsUserSettings(); hasFileHistoryChanged = true; } private void updateOpenHistoryMenuItems() { if (isVisualizedInApplet()) { return; } if (!hasFileHistoryChanged) { return; } hasFileHistoryChanged = false; File[] openFilesHistory = getFileHistory(); updateOpenHistoryMenuItems(openFilesHistory); } private void populateMenuWithHistory(JMenu menu, final boolean quick, File[] openFilesHistory) { JMenuItem lastItem; int index = 0; for (File file: openFilesHistory) { if (index < 10) { char mnemonic = (char) ('0' + (++index % 10)); lastItem = new JMenuItem(mnemonic + " " + file.getName()); lastItem.setMnemonic(mnemonic); } else { lastItem = new JMenuItem(file.getName()); } final File f = file; lastItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doLoadConfigAsync(true, quick, f); } }); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); menu.add(lastItem); } } private void doLoadConfigAsync(final boolean ask, final boolean quick, final File file) { new Thread(new Runnable() { public void run() { cooja.doLoadConfig(ask, quick, file, null); } }).start(); } private void updateOpenHistoryMenuItems(File[] openFilesHistory) { menuOpenSimulation.removeAll(); /* Reconfigure submenu */ JMenu reconfigureMenu = new JMenu("Open and Reconfigure"); JMenuItem browseItem2 = new JMenuItem("Browse..."); browseItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doLoadConfigAsync(true, false, null); } }); reconfigureMenu.add(browseItem2); reconfigureMenu.add(new JSeparator()); populateMenuWithHistory(reconfigureMenu, false, openFilesHistory); /* Open menu */ JMenuItem browseItem = new JMenuItem("Browse..."); browseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doLoadConfigAsync(true, true, null); } }); menuOpenSimulation.add(browseItem); menuOpenSimulation.add(new JSeparator()); menuOpenSimulation.add(reconfigureMenu); menuOpenSimulation.add(new JSeparator()); populateMenuWithHistory(menuOpenSimulation, true, openFilesHistory); } /** * Enables/disables menues and menu items depending on whether a simulation is loaded etc. */ void updateGUIComponentState() { if (!isVisualized()) { return; } /* Update action state */ for (GUIAction a: guiActions) { a.setEnabled(a.shouldBeEnabled()); } /* Mote and mote type menues */ if (menuMoteTypeClasses != null) { menuMoteTypeClasses.setEnabled(getSimulation() != null); } if (menuMoteTypes != null) { menuMoteTypes.setEnabled(getSimulation() != null); } } private JMenuBar createMenuBar() { JMenuItem menuItem; /* Prepare GUI actions */ guiActions.add(newSimulationAction); guiActions.add(closeSimulationAction); guiActions.add(reloadSimulationAction); guiActions.add(reloadRandomSimulationAction); guiActions.add(saveSimulationAction); /* guiActions.add(closePluginsAction);*/ guiActions.add(exportExecutableJARAction); guiActions.add(exitCoojaAction); guiActions.add(startStopSimulationAction); guiActions.add(removeAllMotesAction); guiActions.add(showBufferSettingsAction); /* Menus */ JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu simulationMenu = new JMenu("Simulation"); JMenu motesMenu = new JMenu("Motes"); final JMenu toolsMenu = new JMenu("Tools"); JMenu settingsMenu = new JMenu("Settings"); JMenu helpMenu = new JMenu("Help"); menuBar.add(fileMenu); menuBar.add(simulationMenu); menuBar.add(motesMenu); menuBar.add(toolsMenu); menuBar.add(settingsMenu); menuBar.add(helpMenu); fileMenu.setMnemonic(KeyEvent.VK_F); simulationMenu.setMnemonic(KeyEvent.VK_S); motesMenu.setMnemonic(KeyEvent.VK_M); toolsMenu.setMnemonic(KeyEvent.VK_T); helpMenu.setMnemonic(KeyEvent.VK_H); /* File menu */ fileMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); updateOpenHistoryMenuItems(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); fileMenu.add(new JMenuItem(newSimulationAction)); menuOpenSimulation = new JMenu("Open simulation"); menuOpenSimulation.setMnemonic(KeyEvent.VK_O); fileMenu.add(menuOpenSimulation); if (isVisualizedInApplet()) { menuOpenSimulation.setEnabled(false); menuOpenSimulation.setToolTipText("Not available in applet version"); } fileMenu.add(new JMenuItem(closeSimulationAction)); hasFileHistoryChanged = true; fileMenu.add(new JMenuItem(saveSimulationAction)); fileMenu.add(new JMenuItem(exportExecutableJARAction)); /* menu.addSeparator();*/ /* menu.add(new JMenuItem(closePluginsAction));*/ fileMenu.addSeparator(); fileMenu.add(new JMenuItem(exitCoojaAction)); /* Simulation menu */ simulationMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); simulationMenu.add(new JMenuItem(startStopSimulationAction)); JMenuItem reloadSimulationMenuItem = new JMenu("Reload simulation"); reloadSimulationMenuItem.add(new JMenuItem(reloadSimulationAction)); reloadSimulationMenuItem.add(new JMenuItem(reloadRandomSimulationAction)); simulationMenu.add(reloadSimulationMenuItem); GUIAction guiAction = new StartPluginGUIAction("Control panel..."); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.putClientProperty("class", SimControl.class); simulationMenu.add(menuItem); guiAction = new StartPluginGUIAction("Simulation..."); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_I); menuItem.putClientProperty("class", SimInformation.class); simulationMenu.add(menuItem); // Mote type menu motesMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Mote type classes sub menu menuMoteTypeClasses = new JMenu("Create new mote type"); menuMoteTypeClasses.setMnemonic(KeyEvent.VK_C); menuMoteTypeClasses.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypeClasses.removeAll(); // Recreate menu items JMenuItem menuItem; for (Class<? extends MoteType> moteTypeClass : moteTypeClasses) { /* Sort mote types according to abstraction level */ String abstractionLevelDescription = Cooja.getAbstractionLevelDescriptionOf(moteTypeClass); if(abstractionLevelDescription == null) { abstractionLevelDescription = "[unknown cross-level]"; } /* Check if abstraction description already exists */ JSeparator abstractionLevelSeparator = null; for (Component component: menuMoteTypeClasses.getMenuComponents()) { if (component == null || !(component instanceof JSeparator)) { continue; } JSeparator existing = (JSeparator) component; if (abstractionLevelDescription.equals(existing.getToolTipText())) { abstractionLevelSeparator = existing; break; } } if (abstractionLevelSeparator == null) { abstractionLevelSeparator = new JSeparator(); abstractionLevelSeparator.setToolTipText(abstractionLevelDescription); menuMoteTypeClasses.add(abstractionLevelSeparator); } String description = Cooja.getDescriptionOf(moteTypeClass); menuItem = new JMenuItem(description + "..."); menuItem.setActionCommand("create mote type"); menuItem.putClientProperty("class", moteTypeClass); /* menuItem.setToolTipText(abstractionLevelDescription);*/ menuItem.addActionListener(guiEventHandler); if (isVisualizedInApplet() && moteTypeClass.equals(ContikiMoteType.class)) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } /* Add new item directly after cross level separator */ for (int i=0; i < menuMoteTypeClasses.getMenuComponentCount(); i++) { if (menuMoteTypeClasses.getMenuComponent(i) == abstractionLevelSeparator) { menuMoteTypeClasses.add(menuItem, i+1); break; } } } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Mote menu motesMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Mote types sub menu menuMoteTypes = new JMenu("Add motes"); menuMoteTypes.setMnemonic(KeyEvent.VK_A); menuMoteTypes.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypes.removeAll(); if (mySimulation != null) { // Recreate menu items JMenuItem menuItem; for (MoteType moteType : mySimulation.getMoteTypes()) { menuItem = new JMenuItem(moteType.getDescription()); menuItem.setActionCommand("add motes"); menuItem.setToolTipText(getDescriptionOf(moteType.getClass())); menuItem.putClientProperty("motetype", moteType); menuItem.addActionListener(guiEventHandler); menuMoteTypes.add(menuItem); } if(mySimulation.getMoteTypes().length > 0) { menuMoteTypes.add(new JSeparator()); } } menuMoteTypes.add(menuMoteTypeClasses); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); motesMenu.add(menuMoteTypes); guiAction = new StartPluginGUIAction("Mote types..."); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.putClientProperty("class", MoteTypeInformation.class); motesMenu.add(menuItem); motesMenu.add(new JMenuItem(removeAllMotesAction)); /* Tools menu */ toolsMenu.addMenuListener(new MenuListener() { private ActionListener menuItemListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Object pluginClass = ((JMenuItem)e.getSource()).getClientProperty("class"); Object mote = ((JMenuItem)e.getSource()).getClientProperty("mote"); tryStartPlugin((Class<? extends Plugin>) pluginClass, cooja, getSimulation(), (Mote)mote); } }; private JMenuItem createMenuItem(Class<? extends Plugin> newPluginClass, int pluginType) { String description = getDescriptionOf(newPluginClass); JMenuItem menuItem = new JMenuItem(description + "..."); menuItem.putClientProperty("class", newPluginClass); menuItem.addActionListener(menuItemListener); String tooltip = "<html><pre>"; if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tooltip += "Cooja plugin: "; } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { tooltip += "Simulation plugin: "; if (getSimulation() == null) { menuItem.setEnabled(false); } } else if (pluginType == PluginType.MOTE_PLUGIN) { tooltip += "Mote plugin: "; } tooltip += description + " (" + newPluginClass.getName() + ")"; /* Check if simulation plugin depends on any particular radio medium */ if ((pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) && (getSimulation() != null)) { if (newPluginClass.getAnnotation(SupportedArguments.class) != null) { boolean active = false; Class<? extends RadioMedium>[] radioMediums = newPluginClass.getAnnotation(SupportedArguments.class).radioMediums(); for (Class<? extends Object> o: radioMediums) { if (o.isAssignableFrom(getSimulation().getRadioMedium().getClass())) { active = true; break; } } if (!active) { menuItem.setVisible(false); } } } /* Check if plugin was imported by a extension directory */ File project = getProjectConfig().getUserProjectDefining(Cooja.class, "PLUGINS", newPluginClass.getName()); if (project != null) { tooltip += "\nLoaded by extension: " + project.getPath(); } tooltip += "</html>"; /*menuItem.setToolTipText(tooltip);*/ return menuItem; } public void menuSelected(MenuEvent e) { /* Populate tools menu */ toolsMenu.removeAll(); /* Cooja plugins */ boolean hasCoojaPlugins = false; for (Class<? extends Plugin> pluginClass: pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { continue; } toolsMenu.add(createMenuItem(pluginClass, pluginType)); hasCoojaPlugins = true; } /* Simulation plugins */ boolean hasSimPlugins = false; for (Class<? extends Plugin> pluginClass: pluginClasses) { if (pluginClass.equals(SimControl.class)) { continue; /* ignore */ } if (pluginClass.equals(SimInformation.class)) { continue; /* ignore */ } if (pluginClass.equals(MoteTypeInformation.class)) { continue; /* ignore */ } int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType != PluginType.SIM_PLUGIN && pluginType != PluginType.SIM_STANDARD_PLUGIN) { continue; } if (hasCoojaPlugins) { hasCoojaPlugins = false; toolsMenu.addSeparator(); } toolsMenu.add(createMenuItem(pluginClass, pluginType)); hasSimPlugins = true; } for (Class<? extends Plugin> pluginClass: pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType != PluginType.MOTE_PLUGIN) { continue; } if (hasSimPlugins) { hasSimPlugins = false; toolsMenu.addSeparator(); } toolsMenu.add(createMotePluginsSubmenu(pluginClass)); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Settings menu settingsMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menuItem = new JMenuItem("External tools paths..."); menuItem.setActionCommand("edit paths"); menuItem.addActionListener(guiEventHandler); settingsMenu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Cooja extensions..."); menuItem.setActionCommand("manage extensions"); menuItem.addActionListener(guiEventHandler); settingsMenu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Cooja mote configuration wizard..."); menuItem.setActionCommand("configuration wizard"); menuItem.addActionListener(guiEventHandler); settingsMenu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } settingsMenu.add(new JMenuItem(showBufferSettingsAction)); /* Help */ helpMenu.add(new JMenuItem(showGettingStartedAction)); helpMenu.add(new JMenuItem(showKeyboardShortcutsAction)); JCheckBoxMenuItem checkBox = new JCheckBoxMenuItem(showQuickHelpAction); showQuickHelpAction.putValue("checkbox", checkBox); helpMenu.add(checkBox); helpMenu.addSeparator(); menuItem = new JMenuItem("Java version: " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); menuItem.setEnabled(false); helpMenu.add(menuItem); menuItem = new JMenuItem("System \"os.arch\": " + System.getProperty("os.arch")); menuItem.setEnabled(false); helpMenu.add(menuItem); menuItem = new JMenuItem("System \"sun.arch.data.model\": " + System.getProperty("sun.arch.data.model")); menuItem.setEnabled(false); helpMenu.add(menuItem); return menuBar; } private static void configureFrame(final Cooja gui, boolean createSimDialog) { if (frame == null) { frame = new JFrame(WINDOW_TITLE); } frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* Menu bar */ frame.setJMenuBar(gui.createMenuBar()); /* Scrollable desktop */ JComponent desktop = gui.getDesktopPane(); desktop.setOpaque(true); JScrollPane scroll = new JScrollPane(desktop); scroll.setBorder(null); JPanel container = new JPanel(new BorderLayout()); container.add(BorderLayout.CENTER, scroll); container.add(BorderLayout.EAST, gui.quickHelpScroll); frame.setContentPane(container); frame.setSize(700, 700); frame.setLocationRelativeTo(null); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { gui.doQuit(true); } }); frame.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { updateDesktopSize(gui.getDesktopPane()); } }); /* Restore frame size and position */ int framePosX = Integer.parseInt(getExternalToolsSetting("FRAME_POS_X", "0")); int framePosY = Integer.parseInt(getExternalToolsSetting("FRAME_POS_Y", "0")); int frameWidth = Integer.parseInt(getExternalToolsSetting("FRAME_WIDTH", "0")); int frameHeight = Integer.parseInt(getExternalToolsSetting("FRAME_HEIGHT", "0")); String frameScreen = getExternalToolsSetting("FRAME_SCREEN", ""); /* Restore position to the same graphics device */ GraphicsDevice device = null; GraphicsDevice all[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (GraphicsDevice gd : all) { if (gd.getIDstring().equals(frameScreen)) { device = gd; } } /* Check if frame should be maximized */ if (device != null) { if (frameWidth == Integer.MAX_VALUE && frameHeight == Integer.MAX_VALUE) { frame.setLocation(device.getDefaultConfiguration().getBounds().getLocation()); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); } else if (frameWidth > 0 && frameHeight > 0) { /* Sanity-check: will Cooja be visible on screen? */ boolean intersects = device.getDefaultConfiguration().getBounds().intersects( new Rectangle(framePosX, framePosY, frameWidth, frameHeight)); if (intersects) { frame.setLocation(framePosX, framePosY); frame.setSize(frameWidth, frameHeight); } } } frame.setVisible(true); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } private static void configureApplet(final Cooja gui, boolean createSimDialog) { applet = CoojaApplet.applet; // Add menu bar JMenuBar menuBar = gui.createMenuBar(); applet.setJMenuBar(menuBar); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); applet.setContentPane(newContentPane); applet.setSize(700, 700); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } /** * @return Current desktop pane (simulator visualizer) */ public JDesktopPane getDesktopPane() { return myDesktopPane; } public static void setLookAndFeel() { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); ToolTipManager.sharedInstance().setDismissDelay(60000); /* Nimbus */ try { String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("linux")) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (UnsupportedLookAndFeelException e) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } } else { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } return; } catch (Exception e) { } /* System */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); return; } catch (Exception e) { } } private static void updateDesktopSize(final JDesktopPane desktop) { if (desktop == null || !desktop.isVisible() || desktop.getParent() == null) { return; } Rectangle rect = desktop.getVisibleRect(); Dimension pref = new Dimension(rect.width - 1, rect.height - 1); for (JInternalFrame frame : desktop.getAllFrames()) { if (pref.width < frame.getX() + frame.getWidth() - 20) { pref.width = frame.getX() + frame.getWidth(); } if (pref.height < frame.getY() + frame.getHeight() - 20) { pref.height = frame.getY() + frame.getHeight(); } } desktop.setPreferredSize(pref); desktop.revalidate(); } private static JDesktopPane createDesktopPane() { final JDesktopPane desktop = new JDesktopPane() { private static final long serialVersionUID = -8272040875621119329L; public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); updateDesktopSize(this); } public void remove(Component c) { super.remove(c); updateDesktopSize(this); } public Component add(Component comp) { Component c = super.add(comp); updateDesktopSize(this); return c; } }; desktop.setDesktopManager(new DefaultDesktopManager() { private static final long serialVersionUID = -5987404936292377152L; public void endResizingFrame(JComponent f) { super.endResizingFrame(f); updateDesktopSize(desktop); } public void endDraggingFrame(JComponent f) { super.endDraggingFrame(f); updateDesktopSize(desktop); } }); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); return desktop; } public static Simulation quickStartSimulationConfig(File config, boolean vis, Long manualRandomSeed) { logger.info("> Starting Cooja"); JDesktopPane desktop = createDesktopPane(); if (vis) { frame = new JFrame(WINDOW_TITLE); } Cooja gui = new Cooja(desktop); if (vis) { configureFrame(gui, false); } if (vis) { gui.doLoadConfig(false, true, config, manualRandomSeed); return gui.getSimulation(); } else { try { Simulation newSim = gui.loadSimulationConfig(config, true, manualRandomSeed); if (newSim == null) { return null; } gui.setSimulation(newSim, false); return newSim; } catch (Exception e) { logger.fatal("Exception when loading simulation: ", e); return null; } } } /** * Allows user to create a simulation with a single mote type. * * @param source Contiki application file name * @return True if simulation was created */ private static Simulation quickStartSimulation(String source) { logger.info("> Starting Cooja"); JDesktopPane desktop = createDesktopPane(); frame = new JFrame(WINDOW_TITLE); Cooja gui = new Cooja(desktop); configureFrame(gui, false); logger.info("> Creating simulation"); Simulation sim = new Simulation(gui); sim.setTitle("Quickstarted simulation: " + source); boolean simOK = CreateSimDialog.showDialog(Cooja.getTopParentContainer(), sim); if (!simOK) { logger.fatal("No simulation, aborting quickstart"); System.exit(1); } gui.setSimulation(sim, true); logger.info("> Creating mote type"); ContikiMoteType moteType = new ContikiMoteType(); moteType.setContikiSourceFile(new File(source)); moteType.setDescription("Cooja mote type (" + source + ")"); try { boolean compileOK = moteType.configureAndInit(Cooja.getTopParentContainer(), sim, true); if (!compileOK) { logger.fatal("Mote type initialization failed, aborting quickstart"); return null; } } catch (MoteTypeCreationException e1) { logger.fatal("Mote type initialization failed, aborting quickstart"); return null; } sim.addMoteType(moteType); logger.info("> Adding motes"); gui.doAddMotes(moteType); return sim; } //// PROJECT CONFIG AND EXTENDABLE PARTS METHODS //// /** * Register new mote type class. * * @param moteTypeClass * Class to register */ public void registerMoteType(Class<? extends MoteType> moteTypeClass) { moteTypeClasses.add(moteTypeClass); } /** * Unregister all mote type classes. */ public void unregisterMoteTypes() { moteTypeClasses.clear(); } /** * @return All registered mote type classes */ public Vector<Class<? extends MoteType>> getRegisteredMoteTypes() { return moteTypeClasses; } /** * Register new positioner class. * * @param positionerClass * Class to register * @return True if class was registered */ public boolean registerPositioner(Class<? extends Positioner> positionerClass) { // Check that interval constructor exists try { positionerClass .getConstructor(new Class[] { int.class, double.class, double.class, double.class, double.class, double.class, double.class }); } catch (Exception e) { logger.fatal("No interval constructor found of positioner: " + positionerClass); return false; } positionerClasses.add(positionerClass); return true; } /** * Unregister all positioner classes. */ public void unregisterPositioners() { positionerClasses.clear(); } /** * @return All registered positioner classes */ public Vector<Class<? extends Positioner>> getRegisteredPositioners() { return positionerClasses; } /** * Register new radio medium class. * * @param radioMediumClass * Class to register * @return True if class was registered */ public boolean registerRadioMedium( Class<? extends RadioMedium> radioMediumClass) { // Check that simulation constructor exists try { radioMediumClass.getConstructor(new Class[] { Simulation.class }); } catch (Exception e) { logger.fatal("No simulation constructor found of radio medium: " + radioMediumClass); return false; } radioMediumClasses.add(radioMediumClass); return true; } /** * Unregister all radio medium classes. */ public void unregisterRadioMediums() { radioMediumClasses.clear(); } /** * @return All registered radio medium classes */ public Vector<Class<? extends RadioMedium>> getRegisteredRadioMediums() { return radioMediumClasses; } /** * Builds new extension configuration using current extension directories settings. * Reregisters mote types, plugins, positioners and radio * mediums. This method may still return true even if all classes could not be * registered, but always returns false if all extension directory configuration * files were not parsed correctly. */ public void reparseProjectConfig() throws ParseProjectsException { if (PROJECT_DEFAULT_CONFIG_FILENAME == null) { if (isVisualizedInApplet()) { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_applet.config"; } else { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_default.config"; } } /* Remove current dependencies */ unregisterMoteTypes(); unregisterPlugins(); unregisterPositioners(); unregisterRadioMediums(); projectDirClassLoader = null; /* Build cooja configuration */ try { projectConfig = new ProjectConfig(true); } catch (FileNotFoundException e) { logger.fatal("Could not find default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Could not find default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } catch (IOException e) { logger.fatal("Error when reading default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Error when reading default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } if (!isVisualizedInApplet()) { for (COOJAProject project: currentProjects) { try { projectConfig.appendProjectDir(project.dir); } catch (FileNotFoundException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when loading extension: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when reading extension config: " + e.getMessage()).initCause(e); } } /* Create extension class loader */ try { projectDirClassLoader = createClassLoader(currentProjects); } catch (ClassLoaderCreationException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when creating class loader").initCause(e); } } // Register mote types String[] moteTypeClassNames = projectConfig.getStringArrayValue(Cooja.class, "MOTETYPES"); if (moteTypeClassNames != null) { for (String moteTypeClassName : moteTypeClassNames) { if (moteTypeClassName.trim().isEmpty()) { continue; } Class<? extends MoteType> moteTypeClass = tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass != null) { registerMoteType(moteTypeClass); // logger.info("Loaded mote type class: " + moteTypeClassName); } else { logger.warn("Could not load mote type class: " + moteTypeClassName); } } } // Register plugins registerPlugin(SimControl.class); registerPlugin(SimInformation.class); registerPlugin(MoteTypeInformation.class); String[] pluginClassNames = projectConfig.getStringArrayValue(Cooja.class, "PLUGINS"); if (pluginClassNames != null) { for (String pluginClassName : pluginClassNames) { Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass != null) { registerPlugin(pluginClass); // logger.info("Loaded plugin class: " + pluginClassName); } else { logger.warn("Could not load plugin class: " + pluginClassName); } } } // Register positioners String[] positionerClassNames = projectConfig.getStringArrayValue( Cooja.class, "POSITIONERS"); if (positionerClassNames != null) { for (String positionerClassName : positionerClassNames) { Class<? extends Positioner> positionerClass = tryLoadClass(this, Positioner.class, positionerClassName); if (positionerClass != null) { registerPositioner(positionerClass); // logger.info("Loaded positioner class: " + positionerClassName); } else { logger .warn("Could not load positioner class: " + positionerClassName); } } } // Register radio mediums String[] radioMediumsClassNames = projectConfig.getStringArrayValue( Cooja.class, "RADIOMEDIUMS"); if (radioMediumsClassNames != null) { for (String radioMediumClassName : radioMediumsClassNames) { Class<? extends RadioMedium> radioMediumClass = tryLoadClass(this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { registerRadioMedium(radioMediumClass); // logger.info("Loaded radio medium class: " + radioMediumClassName); } else { logger.warn("Could not load radio medium class: " + radioMediumClassName); } } } } /** * Returns the current extension configuration common to the entire simulator. * * @return Current extension configuration */ public ProjectConfig getProjectConfig() { return projectConfig; } /** * Returns the current extension directories common to the entire simulator. * * @return Current extension directories. */ public COOJAProject[] getProjects() { return currentProjects.toArray(new COOJAProject[0]); } // // PLUGIN METHODS //// /** * Show a started plugin in working area. * * @param plugin Plugin */ public void showPlugin(final Plugin plugin) { new RunnableInEDT<Boolean>() { public Boolean work() { JInternalFrame pluginFrame = plugin.getCooja(); if (pluginFrame == null) { logger.fatal("Failed trying to show plugin without visualizer."); return false; } myDesktopPane.add(pluginFrame); /* Set size if not already specified by plugin */ if (pluginFrame.getWidth() <= 0 || pluginFrame.getHeight() <= 0) { pluginFrame.setSize(FRAME_STANDARD_WIDTH, FRAME_STANDARD_HEIGHT); } /* Set location if not already set */ if (pluginFrame.getLocation().x <= 0 && pluginFrame.getLocation().y <= 0) { pluginFrame.setLocation(determineNewPluginLocation()); } pluginFrame.setVisible(true); /* Select plugin */ try { for (JInternalFrame existingPlugin : myDesktopPane.getAllFrames()) { existingPlugin.setSelected(false); } pluginFrame.setSelected(true); } catch (Exception e) { } myDesktopPane.moveToFront(pluginFrame); return true; } }.invokeAndWait(); } /** * Determines suitable location for placing new plugin. * <p> * If possible, this is below right of the second last activated * internfal frame (offset is determined by FRAME_NEW_OFFSET). * * @return Resulting placement position */ private Point determineNewPluginLocation() { Point topFrameLoc; JInternalFrame[] iframes = myDesktopPane.getAllFrames(); if (iframes.length > 1) { topFrameLoc = iframes[1].getLocation(); } else { topFrameLoc = new Point( myDesktopPane.getSize().width / 2, myDesktopPane.getSize().height / 2); } return new Point( topFrameLoc.x + FRAME_NEW_OFFSET, topFrameLoc.y + FRAME_NEW_OFFSET); } /** * Close all mote plugins for given mote. * * @param mote Mote */ public void closeMotePlugins(Mote mote) { for (Plugin p: startedPlugins.toArray(new Plugin[0])) { if (!(p instanceof MotePlugin)) { continue; } Mote pluginMote = ((MotePlugin)p).getMote(); if (pluginMote == mote) { removePlugin(p, false); } } } /** * Remove a plugin from working area. * * @param plugin * Plugin to remove * @param askUser * If plugin is the last one, ask user if we should remove current * simulation also? */ public void removePlugin(final Plugin plugin, final boolean askUser) { new RunnableInEDT<Boolean>() { public Boolean work() { /* Free resources */ plugin.closePlugin(); startedPlugins.remove(plugin); updateGUIComponentState(); /* Dispose visualized components */ if (plugin.getCooja() != null) { plugin.getCooja().dispose(); } /* (OPTIONAL) Remove simulation if all plugins are closed */ if (getSimulation() != null && askUser && startedPlugins.isEmpty()) { doRemoveSimulation(true); } return true; } }.invokeAndWait(); } /** * Same as the {@link #startPlugin(Class, Cooja, Simulation, Mote)} method, * but does not throw exceptions. If COOJA is visualised, an error dialog * is shown if plugin could not be started. * * @see #startPlugin(Class, Cooja, Simulation, Mote) * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin */ private Plugin tryStartPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote, boolean activate) { try { return startPlugin(pluginClass, argGUI, argSimulation, argMote, activate); } catch (PluginConstructionException ex) { if (Cooja.isVisualized()) { Cooja.showErrorDialog(Cooja.getTopParentContainer(), "Error when starting plugin", ex, false); } else { /* If the plugin requires visualization, inform user */ Throwable cause = ex; do { if (cause instanceof PluginRequiresVisualizationException) { logger.info("Visualized plugin was not started: " + pluginClass); return null; } } while (cause != null && (cause=cause.getCause()) != null); logger.fatal("Error when starting plugin", ex); } } return null; } public Plugin tryStartPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote) { return tryStartPlugin(pluginClass, argGUI, argSimulation, argMote, true); } public Plugin startPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote) throws PluginConstructionException { return startPlugin(pluginClass, argGUI, argSimulation, argMote, true); } /** * Starts given plugin. If visualized, the plugin is also shown. * * @see PluginType * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin * @throws PluginConstructionException At errors */ private Plugin startPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote, boolean activate) throws PluginConstructionException { // Check that plugin class is registered if (!pluginClasses.contains(pluginClass)) { throw new PluginConstructionException("Tool class not registered: " + pluginClass); } // Construct plugin depending on plugin type int pluginType = pluginClass.getAnnotation(PluginType.class).value(); Plugin plugin; try { if (pluginType == PluginType.MOTE_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for mote plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for mote plugin"); } if (argMote == null) { throw new PluginConstructionException("No mote argument for mote plugin"); } plugin = pluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, Cooja.class }) .newInstance(argMote, argSimulation, argGUI); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for simulation plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for simulation plugin"); } plugin = pluginClass.getConstructor(new Class[] { Simulation.class, Cooja.class }) .newInstance(argSimulation, argGUI); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for GUI plugin"); } plugin = pluginClass.getConstructor(new Class[] { Cooja.class }) .newInstance(argGUI); } else { throw new PluginConstructionException("Bad plugin type: " + pluginType); } } catch (PluginRequiresVisualizationException e) { PluginConstructionException ex = new PluginConstructionException("Tool class requires visualization: " + pluginClass.getName()); ex.initCause(e); throw ex; } catch (Exception e) { PluginConstructionException ex = new PluginConstructionException("Construction error for tool of class: " + pluginClass.getName()); ex.initCause(e); throw ex; } if (activate) { plugin.startPlugin(); } // Add to active plugins list startedPlugins.add(plugin); updateGUIComponentState(); // Show plugin if visualizer type if (activate && plugin.getCooja() != null) { cooja.showPlugin(plugin); } return plugin; } /** * Unregister a plugin class. Removes any plugin menu items links as well. * * @param pluginClass Plugin class */ public void unregisterPlugin(Class<? extends Plugin> pluginClass) { pluginClasses.remove(pluginClass); menuMotePluginClasses.remove(pluginClass); } /** * Register a plugin to be included in the GUI. * * @param pluginClass New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerPlugin(final Class<? extends Plugin> pluginClass) { /* Check plugin type */ final int pluginType; if (pluginClass.isAnnotationPresent(PluginType.class)) { pluginType = pluginClass.getAnnotation(PluginType.class).value(); } else { logger.fatal("Could not register plugin, no plugin type found: " + pluginClass); return false; } /* Check plugin constructor */ try { if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { pluginClass.getConstructor(new Class[] { Cooja.class }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { pluginClass.getConstructor(new Class[] { Simulation.class, Cooja.class }); } else if (pluginType == PluginType.MOTE_PLUGIN) { pluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, Cooja.class }); menuMotePluginClasses.add(pluginClass); } else { logger.fatal("Could not register plugin, bad plugin type: " + pluginType); return false; } pluginClasses.add(pluginClass); } catch (NoClassDefFoundError e) { logger.fatal("No plugin class: " + pluginClass + ": " + e.getMessage()); return false; } catch (NoSuchMethodException e) { logger.fatal("No plugin class constructor: " + pluginClass + ": " + e.getMessage()); return false; } return true; } /** * Unregister all plugin classes */ public void unregisterPlugins() { menuMotePluginClasses.clear(); pluginClasses.clear(); } /** * Returns started plugin that ends with given class name, if any. * * @param classname Class name * @return Plugin instance */ public Plugin getPlugin(String classname) { for (Plugin p: startedPlugins) { if (p.getClass().getName().endsWith(classname)) { return p; } } return null; } /** * Returns started plugin with given class name, if any. * * @param classname Class name * @return Plugin instance * @deprecated */ @Deprecated public Plugin getStartedPlugin(String classname) { return getPlugin(classname); } public Plugin[] getStartedPlugins() { return startedPlugins.toArray(new Plugin[0]); } private boolean isMotePluginCompatible(Class<? extends Plugin> motePluginClass, Mote mote) { if (motePluginClass.getAnnotation(SupportedArguments.class) == null) { return true; } /* Check mote interfaces */ boolean moteInterfacesOK = true; Class<? extends MoteInterface>[] moteInterfaces = motePluginClass.getAnnotation(SupportedArguments.class).moteInterfaces(); StringBuilder moteTypeInterfacesError = new StringBuilder(); moteTypeInterfacesError.append( "The plugin:\n" + getDescriptionOf(motePluginClass) + "\nrequires the following mote interfaces:\n" ); for (Class<? extends MoteInterface> requiredMoteInterface: moteInterfaces) { moteTypeInterfacesError.append(getDescriptionOf(requiredMoteInterface) + "\n"); if (mote.getInterfaces().getInterfaceOfType(requiredMoteInterface) == null) { moteInterfacesOK = false; } } /* Check mote type */ boolean moteTypeOK = false; Class<? extends Mote>[] motes = motePluginClass.getAnnotation(SupportedArguments.class).motes(); StringBuilder moteTypeError = new StringBuilder(); moteTypeError.append( "The plugin:\n" + getDescriptionOf(motePluginClass) + "\ndoes not support motes of type:\n" + getDescriptionOf(mote) + "\n\nIt only supports motes of types:\n" ); for (Class<? extends Mote> supportedMote: motes) { moteTypeError.append(getDescriptionOf(supportedMote) + "\n"); if (supportedMote.isAssignableFrom(mote.getClass())) { moteTypeOK = true; } } /*if (!moteInterfacesOK) { menuItem.setToolTipText( "<html><pre>" + moteTypeInterfacesError + "</html>" ); } if (!moteTypeOK) { menuItem.setToolTipText( "<html><pre>" + moteTypeError + "</html>" ); }*/ return moteInterfacesOK && moteTypeOK; } public JMenu createMotePluginsSubmenu(Class<? extends Plugin> pluginClass) { JMenu menu = new JMenu(getDescriptionOf(pluginClass)); if (getSimulation() == null || getSimulation().getMotesCount() == 0) { menu.setEnabled(false); return menu; } ActionListener menuItemListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Object pluginClass = ((JMenuItem)e.getSource()).getClientProperty("class"); Object mote = ((JMenuItem)e.getSource()).getClientProperty("mote"); tryStartPlugin((Class<? extends Plugin>) pluginClass, cooja, getSimulation(), (Mote)mote); } }; final int MAX_PER_ROW = 30; final int MAX_COLUMNS = 5; int added = 0; for (Mote mote: getSimulation().getMotes()) { if (!isMotePluginCompatible(pluginClass, mote)) { continue; } JMenuItem menuItem = new JMenuItem(mote.toString() + "..."); menuItem.putClientProperty("class", pluginClass); menuItem.putClientProperty("mote", mote); menuItem.addActionListener(menuItemListener); menu.add(menuItem); added++; if (added == MAX_PER_ROW) { menu.getPopupMenu().setLayout(new GridLayout(MAX_PER_ROW, MAX_COLUMNS)); } if (added >= MAX_PER_ROW*MAX_COLUMNS) { break; } } if (added == 0) { menu.setEnabled(false); } return menu; } /** * Return a mote plugins submenu for given mote. * * @param mote Mote * @return Mote plugins menu */ public JMenu createMotePluginsSubmenu(Mote mote) { JMenu menuMotePlugins = new JMenu("Mote tools for " + mote); for (Class<? extends Plugin> motePluginClass: menuMotePluginClasses) { if (!isMotePluginCompatible(motePluginClass, mote)) { continue; } GUIAction guiAction = new StartPluginGUIAction(getDescriptionOf(motePluginClass) + "..."); JMenuItem menuItem = new JMenuItem(guiAction); menuItem.putClientProperty("class", motePluginClass); menuItem.putClientProperty("mote", mote); menuMotePlugins.add(menuItem); } return menuMotePlugins; } // // GUI CONTROL METHODS //// /** * @return Current simulation */ public Simulation getSimulation() { return mySimulation; } public void setSimulation(Simulation sim, boolean startPlugins) { if (sim != null) { doRemoveSimulation(false); } mySimulation = sim; updateGUIComponentState(); // Set frame title if (frame != null) { frame.setTitle(sim.getTitle() + " - " + WINDOW_TITLE); } // Open standard plugins (if none opened already) if (startPlugins) { for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.SIM_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, sim, null); } } } setChanged(); notifyObservers(); } /** * Creates a new mote type of the given mote type class. * This may include displaying a dialog for user configurations. * * If mote type is created successfully, the add motes dialog will appear. * * @param moteTypeClass Mote type class */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass) { doCreateMoteType(moteTypeClass, true); } /** * Creates a new mote type of the given mote type class. * This may include displaying a dialog for user configurations. * * @param moteTypeClass Mote type class * @param addMotes Show add motes dialog after successfully adding mote type */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass, boolean addMotes) { if (mySimulation == null) { logger.fatal("Can't create mote type (no simulation)"); return; } mySimulation.stopSimulation(); // Create mote type MoteType newMoteType = null; try { newMoteType = moteTypeClass.newInstance(); if (!newMoteType.configureAndInit(Cooja.getTopParentContainer(), mySimulation, isVisualized())) { return; } mySimulation.addMoteType(newMoteType); } catch (Exception e) { logger.fatal("Exception when creating mote type", e); if (isVisualized()) { showErrorDialog(getTopParentContainer(), "Mote type creation error", e, false); } return; } /* Allow user to immediately add motes */ if (addMotes) { doAddMotes(newMoteType); } } /** * Remove current simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? * @return True if no simulation exists when method returns */ public boolean doRemoveSimulation(boolean askForConfirmation) { if (mySimulation == null) { return true; } if (askForConfirmation) { boolean ok = new RunnableInEDT<Boolean>() { public Boolean work() { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(Cooja.getTopParentContainer(), "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s2); if (n != JOptionPane.YES_OPTION) { return false; } return true; } }.invokeAndWait(); if (!ok) { return false; } } // Close all started non-GUI plugins for (Object startedPlugin : startedPlugins.toArray()) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { removePlugin((Plugin) startedPlugin, false); } } // Delete simulation mySimulation.deleteObservers(); mySimulation.stopSimulation(); mySimulation.removed(); /* Clear current mote relations */ MoteRelation relations[] = getMoteRelations(); for (MoteRelation r: relations) { removeMoteRelation(r.source, r.dest); } mySimulation = null; updateGUIComponentState(); // Reset frame title if (isVisualizedInFrame()) { frame.setTitle(WINDOW_TITLE); } setChanged(); notifyObservers(); return true; } /** * Load a simulation configuration file from disk * * @param askForConfirmation Ask for confirmation before removing any current simulation * @param quick Quick-load simulation * @param configFile Configuration file to load, if null a dialog will appear */ public void doLoadConfig(boolean askForConfirmation, final boolean quick, File configFile, Long manualRandomSeed) { if (isVisualizedInApplet()) { return; } /* Warn about memory usage */ if (warnMemory()) { return; } /* Remove current simulation */ if (!doRemoveSimulation(true)) { return; } /* Use provided configuration, or open File Chooser */ if (configFile != null && !configFile.isDirectory()) { if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file: " + configFile.getAbsolutePath()); /* File does not exist, open dialog */ doLoadConfig(askForConfirmation, quick, null, manualRandomSeed); return; } } else { final File suggestedFile = configFile; configFile = new RunnableInEDT<File>() { public File work() { JFileChooser fc = new JFileChooser(); fc.setFileFilter(Cooja.SAVED_SIMULATIONS_FILES); if (suggestedFile != null && suggestedFile.isDirectory()) { fc.setCurrentDirectory(suggestedFile); } else { /* Suggest file using file history */ File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } } int returnVal = fc.showOpenDialog(Cooja.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { logger.info("Load command cancelled by user..."); return null; } File file = fc.getSelectedFile(); if (!file.exists()) { /* Try default file extension */ file = new File(file.getParent(), file.getName() + SAVED_SIMULATIONS_FILES); } if (!file.exists() || !file.canRead()) { logger.fatal("No read access to file"); return null; } return file; } }.invokeAndWait(); if (configFile == null) { return; } } addToFileHistory(configFile); final JDialog progressDialog; final String progressTitle = configFile == null ? "Loading" : ("Loading " + configFile.getAbsolutePath()); if (quick) { final Thread loadThread = Thread.currentThread(); progressDialog = new RunnableInEDT<JDialog>() { public JDialog work() { final JDialog progressDialog = new JDialog((Window) Cooja.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); JPanel progressPanel = new JPanel(new BorderLayout()); JProgressBar progressBar; JButton button; progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ button = new JButton("Abort"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } } }); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(Cooja.getTopParentContainer()); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { progressDialog.setVisible(true); } }); return progressDialog; } }.invokeAndWait(); } else { progressDialog = null; } // Load simulation in this thread, while showing progress monitor final File fileToLoad = configFile; Simulation newSim = null; boolean shouldRetry = false; do { try { shouldRetry = false; cooja.doRemoveSimulation(false); PROGRESS_WARNINGS.clear(); newSim = loadSimulationConfig(fileToLoad, quick, manualRandomSeed); cooja.setSimulation(newSim, false); /* Optionally show compilation warnings */ boolean hideWarn = Boolean.parseBoolean( Cooja.getExternalToolsSetting("HIDE_WARNINGS", "false") ); if (quick && !hideWarn && !PROGRESS_WARNINGS.isEmpty()) { showWarningsDialog(frame, PROGRESS_WARNINGS.toArray(new String[0])); } PROGRESS_WARNINGS.clear(); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(Cooja.getTopParentContainer(), "Simulation load error", e, true); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(Cooja.getTopParentContainer(), "Simulation load error", e, true); } } while (shouldRetry); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } return; } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * * @param autoStart Start executing simulation when loaded * @param randomSeed Simulation's next random seed */ public void reloadCurrentSimulation(final boolean autoStart, final long randomSeed) { if (getSimulation() == null) { logger.fatal("No simulation to reload"); return; } /* Warn about memory usage */ if (warnMemory()) { return; } final JDialog progressDialog = new JDialog(frame, "Reloading", true); final Thread loadThread = new Thread(new Runnable() { public void run() { /* Get current simulation configuration */ Element root = new Element("simconf"); Element simulationElement = new Element("simulation"); simulationElement.addContent(getSimulation().getConfigXML()); root.addContent(simulationElement); Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } /* Remove current simulation, and load config */ boolean shouldRetry = false; do { try { shouldRetry = false; cooja.doRemoveSimulation(false); PROGRESS_WARNINGS.clear(); Simulation newSim = loadSimulationConfig(root, true, new Long(randomSeed)); cooja.setSimulation(newSim, false); if (autoStart) { newSim.startSimulation(); } /* Optionally show compilation warnings */ boolean hideWarn = Boolean.parseBoolean( Cooja.getExternalToolsSetting("HIDE_WARNINGS", "false") ); if (!hideWarn && !PROGRESS_WARNINGS.isEmpty()) { showWarningsDialog(frame, PROGRESS_WARNINGS.toArray(new String[0])); } PROGRESS_WARNINGS.clear(); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); cooja.doRemoveSimulation(false); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); cooja.doRemoveSimulation(false); } } while (shouldRetry); if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); // Display progress dialog while reloading JProgressBar progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ JButton button = new JButton("Abort"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); progressDialog.setVisible(true); } private boolean warnMemory() { long max = Runtime.getRuntime().maxMemory(); long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); double memRatio = (double) used / (double) max; if (memRatio < 0.8) { return false; } DecimalFormat format = new DecimalFormat("0.000"); logger.warn("Memory usage is getting critical. Reboot Cooja to avoid out of memory error. Current memory usage is " + format.format(100*memRatio) + "%."); if (isVisualized()) { int n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "Reboot Cooja to avoid out of memory error.\n" + "Current memory usage is " + format.format(100*memRatio) + "%.", "Out of memory warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] { "Continue", "Abort"}, "Abort"); if (n != JOptionPane.YES_OPTION) { return true; } } return false; } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * The same random seed is used. * * @see #reloadCurrentSimulation(boolean, long) * @param autoStart Start executing simulation when loaded */ public void reloadCurrentSimulation(boolean autoStart) { reloadCurrentSimulation(autoStart, getSimulation().getRandomSeed()); } /** * Save current simulation configuration to disk * * @param askForConfirmation * Ask for confirmation before overwriting file */ public File doSaveConfig(boolean askForConfirmation) { if (isVisualizedInApplet()) { return null; } if (mySimulation == null) { return null; } mySimulation.stopSimulation(); JFileChooser fc = new JFileChooser(); fc.setFileFilter(Cooja.SAVED_SIMULATIONS_FILES); // Suggest file using history File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } int returnVal = fc.showSaveDialog(myDesktopPane); if (returnVal == JFileChooser.APPROVE_OPTION) { File saveFile = fc.getSelectedFile(); if (!fc.accept(saveFile)) { saveFile = new File(saveFile.getParent(), saveFile.getName() + SAVED_SIMULATIONS_FILES); } if (saveFile.exists()) { if (askForConfirmation) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return null; } } } if (!saveFile.exists() || saveFile.canWrite()) { saveSimulationConfig(saveFile); addToFileHistory(saveFile); return saveFile; } else { JOptionPane.showMessageDialog( getTopParentContainer(), "No write access to " + saveFile, "Save failed", JOptionPane.ERROR_MESSAGE); logger.fatal("No write access to file: " + saveFile.getAbsolutePath()); } } else { logger.info("Save command cancelled by user..."); } return null; } /** * Add new mote to current simulation */ public void doAddMotes(MoteType moteType) { if (mySimulation != null) { mySimulation.stopSimulation(); Vector<Mote> newMotes = AddMoteDialog.showDialog(getTopParentContainer(), mySimulation, moteType); if (newMotes != null) { for (Mote newMote : newMotes) { mySimulation.addMote(newMote); } } } else { logger.warn("No simulation active"); } } /** * Create a new simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doCreateSimulation(boolean askForConfirmation) { /* Remove current simulation */ if (!doRemoveSimulation(askForConfirmation)) { return; } // Create new simulation Simulation newSim = new Simulation(this); boolean createdOK = CreateSimDialog.showDialog(Cooja.getTopParentContainer(), newSim); if (createdOK) { cooja.setSimulation(newSim, true); } } /** * Quit program * * @param askForConfirmation Should we ask for confirmation before quitting? */ public void doQuit(boolean askForConfirmation) { doQuit(askForConfirmation, 0); } public void doQuit(boolean askForConfirmation, int exitCode) { if (isVisualizedInApplet()) { return; } if (askForConfirmation) { if (getSimulation() != null) { /* Save? */ String s1 = "Yes"; String s2 = "No"; String s3 = "Cancel"; Object[] options = { s1, s2, s3 }; int n = JOptionPane.showOptionDialog(Cooja.getTopParentContainer(), "Do you want to save the current simulation?", WINDOW_TITLE, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, s1); if (n == JOptionPane.YES_OPTION) { if (cooja.doSaveConfig(true) == null) { return; } } else if (n == JOptionPane.CANCEL_OPTION) { return; } else if (n != JOptionPane.NO_OPTION) { return; } } } if (getSimulation() != null) { doRemoveSimulation(false); } // Clean up resources Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } /* Store frame size and position */ if (isVisualizedInFrame()) { setExternalToolsSetting("FRAME_SCREEN", frame.getGraphicsConfiguration().getDevice().getIDstring()); setExternalToolsSetting("FRAME_POS_X", "" + frame.getLocationOnScreen().x); setExternalToolsSetting("FRAME_POS_Y", "" + frame.getLocationOnScreen().y); if (frame.getExtendedState() == JFrame.MAXIMIZED_BOTH) { setExternalToolsSetting("FRAME_WIDTH", "" + Integer.MAX_VALUE); setExternalToolsSetting("FRAME_HEIGHT", "" + Integer.MAX_VALUE); } else { setExternalToolsSetting("FRAME_WIDTH", "" + frame.getWidth()); setExternalToolsSetting("FRAME_HEIGHT", "" + frame.getHeight()); } } saveExternalToolsUserSettings(); System.exit(exitCode); } // // EXTERNAL TOOLS SETTINGS METHODS //// /** * @return Number of external tools settings */ public static int getExternalToolsSettingsCount() { return externalToolsSettingNames.length; } /** * Get name of external tools setting at given index. * * @param index * Setting index * @return Name */ public static String getExternalToolsSettingName(int index) { return externalToolsSettingNames[index]; } /** * @param name * Name of setting * @return Value */ public static String getExternalToolsSetting(String name) { return getExternalToolsSetting(name, null); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsSetting(String name, String defaultValue) { if (specifiedContikiPath != null && "PATH_CONTIKI".equals(name)) { return specifiedContikiPath; } return currentExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsDefaultSetting(String name, String defaultValue) { return defaultExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param newVal * New value */ public static void setExternalToolsSetting(String name, String newVal) { currentExternalToolsSettings.setProperty(name, newVal); } /** * Load external tools settings from default file. */ public static void loadExternalToolsDefaultSettings() { String osName = System.getProperty("os.name").toLowerCase(); String osArch = System.getProperty("os.arch").toLowerCase(); String filename = null; if (osName.startsWith("win")) { filename = Cooja.EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME; } else if (osName.startsWith("mac os x")) { filename = Cooja.EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME; } else if (osName.startsWith("freebsd")) { filename = Cooja.EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME; } else if (osName.startsWith("linux")) { filename = Cooja.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; if (osArch.startsWith("amd64")) { filename = Cooja.EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME; } } else { logger.warn("Unknown system: " + osName); logger.warn("Using default linux external tools configuration"); filename = Cooja.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; } try { InputStream in = Cooja.class.getResourceAsStream(EXTERNAL_TOOLS_SETTINGS_FILENAME); if (in == null) { throw new FileNotFoundException(filename + " not found"); } Properties settings = new Properties(); settings.load(in); in.close(); in = Cooja.class.getResourceAsStream(filename); if (in == null) { throw new FileNotFoundException(filename + " not found"); } settings.load(in); in.close(); currentExternalToolsSettings = settings; defaultExternalToolsSettings = (Properties) currentExternalToolsSettings.clone(); logger.info("External tools default settings: " + filename); } catch (IOException e) { logger.warn("Error when reading external tools settings from " + filename, e); } finally { if (currentExternalToolsSettings == null) { defaultExternalToolsSettings = new Properties(); currentExternalToolsSettings = new Properties(); } } } /** * Load user values from external properties file */ public static void loadExternalToolsUserSettings() { if (externalToolsUserSettingsFile == null) { return; } try { FileInputStream in = new FileInputStream(externalToolsUserSettingsFile); Properties settings = new Properties(); settings.load(in); in.close(); Enumeration<Object> en = settings.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); setExternalToolsSetting(key, settings.getProperty(key)); } logger.info("External tools user settings: " + externalToolsUserSettingsFile); } catch (FileNotFoundException e) { logger.warn("Error when reading user settings from: " + externalToolsUserSettingsFile); } catch (IOException e) { logger.warn("Error when reading user settings from: " + externalToolsUserSettingsFile); } } /** * Save external tools user settings to file. */ public static void saveExternalToolsUserSettings() { if (isVisualizedInApplet()) { return; } if (externalToolsUserSettingsFileReadOnly) { return; } try { FileOutputStream out = new FileOutputStream(externalToolsUserSettingsFile); Properties differingSettings = new Properties(); Enumeration keyEnum = currentExternalToolsSettings.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); String defaultSetting = getExternalToolsDefaultSetting(key, ""); String currentSetting = currentExternalToolsSettings.getProperty(key, ""); if (!defaultSetting.equals(currentSetting)) { differingSettings.setProperty(key, currentSetting); } } differingSettings.store(out, "Cooja External Tools (User specific)"); out.close(); } catch (FileNotFoundException ex) { // Could not open settings file for writing, aborting logger.warn("Could not save external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } catch (IOException ex) { // Could not open settings file for writing, aborting logger.warn("Error while saving external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } } // // GUI EVENT HANDLER //// private class GUIEventHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("create mote type")) { cooja.doCreateMoteType((Class<? extends MoteType>) ((JMenuItem) e .getSource()).getClientProperty("class")); } else if (e.getActionCommand().equals("add motes")) { cooja.doAddMotes((MoteType) ((JMenuItem) e.getSource()) .getClientProperty("motetype")); } else if (e.getActionCommand().equals("edit paths")) { ExternalToolsDialog.showDialog(Cooja.getTopParentContainer()); } else if (e.getActionCommand().equals("manage extensions")) { COOJAProject[] newProjects = ProjectDirectoriesDialog.showDialog( Cooja.getTopParentContainer(), Cooja.this, getProjects() ); if (newProjects != null) { currentProjects.clear(); for (COOJAProject p: newProjects) { currentProjects.add(p); } try { reparseProjectConfig(); } catch (ParseProjectsException ex) { logger.fatal("Error when loading extensions: " + ex.getMessage(), ex); if (isVisualized()) { JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), "All Cooja extensions could not load.\n\n" + "To manage Cooja extensions:\n" + "Menu->Settings->Cooja extensions", "Reconfigure Cooja extensions", JOptionPane.INFORMATION_MESSAGE); } showErrorDialog(getTopParentContainer(), "Cooja extensions load error", ex, false); } } } else if (e.getActionCommand().equals("configuration wizard")) { ConfigurationWizard.startWizard(Cooja.getTopParentContainer(), Cooja.this); } else { logger.warn("Unhandled action: " + e.getActionCommand()); } } } // // VARIOUS HELP METHODS //// /** * Help method that tries to load and initialize a class with given name. * * @param <N> Class extending given class type * @param classType Class type * @param className Class name * @return Class extending given class type or null if not found */ public <N extends Object> Class<? extends N> tryLoadClass( Object callingObject, Class<N> classType, String className) { if (callingObject != null) { try { return callingObject.getClass().getClassLoader().loadClass(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } try { return Class.forName(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } if (!isVisualizedInApplet()) { try { if (projectDirClassLoader != null) { return projectDirClassLoader.loadClass(className).asSubclass( classType); } } catch (NoClassDefFoundError e) { } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } return null; } private ClassLoader createClassLoader(Collection<COOJAProject> projects) throws ClassLoaderCreationException { return createClassLoader(ClassLoader.getSystemClassLoader(), projects); } public static File findJarFile(File projectDir, String jarfile) { File fp = new File(jarfile); if (!fp.exists()) { fp = new File(projectDir, jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/lib/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "lib/" + jarfile); } return fp.exists() ? fp : null; } private ClassLoader createClassLoader(ClassLoader parent, Collection<COOJAProject> projects) throws ClassLoaderCreationException { if (projects == null || projects.isEmpty()) { return parent; } /* Create class loader from JARs */ ArrayList<URL> urls = new ArrayList<URL>(); for (COOJAProject project: projects) { File projectDir = project.dir; try { urls.add((new File(projectDir, "java")).toURI().toURL()); // Read configuration to check if any JAR files should be loaded ProjectConfig projectConfig = new ProjectConfig(false); projectConfig.appendProjectDir(projectDir); String[] projectJarFiles = projectConfig.getStringArrayValue( Cooja.class, "JARFILES"); if (projectJarFiles != null && projectJarFiles.length > 0) { for (String jarfile : projectJarFiles) { File jarpath = findJarFile(projectDir, jarfile); if (jarpath == null) { throw new FileNotFoundException(jarfile); } urls.add(jarpath.toURI().toURL()); } } } catch (Exception e) { logger.fatal("Error when trying to read JAR-file in " + projectDir + ": " + e); throw (ClassLoaderCreationException) new ClassLoaderCreationException( "Error when trying to read JAR-file in " + projectDir).initCause(e); } } URL[] urlsArray = urls.toArray(new URL[urls.size()]); /* TODO Load from webserver if applet */ return new URLClassLoader(urlsArray, parent); } /** * Help method that returns the description for given object. This method * reads from the object's class annotations if existing. Otherwise it returns * the simple class name of object's class. * * @param object * Object * @return Description */ public static String getDescriptionOf(Object object) { return getDescriptionOf(object.getClass()); } /** * Help method that returns the description for given class. This method reads * from class annotations if existing. Otherwise it returns the simple class * name. * * @param clazz * Class * @return Description */ public static String getDescriptionOf(Class<? extends Object> clazz) { if (clazz.isAnnotationPresent(ClassDescription.class)) { return clazz.getAnnotation(ClassDescription.class).value(); } return clazz.getSimpleName(); } /** * Help method that returns the abstraction level description for given mote type class. * * @param clazz * Class * @return Description */ public static String getAbstractionLevelDescriptionOf(Class<? extends MoteType> clazz) { if (clazz.isAnnotationPresent(AbstractionLevelDescription.class)) { return clazz.getAnnotation(AbstractionLevelDescription.class).value(); } return null; } /** * Load configurations and create a GUI. * * @param args * null */ public static void main(String[] args) { String logConfigFile = null; Long randomSeed = null; for (String element : args) { if (element.startsWith("-log4j=")) { String arg = element.substring("-log4j=".length()); logConfigFile = arg; } } try { // Configure logger if (logConfigFile != null) { if (new File(logConfigFile).exists()) { DOMConfigurator.configure(logConfigFile); } else { System.err.println("Failed to open " + logConfigFile); System.exit(1); } } else if (new File(LOG_CONFIG_FILE).exists()) { DOMConfigurator.configure(LOG_CONFIG_FILE); } else { // Used when starting from jar DOMConfigurator.configure(Cooja.class.getResource("/" + LOG_CONFIG_FILE)); } externalToolsUserSettingsFile = new File(System.getProperty("user.home"), EXTERNAL_TOOLS_USER_SETTINGS_FILENAME); } catch (AccessControlException e) { BasicConfigurator.configure(); externalToolsUserSettingsFile = null; } /* Look and Feel: Nimbus */ setLookAndFeel(); /* Warn at no JAVA_HOME */ String javaHome = System.getenv().get("JAVA_HOME"); if (javaHome == null || javaHome.equals("")) { logger.warn("JAVA_HOME environment variable not set, Cooja motes may not compile"); } // Parse general command arguments for (String element : args) { if (element.startsWith("-contiki=")) { String arg = element.substring("-contiki=".length()); Cooja.specifiedContikiPath = arg; } if (element.startsWith("-external_tools_config=")) { String arg = element.substring("-external_tools_config=".length()); File specifiedExternalToolsConfigFile = new File(arg); if (!specifiedExternalToolsConfigFile.exists()) { logger.fatal("Specified external tools configuration not found: " + specifiedExternalToolsConfigFile); specifiedExternalToolsConfigFile = null; System.exit(1); } else { Cooja.externalToolsUserSettingsFile = specifiedExternalToolsConfigFile; Cooja.externalToolsUserSettingsFileReadOnly = true; } } if (element.startsWith("-random-seed=")) { String arg = element.substring("-random-seed=".length()); try { randomSeed = Long.valueOf(arg); } catch (Exception e) { logger.error("Failed to convert \"" + arg +"\" to an integer."); } } } // Check if simulator should be quick-started if (args.length > 0 && args[0].startsWith("-quickstart=")) { String contikiApp = args[0].substring("-quickstart=".length()); /* Cygwin fix */ if (contikiApp.startsWith("/cygdrive/")) { char driveCharacter = contikiApp.charAt("/cygdrive/".length()); contikiApp = contikiApp.replace("/cygdrive/" + driveCharacter + "/", driveCharacter + ":/"); } Simulation sim = null; if (contikiApp.endsWith(".csc")) { sim = quickStartSimulationConfig(new File(contikiApp), true, randomSeed); } else { if (contikiApp.endsWith(".cooja")) { contikiApp = contikiApp.substring(0, contikiApp.length() - ".cooja".length()); } if (!contikiApp.endsWith(".c")) { contikiApp += ".c"; } sim = quickStartSimulation(contikiApp); } if (sim == null) { System.exit(1); } } else if (args.length > 0 && args[0].startsWith("-nogui=")) { /* Load simulation */ String config = args[0].substring("-nogui=".length()); File configFile = new File(config); Simulation sim = quickStartSimulationConfig(configFile, false, randomSeed); if (sim == null) { System.exit(1); } Cooja gui = sim.getCooja(); /* Make sure at least one test editor is controlling the simulation */ boolean hasEditor = false; for (Plugin startedPlugin : gui.startedPlugins) { if (startedPlugin instanceof ScriptRunner) { hasEditor = true; break; } } /* Backwards compatibility: * simulation has no test editor, but has external (old style) test script. * We will manually start a test editor from here. */ if (!hasEditor) { File scriptFile = new File(config.substring(0, config.length()-4) + ".js"); if (scriptFile.exists()) { logger.info("Detected old simulation test, starting test editor manually from: " + scriptFile); ScriptRunner plugin = (ScriptRunner) gui.tryStartPlugin(ScriptRunner.class, gui, sim, null); if (plugin == null) { System.exit(1); } plugin.updateScript(scriptFile); try { plugin.setScriptActive(true); } catch (Exception e) { logger.fatal("Error: " + e.getMessage(), e); System.exit(1); } } else { logger.fatal("No test editor controlling simulation, aborting"); System.exit(1); } } sim.setSpeedLimit(null); sim.startSimulation(); } else if (args.length > 0 && args[0].startsWith("-applet")) { String tmpWebPath=null, tmpBuildPath=null, tmpEsbFirmware=null, tmpSkyFirmware=null; for (int i = 1; i < args.length; i++) { if (args[i].startsWith("-web=")) { tmpWebPath = args[i].substring("-web=".length()); } else if (args[i].startsWith("-sky_firmware=")) { tmpSkyFirmware = args[i].substring("-sky_firmware=".length()); } else if (args[i].startsWith("-esb_firmware=")) { tmpEsbFirmware = args[i].substring("-esb_firmware=".length()); } else if (args[i].startsWith("-build=")) { tmpBuildPath = args[i].substring("-build=".length()); } } // Applet start-up final String webPath = tmpWebPath, buildPath = tmpBuildPath; final String skyFirmware = tmpSkyFirmware, esbFirmware = tmpEsbFirmware; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); applet = CoojaApplet.applet; Cooja gui = new Cooja(desktop); Cooja.setExternalToolsSetting("PATH_CONTIKI_BUILD", buildPath); Cooja.setExternalToolsSetting("PATH_CONTIKI_WEB", webPath); Cooja.setExternalToolsSetting("SKY_FIRMWARE", skyFirmware); Cooja.setExternalToolsSetting("ESB_FIRMWARE", esbFirmware); configureApplet(gui, false); } }); } else { // Frame start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); frame = new JFrame(WINDOW_TITLE); Cooja gui = new Cooja(desktop); configureFrame(gui, false); } }); } } /** * Loads a simulation configuration from given file. * * When loading Contiki mote types, the libraries must be recompiled. User may * change mote type settings at this point. * * @see #saveSimulationConfig(File) * @param file * File to read * @return New simulation or null if recompiling failed or aborted * @throws UnsatisfiedLinkError * If associated libraries could not be loaded */ public Simulation loadSimulationConfig(File file, boolean quick, Long manualRandomSeed) throws UnsatisfiedLinkError, SimulationCreationException { this.currentConfigFile = file; /* Used to generate config relative paths */ try { this.currentConfigFile = this.currentConfigFile.getCanonicalFile(); } catch (IOException e) { } try { SAXBuilder builder = new SAXBuilder(); InputStream in = new FileInputStream(file); if (file.getName().endsWith(".gz")) { in = new GZIPInputStream(in); } Document doc = builder.build(in); Element root = doc.getRootElement(); in.close(); return loadSimulationConfig(root, quick, manualRandomSeed); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException("Config not wellformed").initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException("Load simulation error").initCause(e); } } public Simulation loadSimulationConfig(Element root, boolean quick, Long manualRandomSeed) throws SimulationCreationException { Simulation newSim = null; try { // Check that config file version is correct if (!root.getName().equals("simconf")) { logger.fatal("Not a valid Cooja simulation config."); return null; } /* Verify extension directories */ boolean projectsOk = verifyProjects(root.getChildren(), !quick); /* GENERATE UNIQUE MOTE TYPE IDENTIFIERS */ root.detach(); String configString = new XMLOutputter().outputString(new Document(root)); /* Locate Contiki mote types in config */ Properties moteTypeIDMappings = new Properties(); String identifierExtraction = ContikiMoteType.class.getName() + "[\\s\\n]*<identifier>([^<]*)</identifier>"; Matcher matcher = Pattern.compile(identifierExtraction).matcher(configString); while (matcher.find()) { moteTypeIDMappings.setProperty(matcher.group(1), ""); } /* Create old to new identifier mappings */ Enumeration<Object> existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); MoteType[] existingMoteTypes = null; if (mySimulation != null) { existingMoteTypes = mySimulation.getMoteTypes(); } ArrayList<Object> reserved = new ArrayList<Object>(); reserved.addAll(moteTypeIDMappings.keySet()); reserved.addAll(moteTypeIDMappings.values()); String newID = ContikiMoteType.generateUniqueMoteTypeID(existingMoteTypes, reserved); moteTypeIDMappings.setProperty(existingIdentifier, newID); } /* Create new config */ existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); configString = configString.replaceAll( "<identifier>" + existingIdentifier + "</identifier>", "<identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</identifier>"); configString = configString.replaceAll( "<motetype_identifier>" + existingIdentifier + "</motetype_identifier>", "<motetype_identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</motetype_identifier>"); } /* Replace existing config */ root = new SAXBuilder().build(new StringReader(configString)).getRootElement(); // Create new simulation from config for (Object element : root.getChildren()) { if (((Element) element).getName().equals("simulation")) { Collection<Element> config = ((Element) element).getChildren(); newSim = new Simulation(this); System.gc(); boolean createdOK = newSim.setConfigXML(config, !quick, manualRandomSeed); if (!createdOK) { logger.info("Simulation not loaded"); return null; } } } // Restart plugins from config setPluginsConfigXML(root.getChildren(), newSim, !quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "No access to configuration file: " + e.getMessage()).initCause(e); } catch (MoteTypeCreationException e) { throw (SimulationCreationException) new SimulationCreationException( "Mote type creation error: " + e.getMessage()).initCause(e); } catch (Exception e) { throw (SimulationCreationException) new SimulationCreationException( "Unknown error: " + e.getMessage()).initCause(e); } return newSim; } /** * Saves current simulation configuration to given file and notifies * observers. * * @see #loadSimulationConfig(File, boolean) * @param file * File to write */ public void saveSimulationConfig(File file) { this.currentConfigFile = file; /* Used to generate config relative paths */ try { this.currentConfigFile = this.currentConfigFile.getCanonicalFile(); } catch (IOException e) { } try { // Create and write to document Document doc = new Document(extractSimulationConfig()); OutputStream out = new FileOutputStream(file); if (file.getName().endsWith(".gz")) { out = new GZIPOutputStream(out); } XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); logger.info("Saved to file: " + file.getAbsolutePath()); } catch (Exception e) { logger.warn("Exception while saving simulation config: " + e); e.printStackTrace(); } } public Element extractSimulationConfig() { // Create simulation config Element root = new Element("simconf"); /* Store extension directories meta data */ for (COOJAProject project: currentProjects) { Element projectElement = new Element("project"); projectElement.addContent(createPortablePath(project.dir).getPath().replaceAll("\\\\", "/")); projectElement.setAttribute("EXPORT", "discard"); root.addContent(projectElement); } Element simulationElement = new Element("simulation"); simulationElement.addContent(mySimulation.getConfigXML()); root.addContent(simulationElement); // Create started plugins config Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } return root; } /** * Returns started plugins config. * * @return Config or null */ public Collection<Element> getPluginsConfigXML() { ArrayList<Element> config = new ArrayList<Element>(); Element pluginElement, pluginSubElement; /* Loop over all plugins */ for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); // Ignore GUI plugins if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { continue; } pluginElement = new Element("plugin"); pluginElement.setText(startedPlugin.getClass().getName()); // Create mote argument config (if mote plugin) if (pluginType == PluginType.MOTE_PLUGIN) { pluginSubElement = new Element("mote_arg"); Mote taggedMote = ((MotePlugin) startedPlugin).getMote(); for (int moteNr = 0; moteNr < mySimulation.getMotesCount(); moteNr++) { if (mySimulation.getMote(moteNr) == taggedMote) { pluginSubElement.setText(Integer.toString(moteNr)); pluginElement.addContent(pluginSubElement); break; } } } // Create plugin specific configuration Collection<Element> pluginXML = startedPlugin.getConfigXML(); if (pluginXML != null) { pluginSubElement = new Element("plugin_config"); pluginSubElement.addContent(pluginXML); pluginElement.addContent(pluginSubElement); } // If plugin is visualizer plugin, create visualization arguments if (startedPlugin.getCooja() != null) { JInternalFrame pluginFrame = startedPlugin.getCooja(); pluginSubElement = new Element("width"); pluginSubElement.setText("" + pluginFrame.getSize().width); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("z"); pluginSubElement.setText("" + getDesktopPane().getComponentZOrder(pluginFrame)); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("height"); pluginSubElement.setText("" + pluginFrame.getSize().height); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_x"); pluginSubElement.setText("" + pluginFrame.getLocation().x); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_y"); pluginSubElement.setText("" + pluginFrame.getLocation().y); pluginElement.addContent(pluginSubElement); if (pluginFrame.isIcon()) { pluginSubElement = new Element("minimized"); pluginSubElement.setText("" + true); pluginElement.addContent(pluginSubElement); } } config.add(pluginElement); } return config; } public boolean verifyProjects(Collection<Element> configXML, boolean visAvailable) { boolean allOk = true; /* Match current extensions against extensions in simulation config */ for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("project")) { File projectFile = restorePortablePath(new File(pluginElement.getText())); try { projectFile = projectFile.getCanonicalFile(); } catch (IOException e) { } boolean found = false; for (COOJAProject currentProject: currentProjects) { if (projectFile.getPath().replaceAll("\\\\", "/"). equals(currentProject.dir.getPath().replaceAll("\\\\", "/"))) { found = true; break; } } if (!found) { logger.warn("Loaded simulation may depend on not found extension: '" + projectFile + "'"); allOk = false; } } } return allOk; } /** * Starts plugins with arguments in given config. * * @param configXML * Config XML elements * @param simulation * Simulation on which to start plugins * @return True if all plugins started, false otherwise */ public boolean setPluginsConfigXML(Collection<Element> configXML, Simulation simulation, boolean visAvailable) { for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("plugin")) { // Read plugin class String pluginClassName = pluginElement.getText().trim(); /* Backwards compatibility: se.sics -> org.contikios */ if (pluginClassName.startsWith("se.sics")) { pluginClassName = pluginClassName.replaceFirst("se\\.sics", "org.contikios"); } /* Backwards compatibility: old visualizers were replaced */ if (pluginClassName.equals("org.contikios.cooja.plugins.VisUDGM") || pluginClassName.equals("org.contikios.cooja.plugins.VisBattery") || pluginClassName.equals("org.contikios.cooja.plugins.VisTraffic") || pluginClassName.equals("org.contikios.cooja.plugins.VisState") || pluginClassName.equals("org.contikios.cooja.plugins.VisUDGM")) { logger.warn("Old simulation config detected: visualizers have been remade"); pluginClassName = "org.contikios.cooja.plugins.Visualizer"; } Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass == null) { logger.fatal("Could not load plugin class: " + pluginClassName); return false; } // Parse plugin mote argument (if any) Mote mote = null; for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("mote_arg")) { int moteNr = Integer.parseInt(pluginSubElement.getText()); if (moteNr >= 0 && moteNr < simulation.getMotesCount()) { mote = simulation.getMote(moteNr); } } } /* Start plugin */ final Plugin startedPlugin = tryStartPlugin(pluginClass, this, simulation, mote, false); if (startedPlugin == null) { continue; } /* Apply plugin specific configuration */ for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("plugin_config")) { startedPlugin.setConfigXML(pluginSubElement.getChildren(), visAvailable); } } /* Activate plugin */ startedPlugin.startPlugin(); /* If Cooja not visualized, ignore window configuration */ if (startedPlugin.getCooja() == null) { continue; } // If plugin is visualizer plugin, parse visualization arguments new RunnableInEDT<Boolean>() { public Boolean work() { Dimension size = new Dimension(100, 100); Point location = new Point(100, 100); for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("width")) { size.width = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setSize(size); } else if (pluginSubElement.getName().equals("height")) { size.height = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setSize(size); } else if (pluginSubElement.getName().equals("z")) { int zOrder = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().putClientProperty("zorder", zOrder); } else if (pluginSubElement.getName().equals("location_x")) { location.x = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setLocation(location); } else if (pluginSubElement.getName().equals("location_y")) { location.y = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setLocation(location); } else if (pluginSubElement.getName().equals("minimized")) { boolean minimized = Boolean.parseBoolean(pluginSubElement.getText()); final JInternalFrame pluginGUI = startedPlugin.getCooja(); if (minimized && pluginGUI != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { pluginGUI.setIcon(true); } catch (PropertyVetoException e) { } }; }); } } } showPlugin(startedPlugin); return true; } }.invokeAndWait(); } } /* Z order visualized plugins */ try { for (int z=0; z < getDesktopPane().getAllFrames().length; z++) { for (JInternalFrame plugin : getDesktopPane().getAllFrames()) { if (plugin.getClientProperty("zorder") == null) { continue; } int zOrder = ((Integer) plugin.getClientProperty("zorder")).intValue(); if (zOrder != z) { continue; } getDesktopPane().setComponentZOrder(plugin, zOrder); if (z == 0) { plugin.setSelected(true); } plugin.putClientProperty("zorder", null); break; } getDesktopPane().repaint(); } } catch (Exception e) { } return true; } public class ParseProjectsException extends Exception { private static final long serialVersionUID = 1508168026300714850L; public ParseProjectsException(String message) { super(message); } } public class ClassLoaderCreationException extends Exception { private static final long serialVersionUID = 1578001681266277774L; public ClassLoaderCreationException(String message) { super(message); } } public class SimulationCreationException extends Exception { private static final long serialVersionUID = -2414899187405770448L; public SimulationCreationException(String message) { super(message); } } public class PluginConstructionException extends Exception { private static final long serialVersionUID = 8004171223353676751L; public PluginConstructionException(String message) { super(message); } } /** * A simple error dialog with compilation output and stack trace. * * @param parentComponent * Parent component * @param title * Title of error window * @param exception * Exception causing window to be shown * @param retryAvailable * If true, a retry option is presented * @return Retry failed operation */ public static boolean showErrorDialog(final Component parentComponent, final String title, final Throwable exception, final boolean retryAvailable) { return new RunnableInEDT<Boolean>() { public Boolean work() { JTabbedPane tabbedPane = new JTabbedPane(); final JDialog errorDialog; if (parentComponent instanceof Dialog) { errorDialog = new JDialog((Dialog) parentComponent, title, true); } else if (parentComponent instanceof Frame) { errorDialog = new JDialog((Frame) parentComponent, title, true); } else { errorDialog = new JDialog((Frame) null, title); } Box buttonBox = Box.createHorizontalBox(); if (exception != null) { /* Contiki error */ if (exception instanceof ContikiError) { String contikiError = ((ContikiError) exception).getContikiError(); MessageList list = new MessageList(); for (String l: contikiError.split("\n")) { list.addMessage(l); } list.addPopupMenuItem(null, true); tabbedPane.addTab("Contiki error", new JScrollPane(list)); } /* Compilation output */ MessageList compilationOutput = null; if (exception instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception).getCompilationOutput(); } else if (exception.getCause() != null && exception.getCause() instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception.getCause()).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception.getCause()).getCompilationOutput(); } if (compilationOutput != null) { compilationOutput.addPopupMenuItem(null, true); tabbedPane.addTab("Compilation output", new JScrollPane(compilationOutput)); } /* Stack trace */ MessageList stackTrace = new MessageList(); PrintStream printStream = stackTrace.getInputStream(MessageList.NORMAL); exception.printStackTrace(printStream); stackTrace.addPopupMenuItem(null, true); tabbedPane.addTab("Java stack trace", new JScrollPane(stackTrace)); /* Exception message */ buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(new JLabel(exception.getMessage())); buttonBox.add(Box.createHorizontalStrut(10)); } buttonBox.add(Box.createHorizontalGlue()); if (retryAvailable) { Action retryAction = new AbstractAction() { private static final long serialVersionUID = 2370456199250998435L; public void actionPerformed(ActionEvent e) { errorDialog.setTitle("-RETRY-"); errorDialog.dispose(); } }; JButton retryButton = new JButton(retryAction); retryButton.setText("Retry Ctrl+R"); buttonBox.add(retryButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK, false), "retry"); errorDialog.getRootPane().getActionMap().put("retry", retryAction); } AbstractAction closeAction = new AbstractAction(){ private static final long serialVersionUID = 6225539435993362733L; public void actionPerformed(ActionEvent e) { errorDialog.dispose(); } }; JButton closeButton = new JButton(closeAction); closeButton.setText("Close"); buttonBox.add(closeButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "close"); errorDialog.getRootPane().getActionMap().put("close", closeAction); errorDialog.getRootPane().setDefaultButton(closeButton); errorDialog.getContentPane().add(BorderLayout.CENTER, tabbedPane); errorDialog.getContentPane().add(BorderLayout.SOUTH, buttonBox); errorDialog.setSize(700, 500); errorDialog.setLocationRelativeTo(parentComponent); errorDialog.setVisible(true); /* BLOCKS */ if (errorDialog.getTitle().equals("-RETRY-")) { return true; } return false; } }.invokeAndWait(); } private static void showWarningsDialog(final Frame parent, final String[] warnings) { new RunnableInEDT<Boolean>() { public Boolean work() { final JDialog dialog = new JDialog(parent, "Compilation warnings", false); Box buttonBox = Box.createHorizontalBox(); /* Warnings message list */ MessageList compilationOutput = new MessageList(); for (String w: warnings) { compilationOutput.addMessage(w, MessageList.ERROR); } compilationOutput.addPopupMenuItem(null, true); /* Checkbox */ buttonBox.add(Box.createHorizontalGlue()); JCheckBox hideButton = new JCheckBox("Hide compilation warnings", false); hideButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Cooja.setExternalToolsSetting("HIDE_WARNINGS", "" + ((JCheckBox)e.getSource()).isSelected()); }; }); buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(hideButton); /* Close on escape */ AbstractAction closeAction = new AbstractAction(){ private static final long serialVersionUID = 2646163984382201634L; public void actionPerformed(ActionEvent e) { dialog.dispose(); } }; InputMap inputMap = dialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "close"); dialog.getRootPane().getActionMap().put("close", closeAction); /* Layout */ dialog.getContentPane().add(BorderLayout.CENTER, new JScrollPane(compilationOutput)); dialog.getContentPane().add(BorderLayout.SOUTH, buttonBox); dialog.setSize(700, 500); dialog.setLocationRelativeTo(parent); dialog.setVisible(true); return true; } }.invokeAndWait(); } /** * Runs work method in event dispatcher thread. * Worker method returns a value. * * @author Fredrik Osterlind */ public static abstract class RunnableInEDT<T> { private T val; /** * Work method to be implemented. * * @return Return value */ public abstract T work(); /** * Runs worker method in event dispatcher thread. * * @see #work() * @return Worker method return value */ public T invokeAndWait() { if(java.awt.EventQueue.isDispatchThread()) { return RunnableInEDT.this.work(); } try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { val = RunnableInEDT.this.work(); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return val; } } /** * This method can be used by various different modules in the simulator to * indicate for example that a mote has been selected. All mote highlight * listeners will be notified. An example application of mote highlightinh is * a simulator visualizer that highlights the mote. * * @see #addMoteHighlightObserver(Observer) * @param m * Mote to highlight */ public void signalMoteHighlight(Mote m) { moteHighlightObservable.setChangedAndNotify(m); } /** * Adds directed relation between given motes. * * @param source Source mote * @param dest Destination mote */ public void addMoteRelation(Mote source, Mote dest) { addMoteRelation(source, dest, null); } /** * Adds directed relation between given motes. * * @param source Source mote * @param dest Destination mote * @param color The color to use when visualizing the mote relation */ public void addMoteRelation(Mote source, Mote dest, Color color) { if (source == null || dest == null) { return; } removeMoteRelation(source, dest); /* Unique relations */ moteRelations.add(new MoteRelation(source, dest, color)); moteRelationObservable.setChangedAndNotify(); } /** * Removes the relations between given motes. * * @param source Source mote * @param dest Destination mote */ public void removeMoteRelation(Mote source, Mote dest) { if (source == null || dest == null) { return; } MoteRelation[] arr = getMoteRelations(); for (MoteRelation r: arr) { if (r.source == source && r.dest == dest) { moteRelations.remove(r); /* Relations are unique */ moteRelationObservable.setChangedAndNotify(); break; } } } /** * @return All current mote relations. * * @see #addMoteRelationsObserver(Observer) */ public MoteRelation[] getMoteRelations() { return moteRelations.toArray(new MoteRelation[moteRelations.size()]); } /** * Adds mote relation observer. * Typically used by visualizer plugins. * * @param newObserver Observer */ public void addMoteRelationsObserver(Observer newObserver) { moteRelationObservable.addObserver(newObserver); } /** * Removes mote relation observer. * Typically used by visualizer plugins. * * @param observer Observer */ public void deleteMoteRelationsObserver(Observer observer) { moteRelationObservable.deleteObserver(observer); } /** * Tries to convert given file to be "portable". * The portable path is either relative to Contiki, or to the configuration (.csc) file. * * If this method fails, it returns the original file. * * @param file Original file * @return Portable file, or original file is conversion failed */ public File createPortablePath(File file) { return createPortablePath(file, true); } public File createPortablePath(File file, boolean allowConfigRelativePaths) { File portable = null; portable = createContikiRelativePath(file); if (portable != null) { /*logger.info("Generated Contiki relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } if (allowConfigRelativePaths) { portable = createConfigRelativePath(file); if (portable != null) { /*logger.info("Generated config relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } } logger.warn("Path is not portable: '" + file.getPath()); return file; } /** * Tries to restore a previously "portable" file to be "absolute". * If the given file already exists, no conversion is performed. * * @see #createPortablePath(File) * @param file Portable file * @return Absolute file */ public File restorePortablePath(File file) { if (file == null || file.exists()) { /* No conversion possible/needed */ return file; } File absolute = null; absolute = restoreContikiRelativePath(file); if (absolute != null) { /*logger.info("Restored Contiki relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } absolute = restoreConfigRelativePath(file); if (absolute != null) { /*logger.info("Restored config relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } /*logger.info("Portable path was not restored: '" + file.getPath());*/ return file; } private final static String[][] PATH_IDENTIFIER = { {"[CONTIKI_DIR]","PATH_CONTIKI",""}, {"[COOJA_DIR]","PATH_COOJA","/tools/cooja"}, {"[APPS_DIR]","PATH_APPS","/tools/cooja/apps"} }; private File createContikiRelativePath(File file) { try { int elem = PATH_IDENTIFIER.length; File path[] = new File [elem]; String canonicals[] = new String[elem]; int match = -1; int mlength = 0; String fileCanonical = file.getCanonicalPath(); //No so nice, but goes along with GUI.getExternalToolsSetting String defp = Cooja.getExternalToolsSetting("PATH_CONTIKI", null); for(int i = 0; i < elem; i++){ path[i] = new File(Cooja.getExternalToolsSetting(PATH_IDENTIFIER[i][1], defp + PATH_IDENTIFIER[i][2])); canonicals[i] = path[i].getCanonicalPath(); if (fileCanonical.startsWith(canonicals[i])){ if(mlength < canonicals[i].length()){ mlength = canonicals[i].length(); match = i; } } } if(match == -1) return null; /* Replace Contiki's canonical path with Contiki identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(canonicals[match]), java.util.regex.Matcher.quoteReplacement(PATH_IDENTIFIER[match][0])); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreContikiRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to Contiki relative path: " + e1.getMessage());*/ return null; } } private File restoreContikiRelativePath(File portable) { int elem = PATH_IDENTIFIER.length; File path = null; String canonical = null; try { String portablePath = portable.getPath(); int i = 0; //logger.info("PPATH: " + portablePath); for(; i < elem; i++){ if (portablePath.startsWith(PATH_IDENTIFIER[i][0])) break; } if(i == elem) return null; //logger.info("Found: " + PATH_IDENTIFIER[i][0]); //No so nice, but goes along with GUI.getExternalToolsSetting String defp = Cooja.getExternalToolsSetting("PATH_CONTIKI", null); path = new File(Cooja.getExternalToolsSetting(PATH_IDENTIFIER[i][1], defp + PATH_IDENTIFIER[i][2])); //logger.info("Config: " + PATH_IDENTIFIER[i][1] + ", " + defp + PATH_IDENTIFIER[i][2] + " = " + path.toString()); canonical = path.getCanonicalPath(); File absolute = new File(portablePath.replace(PATH_IDENTIFIER[i][0], canonical)); if(!absolute.exists()){ logger.warn("Replaced " + portable + " with " + absolute.toString() + " (default: "+ defp + PATH_IDENTIFIER[i][2] +"), but could not find it. This does not have to be an error, as the file might be created later."); } return absolute; } catch (IOException e) { return null; } } private final static String PATH_CONFIG_IDENTIFIER = "[CONFIG_DIR]"; public File currentConfigFile = null; /* Used to generate config relative paths */ private File createConfigRelativePath(File file) { String id = PATH_CONFIG_IDENTIFIER; if (currentConfigFile == null) { return null; } try { File configPath = currentConfigFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String configCanonical = configPath.getCanonicalPath(); String fileCanonical = file.getCanonicalPath(); if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow one parent directory */ File parent = new File(configCanonical).getParentFile(); if (parent != null) { configCanonical = parent.getCanonicalPath(); id += "/.."; } } if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow two parent directories */ File parent = new File(configCanonical).getParentFile(); if (parent != null) { configCanonical = parent.getCanonicalPath(); id += "/.."; } } if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow three parent directories */ File parent = new File(configCanonical).getParentFile(); if (parent != null) { configCanonical = parent.getCanonicalPath(); id += "/.."; } } if (!fileCanonical.startsWith(configCanonical)) { /* File is not in a config subdirectory */ /*logger.info("File is not in a config subdirectory: " + file.getAbsolutePath());*/ return null; } /* Replace config's canonical path with config identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(configCanonical), java.util.regex.Matcher.quoteReplacement(id)); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreConfigRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to config relative path: " + e1.getMessage());*/ return null; } } private File restoreConfigRelativePath(File portable) { return restoreConfigRelativePath(currentConfigFile, portable); } public static File restoreConfigRelativePath(File configFile, File portable) { if (configFile == null) { return null; } File configPath = configFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String portablePath = portable.getPath(); if (!portablePath.startsWith(PATH_CONFIG_IDENTIFIER)) { return null; } File absolute = new File(portablePath.replace(PATH_CONFIG_IDENTIFIER, configPath.getAbsolutePath())); return absolute; } private static JProgressBar PROGRESS_BAR = null; private static ArrayList<String> PROGRESS_WARNINGS = new ArrayList<String>(); public static void setProgressMessage(String msg) { setProgressMessage(msg, MessageList.NORMAL); } public static void setProgressMessage(String msg, int type) { if (PROGRESS_BAR != null && PROGRESS_BAR.isShowing()) { PROGRESS_BAR.setString(msg); PROGRESS_BAR.setStringPainted(true); } if (type != MessageList.NORMAL) { PROGRESS_WARNINGS.add(msg); } } /** * Load quick help for given object or identifier. Note that this method does not * show the quick help pane. * * @param obj If string: help identifier. Else, the class name of the argument * is used as help identifier. */ public void loadQuickHelp(final Object obj) { if (obj == null) { return; } String key; if (obj instanceof String) { key = (String) obj; } else { key = obj.getClass().getName(); } String help = null; if (obj instanceof HasQuickHelp) { help = ((HasQuickHelp) obj).getQuickHelp(); } else { if (quickHelpProperties == null) { /* Load quickhelp.txt */ try { quickHelpProperties = new Properties(); quickHelpProperties.load(new FileReader("quickhelp.txt")); } catch (Exception e) { quickHelpProperties = null; help = "<html><b>Failed to read quickhelp.txt:</b><p>" + e.getMessage() + "</html>"; } } if (quickHelpProperties != null) { help = quickHelpProperties.getProperty(key); } } if (help != null) { quickHelpTextPane.setText("<html>" + help + "</html>"); } else { quickHelpTextPane.setText( "<html><b>" + getDescriptionOf(obj) +"</b>" + "<p>No help available</html>"); } quickHelpTextPane.setCaretPosition(0); } /* GUI actions */ abstract class GUIAction extends AbstractAction { private static final long serialVersionUID = 6946179457635198477L; public GUIAction(String name) { super(name); } public GUIAction(String name, int nmenomic) { this(name); putValue(Action.MNEMONIC_KEY, nmenomic); } public GUIAction(String name, KeyStroke accelerator) { this(name); putValue(Action.ACCELERATOR_KEY, accelerator); } public GUIAction(String name, int nmenomic, KeyStroke accelerator) { this(name, nmenomic); putValue(Action.ACCELERATOR_KEY, accelerator); } public abstract boolean shouldBeEnabled(); } GUIAction newSimulationAction = new GUIAction("New simulation...", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)) { private static final long serialVersionUID = 5053703908505299911L; public void actionPerformed(ActionEvent e) { cooja.doCreateSimulation(true); } public boolean shouldBeEnabled() { return true; } }; GUIAction closeSimulationAction = new GUIAction("Close simulation", KeyEvent.VK_C) { private static final long serialVersionUID = -4783032948880161189L; public void actionPerformed(ActionEvent e) { cooja.doRemoveSimulation(true); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction reloadSimulationAction = new GUIAction("Reload with same random seed", KeyEvent.VK_K, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK)) { private static final long serialVersionUID = 66579555555421977L; public void actionPerformed(ActionEvent e) { if (getSimulation() == null) { /* Reload last opened simulation */ final File file = getLastOpenedFile(); new Thread(new Runnable() { public void run() { cooja.doLoadConfig(true, true, file, null); } }).start(); return; } /* Reload current simulation */ long seed = getSimulation().getRandomSeed(); reloadCurrentSimulation(getSimulation().isRunning(), seed); } public boolean shouldBeEnabled() { return true; } }; GUIAction reloadRandomSimulationAction = new GUIAction("Reload with new random seed", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)) { private static final long serialVersionUID = -4494402222740250203L; public void actionPerformed(ActionEvent e) { /* Replace seed before reloading */ if (getSimulation() != null) { getSimulation().setRandomSeed(getSimulation().getRandomSeed()+1); reloadSimulationAction.actionPerformed(null); } } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction saveSimulationAction = new GUIAction("Save simulation as...", KeyEvent.VK_S) { private static final long serialVersionUID = 1132582220401954286L; public void actionPerformed(ActionEvent e) { cooja.doSaveConfig(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return getSimulation() != null; } }; /* GUIAction closePluginsAction = new GUIAction("Close all plugins") { private static final long serialVersionUID = -37575622808266989L; public void actionPerformed(ActionEvent e) { Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } } public boolean shouldBeEnabled() { return !startedPlugins.isEmpty(); } };*/ GUIAction exportExecutableJARAction = new GUIAction("Export simulation...") { private static final long serialVersionUID = -203601967460630049L; public void actionPerformed(ActionEvent e) { getSimulation().stopSimulation(); /* Info message */ String[] options = new String[] { "OK", "Cancel" }; int n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "This function attempts to build an executable Cooja JAR from the current simulation.\n" + "The JAR will contain all simulation dependencies, including extension JAR files and mote firmware files.\n" + "\nExecutable simulations can be used to run already prepared simulations on several computers.\n" + "\nThis is an experimental feature.", "Export simulation to executable JAR", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (n != JOptionPane.OK_OPTION) { return; } /* Select output file */ JFileChooser fc = new JFileChooser(); FileFilter jarFilter = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".jar")) { return true; } return false; } public String getDescription() { return "Java archive"; } public String toString() { return ".jar"; } }; fc.setFileFilter(jarFilter); File suggest = new File(getExternalToolsSetting("EXECUTE_JAR_LAST", "cooja_simulation.jar")); fc.setSelectedFile(suggest); int returnVal = fc.showSaveDialog(Cooja.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File outputFile = fc.getSelectedFile(); if (outputFile.exists()) { options = new String[] { "Overwrite", "Cancel" }; n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n != JOptionPane.YES_OPTION) { return; } outputFile.delete(); } final File finalOutputFile = outputFile; setExternalToolsSetting("EXECUTE_JAR_LAST", outputFile.getPath()); new Thread() { public void run() { try { ExecuteJAR.buildExecutableJAR(Cooja.this, finalOutputFile); } catch (RuntimeException ex) { JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } }.start(); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction exitCoojaAction = new GUIAction("Exit", 'x') { private static final long serialVersionUID = 7523822251658687665L; public void actionPerformed(ActionEvent e) { cooja.doQuit(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return true; } }; GUIAction startStopSimulationAction = new GUIAction("Start simulation", KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)) { private static final long serialVersionUID = 6750107157493939710L; public void actionPerformed(ActionEvent e) { /* Start/Stop current simulation */ Simulation s = getSimulation(); if (s == null) { return; } if (s.isRunning()) { s.stopSimulation(); } else { s.startSimulation(); } } public void setEnabled(boolean newValue) { if (getSimulation() == null) { putValue(NAME, "Start simulation"); } else if (getSimulation().isRunning()) { putValue(NAME, "Pause simulation"); } else { putValue(NAME, "Start simulation"); } super.setEnabled(newValue); } public boolean shouldBeEnabled() { return getSimulation() != null && getSimulation().isRunnable(); } }; class StartPluginGUIAction extends GUIAction { private static final long serialVersionUID = 7368495576372376196L; public StartPluginGUIAction(String name) { super(name); } public void actionPerformed(final ActionEvent e) { new Thread(new Runnable() { public void run() { Class<Plugin> pluginClass = (Class<Plugin>) ((JMenuItem) e.getSource()).getClientProperty("class"); Mote mote = (Mote) ((JMenuItem) e.getSource()).getClientProperty("mote"); tryStartPlugin(pluginClass, cooja, mySimulation, mote); } }).start(); } public boolean shouldBeEnabled() { return getSimulation() != null; } } GUIAction removeAllMotesAction = new GUIAction("Remove all motes") { private static final long serialVersionUID = 4709776747913364419L; public void actionPerformed(ActionEvent e) { Simulation s = getSimulation(); if (s.isRunning()) { s.stopSimulation(); } while (s.getMotesCount() > 0) { s.removeMote(getSimulation().getMote(0)); } } public boolean shouldBeEnabled() { Simulation s = getSimulation(); return s != null && s.getMotesCount() > 0; } }; GUIAction showQuickHelpAction = new GUIAction("Quick help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { private static final long serialVersionUID = 3151729036597971681L; public void actionPerformed(ActionEvent e) { if (!(e.getSource() instanceof JCheckBoxMenuItem)) { return; } boolean show = ((JCheckBoxMenuItem) e.getSource()).isSelected(); quickHelpTextPane.setVisible(show); quickHelpScroll.setVisible(show); setExternalToolsSetting("SHOW_QUICKHELP", new Boolean(show).toString()); ((JPanel)frame.getContentPane()).revalidate(); updateDesktopSize(getDesktopPane()); } public boolean shouldBeEnabled() { return true; } }; GUIAction showGettingStartedAction = new GUIAction("Getting started") { private static final long serialVersionUID = 2382848024856978524L; public void actionPerformed(ActionEvent e) { loadQuickHelp("GETTING_STARTED"); JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } public boolean shouldBeEnabled() { return true; } }; GUIAction showKeyboardShortcutsAction = new GUIAction("Keyboard shortcuts") { private static final long serialVersionUID = 2382848024856978524L; public void actionPerformed(ActionEvent e) { loadQuickHelp("KEYBOARD_SHORTCUTS"); JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } public boolean shouldBeEnabled() { return true; } }; GUIAction showBufferSettingsAction = new GUIAction("Buffer sizes...") { private static final long serialVersionUID = 7018661735211901837L; public void actionPerformed(ActionEvent e) { if (mySimulation == null) { return; } BufferSettings.showDialog(myDesktopPane, mySimulation); } public boolean shouldBeEnabled() { return mySimulation != null; } }; }
tools/cooja/java/org/contikios/cooja/Cooja.java
/* * Copyright (c) 2006, Swedish Institute of Computer Science. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of the * Institute nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.contikios.cooja; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.Point; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyVetoException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessControlException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.Properties; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultDesktopManager; import javax.swing.InputMap; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.filechooser.FileFilter; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.xml.DOMConfigurator; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.contikios.cooja.MoteType.MoteTypeCreationException; import org.contikios.cooja.VisPlugin.PluginRequiresVisualizationException; import org.contikios.cooja.contikimote.ContikiMoteType; import org.contikios.cooja.dialogs.AddMoteDialog; import org.contikios.cooja.dialogs.BufferSettings; import org.contikios.cooja.dialogs.ConfigurationWizard; import org.contikios.cooja.dialogs.CreateSimDialog; import org.contikios.cooja.dialogs.ExternalToolsDialog; import org.contikios.cooja.dialogs.MessageList; import org.contikios.cooja.dialogs.ProjectDirectoriesDialog; import org.contikios.cooja.plugins.MoteTypeInformation; import org.contikios.cooja.plugins.ScriptRunner; import org.contikios.cooja.plugins.SimControl; import org.contikios.cooja.plugins.SimInformation; import org.contikios.cooja.util.ExecuteJAR; /** * Main file of COOJA Simulator. Typically contains a visualizer for the * simulator, but can also be started without visualizer. * * This class loads external Java classes (in extension directories), and handles the * COOJA plugins as well as the configuration system. If provides a number of * help methods for the rest of the COOJA system, and is the starting point for * loading and saving simulation configs. * * @author Fredrik Osterlind */ public class Cooja extends Observable { private static JFrame frame = null; private static JApplet applet = null; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(Cooja.class); /** * External tools configuration. */ public static final String EXTERNAL_TOOLS_SETTINGS_FILENAME = "/external_tools.config"; /** * External tools default Win32 settings filename. */ public static final String EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME = "/external_tools_win32.config"; /** * External tools default Mac OS X settings filename. */ public static final String EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME = "/external_tools_macosx.config"; /** * External tools default FreeBSD settings filename. */ public static final String EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME = "/external_tools_freebsd.config"; /** * External tools default Linux/Unix settings filename. */ public static final String EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME = "/external_tools_linux.config"; /** * External tools default Linux/Unix settings filename for 64 bit architectures. * Tested on Intel 64-bit Gentoo Linux. */ public static final String EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME = "/external_tools_linux_64.config"; /** * External tools user settings filename. */ public static final String EXTERNAL_TOOLS_USER_SETTINGS_FILENAME = ".cooja.user.properties"; public static File externalToolsUserSettingsFile; private static boolean externalToolsUserSettingsFileReadOnly = false; private static String specifiedContikiPath = null; /** * Logger settings filename. */ public static final String LOG_CONFIG_FILE = "log4j_config.xml"; /** * Default extension configuration filename. */ public static String PROJECT_DEFAULT_CONFIG_FILENAME = null; /** * User extension configuration filename. */ public static final String PROJECT_CONFIG_FILENAME = "cooja.config"; /** * File filter only showing saved simulations files (*.csc). */ public static final FileFilter SAVED_SIMULATIONS_FILES = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".csc")) { return true; } if (file.getName().endsWith(".csc.gz")) { return true; } return false; } public String getDescription() { return "Cooja simulation (.csc, .csc.gz)"; } public String toString() { return ".csc"; } }; // External tools setting names public static Properties defaultExternalToolsSettings; public static Properties currentExternalToolsSettings; private static final String externalToolsSettingNames[] = new String[] { "PATH_CONTIKI", "PATH_COOJA_CORE_RELATIVE","PATH_COOJA","PATH_APPS", "PATH_APPSEARCH", "PATH_MAKE", "PATH_SHELL", "PATH_C_COMPILER", "COMPILER_ARGS", "PATH_LINKER", "LINK_COMMAND_1", "LINK_COMMAND_2", "PATH_AR", "AR_COMMAND_1", "AR_COMMAND_2", "PATH_OBJDUMP", "OBJDUMP_ARGS", "PATH_OBJCOPY", "PATH_JAVAC", "CONTIKI_STANDARD_PROCESSES", "CMD_GREP_PROCESSES", "REGEXP_PARSE_PROCESSES", "CMD_GREP_INTERFACES", "REGEXP_PARSE_INTERFACES", "CMD_GREP_SENSORS", "REGEXP_PARSE_SENSORS", "DEFAULT_PROJECTDIRS", "CORECOMM_TEMPLATE_FILENAME", "PARSE_WITH_COMMAND", "MAPFILE_DATA_START", "MAPFILE_DATA_SIZE", "MAPFILE_BSS_START", "MAPFILE_BSS_SIZE", "MAPFILE_COMMON_START", "MAPFILE_COMMON_SIZE", "MAPFILE_VAR_NAME", "MAPFILE_VAR_ADDRESS_1", "MAPFILE_VAR_ADDRESS_2", "MAPFILE_VAR_SIZE_1", "MAPFILE_VAR_SIZE_2", "PARSE_COMMAND", "COMMAND_VAR_NAME_ADDRESS", "COMMAND_DATA_START", "COMMAND_DATA_END", "COMMAND_BSS_START", "COMMAND_BSS_END", "COMMAND_COMMON_START", "COMMAND_COMMON_END", "HIDE_WARNINGS" }; private static final int FRAME_NEW_OFFSET = 30; private static final int FRAME_STANDARD_WIDTH = 150; private static final int FRAME_STANDARD_HEIGHT = 300; private static final String WINDOW_TITLE = "Cooja: The Contiki Network Simulator"; private Cooja cooja; private Simulation mySimulation; protected GUIEventHandler guiEventHandler = new GUIEventHandler(); private JMenu menuMoteTypeClasses, menuMoteTypes; private JMenu menuOpenSimulation; private boolean hasFileHistoryChanged; private Vector<Class<? extends Plugin>> menuMotePluginClasses = new Vector<Class<? extends Plugin>>(); private JDesktopPane myDesktopPane; private Vector<Plugin> startedPlugins = new Vector<Plugin>(); private ArrayList<GUIAction> guiActions = new ArrayList<GUIAction>(); // Platform configuration variables // Maintained via method reparseProjectConfig() private ProjectConfig projectConfig; private ArrayList<COOJAProject> currentProjects = new ArrayList<COOJAProject>(); public ClassLoader projectDirClassLoader; private Vector<Class<? extends MoteType>> moteTypeClasses = new Vector<Class<? extends MoteType>>(); private Vector<Class<? extends Plugin>> pluginClasses = new Vector<Class<? extends Plugin>>(); private Vector<Class<? extends RadioMedium>> radioMediumClasses = new Vector<Class<? extends RadioMedium>>(); private Vector<Class<? extends Positioner>> positionerClasses = new Vector<Class<? extends Positioner>>(); private class HighlightObservable extends Observable { private void setChangedAndNotify(Mote mote) { setChanged(); notifyObservers(mote); } } private HighlightObservable moteHighlightObservable = new HighlightObservable(); private class MoteRelationsObservable extends Observable { private void setChangedAndNotify() { setChanged(); notifyObservers(); } } private MoteRelationsObservable moteRelationObservable = new MoteRelationsObservable(); private JTextPane quickHelpTextPane; private JScrollPane quickHelpScroll; private Properties quickHelpProperties = null; /* quickhelp.txt */ /** * Mote relation (directed). */ public static class MoteRelation { public Mote source; public Mote dest; public Color color; public MoteRelation(Mote source, Mote dest, Color color) { this.source = source; this.dest = dest; this.color = color; } } private ArrayList<MoteRelation> moteRelations = new ArrayList<MoteRelation>(); /** * Creates a new COOJA Simulator GUI. * * @param desktop Desktop pane */ public Cooja(JDesktopPane desktop) { cooja = this; mySimulation = null; myDesktopPane = desktop; /* Help panel */ quickHelpTextPane = new JTextPane(); quickHelpTextPane.setContentType("text/html"); quickHelpTextPane.setEditable(false); quickHelpTextPane.setVisible(false); quickHelpScroll = new JScrollPane(quickHelpTextPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); quickHelpScroll.setPreferredSize(new Dimension(200, 0)); quickHelpScroll.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(0, 3, 0, 0) )); quickHelpScroll.setVisible(false); loadQuickHelp("GETTING_STARTED"); // Load default and overwrite with user settings (if any) loadExternalToolsDefaultSettings(); loadExternalToolsUserSettings(); final boolean showQuickhelp = getExternalToolsSetting("SHOW_QUICKHELP", "true").equalsIgnoreCase("true"); if (showQuickhelp) { SwingUtilities.invokeLater(new Runnable() { public void run() { JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } }); } /* Debugging - Break on repaints outside EDT */ /*RepaintManager.setCurrentManager(new RepaintManager() { public void addDirtyRegion(JComponent comp, int a, int b, int c, int d) { if(!java.awt.EventQueue.isDispatchThread()) { throw new RuntimeException("Repainting outside EDT"); } super.addDirtyRegion(comp, a, b, c, d); } });*/ // Register default extension directories String defaultProjectDirs = getExternalToolsSetting("DEFAULT_PROJECTDIRS", null); if (defaultProjectDirs != null && defaultProjectDirs.length() > 0) { String[] arr = defaultProjectDirs.split(";"); for (String p : arr) { File projectDir = restorePortablePath(new File(p)); currentProjects.add(new COOJAProject(projectDir)); } } //Scan for projects String searchProjectDirs = getExternalToolsSetting("PATH_APPSEARCH", null); if (searchProjectDirs != null && searchProjectDirs.length() > 0) { String[] arr = searchProjectDirs.split(";"); for (String d : arr) { File searchDir = restorePortablePath(new File(d)); File[] projects = COOJAProject.sarchProjects(searchDir, 3); if(projects == null) continue; for(File p : projects){ currentProjects.add(new COOJAProject(p)); } } } /* Parse current extension configuration */ try { reparseProjectConfig(); } catch (ParseProjectsException e) { logger.fatal("Error when loading extensions: " + e.getMessage(), e); if (isVisualized()) { JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), "All Cooja extensions could not load.\n\n" + "To manage Cooja extensions:\n" + "Menu->Settings->Cooja extensions", "Reconfigure Cooja extensions", JOptionPane.INFORMATION_MESSAGE); showErrorDialog(getTopParentContainer(), "Cooja extensions load error", e, false); } } // Start all standard GUI plugins for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, null, null); } } } /** * Add mote highlight observer. * * @see #deleteMoteHighlightObserver(Observer) * @param newObserver * New observer */ public void addMoteHighlightObserver(Observer newObserver) { moteHighlightObservable.addObserver(newObserver); } /** * Delete mote highlight observer. * * @see #addMoteHighlightObserver(Observer) * @param observer * Observer to delete */ public void deleteMoteHighlightObserver(Observer observer) { moteHighlightObservable.deleteObserver(observer); } /** * @return True if simulator is visualized */ public static boolean isVisualized() { return isVisualizedInFrame() || isVisualizedInApplet(); } public static Container getTopParentContainer() { if (isVisualizedInFrame()) { return frame; } if (isVisualizedInApplet()) { /* Find parent frame for applet */ Container container = applet; while((container = container.getParent()) != null){ if (container instanceof Frame) { return container; } if (container instanceof Dialog) { return container; } if (container instanceof Window) { return container; } } logger.fatal("Returning null top owner container"); } return null; } public static boolean isVisualizedInFrame() { return frame != null; } public static URL getAppletCodeBase() { return applet.getCodeBase(); } public static boolean isVisualizedInApplet() { return applet != null; } /** * Tries to create/remove simulator visualizer. * * @param visualized Visualized */ public void setVisualizedInFrame(boolean visualized) { if (visualized) { if (!isVisualizedInFrame()) { configureFrame(cooja, false); } } else { if (frame != null) { frame.setVisible(false); frame.dispose(); frame = null; } } } public File getLastOpenedFile() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); return historyArray.length > 0 ? new File(historyArray[0]) : null; } public File[] getFileHistory() { // Fetch current history String[] historyArray = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); File[] history = new File[historyArray.length]; for (int i = 0; i < historyArray.length; i++) { history[i] = new File(historyArray[i]); } return history; } public void addToFileHistory(File file) { // Fetch current history String[] history = getExternalToolsSetting("SIMCFG_HISTORY", "").split(";"); String newFile = file.getAbsolutePath(); if (history.length > 0 && history[0].equals(newFile)) { // File already added return; } // Create new history StringBuilder newHistory = new StringBuilder(); newHistory.append(newFile); for (int i = 0, count = 1; i < history.length && count < 10; i++) { String historyFile = history[i]; if (newFile.equals(historyFile) || historyFile.length() == 0) { // File already added or empty file name } else { newHistory.append(';').append(historyFile); count++; } } setExternalToolsSetting("SIMCFG_HISTORY", newHistory.toString()); saveExternalToolsUserSettings(); hasFileHistoryChanged = true; } private void updateOpenHistoryMenuItems() { if (isVisualizedInApplet()) { return; } if (!hasFileHistoryChanged) { return; } hasFileHistoryChanged = false; File[] openFilesHistory = getFileHistory(); updateOpenHistoryMenuItems(openFilesHistory); } private void populateMenuWithHistory(JMenu menu, final boolean quick, File[] openFilesHistory) { JMenuItem lastItem; int index = 0; for (File file: openFilesHistory) { if (index < 10) { char mnemonic = (char) ('0' + (++index % 10)); lastItem = new JMenuItem(mnemonic + " " + file.getName()); lastItem.setMnemonic(mnemonic); } else { lastItem = new JMenuItem(file.getName()); } final File f = file; lastItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doLoadConfigAsync(true, quick, f); } }); lastItem.putClientProperty("file", file); lastItem.setToolTipText(file.getAbsolutePath()); menu.add(lastItem); } } private void doLoadConfigAsync(final boolean ask, final boolean quick, final File file) { new Thread(new Runnable() { public void run() { cooja.doLoadConfig(ask, quick, file, null); } }).start(); } private void updateOpenHistoryMenuItems(File[] openFilesHistory) { menuOpenSimulation.removeAll(); /* Reconfigure submenu */ JMenu reconfigureMenu = new JMenu("Open and Reconfigure"); JMenuItem browseItem2 = new JMenuItem("Browse..."); browseItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doLoadConfigAsync(true, false, null); } }); reconfigureMenu.add(browseItem2); reconfigureMenu.add(new JSeparator()); populateMenuWithHistory(reconfigureMenu, false, openFilesHistory); /* Open menu */ JMenuItem browseItem = new JMenuItem("Browse..."); browseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doLoadConfigAsync(true, true, null); } }); menuOpenSimulation.add(browseItem); menuOpenSimulation.add(new JSeparator()); menuOpenSimulation.add(reconfigureMenu); menuOpenSimulation.add(new JSeparator()); populateMenuWithHistory(menuOpenSimulation, true, openFilesHistory); } /** * Enables/disables menues and menu items depending on whether a simulation is loaded etc. */ void updateGUIComponentState() { if (!isVisualized()) { return; } /* Update action state */ for (GUIAction a: guiActions) { a.setEnabled(a.shouldBeEnabled()); } /* Mote and mote type menues */ if (menuMoteTypeClasses != null) { menuMoteTypeClasses.setEnabled(getSimulation() != null); } if (menuMoteTypes != null) { menuMoteTypes.setEnabled(getSimulation() != null); } } private JMenuBar createMenuBar() { JMenuItem menuItem; /* Prepare GUI actions */ guiActions.add(newSimulationAction); guiActions.add(closeSimulationAction); guiActions.add(reloadSimulationAction); guiActions.add(reloadRandomSimulationAction); guiActions.add(saveSimulationAction); /* guiActions.add(closePluginsAction);*/ guiActions.add(exportExecutableJARAction); guiActions.add(exitCoojaAction); guiActions.add(startStopSimulationAction); guiActions.add(removeAllMotesAction); guiActions.add(showBufferSettingsAction); /* Menus */ JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu simulationMenu = new JMenu("Simulation"); JMenu motesMenu = new JMenu("Motes"); final JMenu toolsMenu = new JMenu("Tools"); JMenu settingsMenu = new JMenu("Settings"); JMenu helpMenu = new JMenu("Help"); menuBar.add(fileMenu); menuBar.add(simulationMenu); menuBar.add(motesMenu); menuBar.add(toolsMenu); menuBar.add(settingsMenu); menuBar.add(helpMenu); fileMenu.setMnemonic(KeyEvent.VK_F); simulationMenu.setMnemonic(KeyEvent.VK_S); motesMenu.setMnemonic(KeyEvent.VK_M); toolsMenu.setMnemonic(KeyEvent.VK_T); helpMenu.setMnemonic(KeyEvent.VK_H); /* File menu */ fileMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); updateOpenHistoryMenuItems(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); fileMenu.add(new JMenuItem(newSimulationAction)); menuOpenSimulation = new JMenu("Open simulation"); menuOpenSimulation.setMnemonic(KeyEvent.VK_O); fileMenu.add(menuOpenSimulation); if (isVisualizedInApplet()) { menuOpenSimulation.setEnabled(false); menuOpenSimulation.setToolTipText("Not available in applet version"); } fileMenu.add(new JMenuItem(closeSimulationAction)); hasFileHistoryChanged = true; fileMenu.add(new JMenuItem(saveSimulationAction)); fileMenu.add(new JMenuItem(exportExecutableJARAction)); /* menu.addSeparator();*/ /* menu.add(new JMenuItem(closePluginsAction));*/ fileMenu.addSeparator(); fileMenu.add(new JMenuItem(exitCoojaAction)); /* Simulation menu */ simulationMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); simulationMenu.add(new JMenuItem(startStopSimulationAction)); JMenuItem reloadSimulationMenuItem = new JMenu("Reload simulation"); reloadSimulationMenuItem.add(new JMenuItem(reloadSimulationAction)); reloadSimulationMenuItem.add(new JMenuItem(reloadRandomSimulationAction)); simulationMenu.add(reloadSimulationMenuItem); GUIAction guiAction = new StartPluginGUIAction("Control panel..."); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.putClientProperty("class", SimControl.class); simulationMenu.add(menuItem); guiAction = new StartPluginGUIAction("Simulation..."); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.setMnemonic(KeyEvent.VK_I); menuItem.putClientProperty("class", SimInformation.class); simulationMenu.add(menuItem); // Mote type menu motesMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Mote type classes sub menu menuMoteTypeClasses = new JMenu("Create new mote type"); menuMoteTypeClasses.setMnemonic(KeyEvent.VK_C); menuMoteTypeClasses.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypeClasses.removeAll(); // Recreate menu items JMenuItem menuItem; for (Class<? extends MoteType> moteTypeClass : moteTypeClasses) { /* Sort mote types according to abstraction level */ String abstractionLevelDescription = Cooja.getAbstractionLevelDescriptionOf(moteTypeClass); if(abstractionLevelDescription == null) { abstractionLevelDescription = "[unknown cross-level]"; } /* Check if abstraction description already exists */ JSeparator abstractionLevelSeparator = null; for (Component component: menuMoteTypeClasses.getMenuComponents()) { if (component == null || !(component instanceof JSeparator)) { continue; } JSeparator existing = (JSeparator) component; if (abstractionLevelDescription.equals(existing.getToolTipText())) { abstractionLevelSeparator = existing; break; } } if (abstractionLevelSeparator == null) { abstractionLevelSeparator = new JSeparator(); abstractionLevelSeparator.setToolTipText(abstractionLevelDescription); menuMoteTypeClasses.add(abstractionLevelSeparator); } String description = Cooja.getDescriptionOf(moteTypeClass); menuItem = new JMenuItem(description + "..."); menuItem.setActionCommand("create mote type"); menuItem.putClientProperty("class", moteTypeClass); /* menuItem.setToolTipText(abstractionLevelDescription);*/ menuItem.addActionListener(guiEventHandler); if (isVisualizedInApplet() && moteTypeClass.equals(ContikiMoteType.class)) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } /* Add new item directly after cross level separator */ for (int i=0; i < menuMoteTypeClasses.getMenuComponentCount(); i++) { if (menuMoteTypeClasses.getMenuComponent(i) == abstractionLevelSeparator) { menuMoteTypeClasses.add(menuItem, i+1); break; } } } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Mote menu motesMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Mote types sub menu menuMoteTypes = new JMenu("Add motes"); menuMoteTypes.setMnemonic(KeyEvent.VK_A); menuMoteTypes.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { // Clear menu menuMoteTypes.removeAll(); if (mySimulation != null) { // Recreate menu items JMenuItem menuItem; for (MoteType moteType : mySimulation.getMoteTypes()) { menuItem = new JMenuItem(moteType.getDescription()); menuItem.setActionCommand("add motes"); menuItem.setToolTipText(getDescriptionOf(moteType.getClass())); menuItem.putClientProperty("motetype", moteType); menuItem.addActionListener(guiEventHandler); menuMoteTypes.add(menuItem); } if(mySimulation.getMoteTypes().length > 0) { menuMoteTypes.add(new JSeparator()); } } menuMoteTypes.add(menuMoteTypeClasses); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); motesMenu.add(menuMoteTypes); guiAction = new StartPluginGUIAction("Mote types..."); menuItem = new JMenuItem(guiAction); guiActions.add(guiAction); menuItem.putClientProperty("class", MoteTypeInformation.class); motesMenu.add(menuItem); motesMenu.add(new JMenuItem(removeAllMotesAction)); /* Tools menu */ toolsMenu.addMenuListener(new MenuListener() { private ActionListener menuItemListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Object pluginClass = ((JMenuItem)e.getSource()).getClientProperty("class"); Object mote = ((JMenuItem)e.getSource()).getClientProperty("mote"); tryStartPlugin((Class<? extends Plugin>) pluginClass, cooja, getSimulation(), (Mote)mote); } }; private JMenuItem createMenuItem(Class<? extends Plugin> newPluginClass, int pluginType) { String description = getDescriptionOf(newPluginClass); JMenuItem menuItem = new JMenuItem(description + "..."); menuItem.putClientProperty("class", newPluginClass); menuItem.addActionListener(menuItemListener); String tooltip = "<html><pre>"; if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { tooltip += "Cooja plugin: "; } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { tooltip += "Simulation plugin: "; if (getSimulation() == null) { menuItem.setEnabled(false); } } else if (pluginType == PluginType.MOTE_PLUGIN) { tooltip += "Mote plugin: "; } tooltip += description + " (" + newPluginClass.getName() + ")"; /* Check if simulation plugin depends on any particular radio medium */ if ((pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) && (getSimulation() != null)) { if (newPluginClass.getAnnotation(SupportedArguments.class) != null) { boolean active = false; Class<? extends RadioMedium>[] radioMediums = newPluginClass.getAnnotation(SupportedArguments.class).radioMediums(); for (Class<? extends Object> o: radioMediums) { if (o.isAssignableFrom(getSimulation().getRadioMedium().getClass())) { active = true; break; } } if (!active) { menuItem.setVisible(false); } } } /* Check if plugin was imported by a extension directory */ File project = getProjectConfig().getUserProjectDefining(Cooja.class, "PLUGINS", newPluginClass.getName()); if (project != null) { tooltip += "\nLoaded by extension: " + project.getPath(); } tooltip += "</html>"; /*menuItem.setToolTipText(tooltip);*/ return menuItem; } public void menuSelected(MenuEvent e) { /* Populate tools menu */ toolsMenu.removeAll(); /* Cooja plugins */ boolean hasCoojaPlugins = false; for (Class<? extends Plugin> pluginClass: pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { continue; } toolsMenu.add(createMenuItem(pluginClass, pluginType)); hasCoojaPlugins = true; } /* Simulation plugins */ boolean hasSimPlugins = false; for (Class<? extends Plugin> pluginClass: pluginClasses) { if (pluginClass.equals(SimControl.class)) { continue; /* ignore */ } if (pluginClass.equals(SimInformation.class)) { continue; /* ignore */ } if (pluginClass.equals(MoteTypeInformation.class)) { continue; /* ignore */ } int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType != PluginType.SIM_PLUGIN && pluginType != PluginType.SIM_STANDARD_PLUGIN) { continue; } if (hasCoojaPlugins) { hasCoojaPlugins = false; toolsMenu.addSeparator(); } toolsMenu.add(createMenuItem(pluginClass, pluginType)); hasSimPlugins = true; } for (Class<? extends Plugin> pluginClass: pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType != PluginType.MOTE_PLUGIN) { continue; } if (hasSimPlugins) { hasSimPlugins = false; toolsMenu.addSeparator(); } toolsMenu.add(createMotePluginsSubmenu(pluginClass)); } } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); // Settings menu settingsMenu.addMenuListener(new MenuListener() { public void menuSelected(MenuEvent e) { updateGUIComponentState(); } public void menuDeselected(MenuEvent e) { } public void menuCanceled(MenuEvent e) { } }); menuItem = new JMenuItem("External tools paths..."); menuItem.setActionCommand("edit paths"); menuItem.addActionListener(guiEventHandler); settingsMenu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Cooja extensions..."); menuItem.setActionCommand("manage extensions"); menuItem.addActionListener(guiEventHandler); settingsMenu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } menuItem = new JMenuItem("Cooja mote configuration wizard..."); menuItem.setActionCommand("configuration wizard"); menuItem.addActionListener(guiEventHandler); settingsMenu.add(menuItem); if (isVisualizedInApplet()) { menuItem.setEnabled(false); menuItem.setToolTipText("Not available in applet version"); } settingsMenu.add(new JMenuItem(showBufferSettingsAction)); /* Help */ helpMenu.add(new JMenuItem(showGettingStartedAction)); helpMenu.add(new JMenuItem(showKeyboardShortcutsAction)); JCheckBoxMenuItem checkBox = new JCheckBoxMenuItem(showQuickHelpAction); showQuickHelpAction.putValue("checkbox", checkBox); helpMenu.add(checkBox); helpMenu.addSeparator(); menuItem = new JMenuItem("Java version: " + System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")"); menuItem.setEnabled(false); helpMenu.add(menuItem); menuItem = new JMenuItem("System \"os.arch\": " + System.getProperty("os.arch")); menuItem.setEnabled(false); helpMenu.add(menuItem); menuItem = new JMenuItem("System \"sun.arch.data.model\": " + System.getProperty("sun.arch.data.model")); menuItem.setEnabled(false); helpMenu.add(menuItem); return menuBar; } private static void configureFrame(final Cooja gui, boolean createSimDialog) { if (frame == null) { frame = new JFrame(WINDOW_TITLE); } frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); /* Menu bar */ frame.setJMenuBar(gui.createMenuBar()); /* Scrollable desktop */ JComponent desktop = gui.getDesktopPane(); desktop.setOpaque(true); JScrollPane scroll = new JScrollPane(desktop); scroll.setBorder(null); JPanel container = new JPanel(new BorderLayout()); container.add(BorderLayout.CENTER, scroll); container.add(BorderLayout.EAST, gui.quickHelpScroll); frame.setContentPane(container); frame.setSize(700, 700); frame.setLocationRelativeTo(null); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { gui.doQuit(true); } }); frame.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { updateDesktopSize(gui.getDesktopPane()); } }); /* Restore frame size and position */ int framePosX = Integer.parseInt(getExternalToolsSetting("FRAME_POS_X", "0")); int framePosY = Integer.parseInt(getExternalToolsSetting("FRAME_POS_Y", "0")); int frameWidth = Integer.parseInt(getExternalToolsSetting("FRAME_WIDTH", "0")); int frameHeight = Integer.parseInt(getExternalToolsSetting("FRAME_HEIGHT", "0")); String frameScreen = getExternalToolsSetting("FRAME_SCREEN", ""); /* Restore position to the same graphics device */ GraphicsDevice device = null; GraphicsDevice all[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (GraphicsDevice gd : all) { if (gd.getIDstring().equals(frameScreen)) { device = gd; } } /* Check if frame should be maximized */ if (device != null) { if (frameWidth == Integer.MAX_VALUE && frameHeight == Integer.MAX_VALUE) { frame.setLocation(device.getDefaultConfiguration().getBounds().getLocation()); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); } else if (frameWidth > 0 && frameHeight > 0) { /* Sanity-check: will Cooja be visible on screen? */ boolean intersects = device.getDefaultConfiguration().getBounds().intersects( new Rectangle(framePosX, framePosY, frameWidth, frameHeight)); if (intersects) { frame.setLocation(framePosX, framePosY); frame.setSize(frameWidth, frameHeight); } } } frame.setVisible(true); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } private static void configureApplet(final Cooja gui, boolean createSimDialog) { applet = CoojaApplet.applet; // Add menu bar JMenuBar menuBar = gui.createMenuBar(); applet.setJMenuBar(menuBar); JComponent newContentPane = gui.getDesktopPane(); newContentPane.setOpaque(true); applet.setContentPane(newContentPane); applet.setSize(700, 700); if (createSimDialog) { SwingUtilities.invokeLater(new Runnable() { public void run() { gui.doCreateSimulation(true); } }); } } /** * @return Current desktop pane (simulator visualizer) */ public JDesktopPane getDesktopPane() { return myDesktopPane; } public static void setLookAndFeel() { JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); ToolTipManager.sharedInstance().setDismissDelay(60000); /* Nimbus */ try { String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("linux")) { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (UnsupportedLookAndFeelException e) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } } else { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } return; } catch (Exception e) { } /* System */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); return; } catch (Exception e) { } } private static void updateDesktopSize(final JDesktopPane desktop) { if (desktop == null || !desktop.isVisible() || desktop.getParent() == null) { return; } Rectangle rect = desktop.getVisibleRect(); Dimension pref = new Dimension(rect.width - 1, rect.height - 1); for (JInternalFrame frame : desktop.getAllFrames()) { if (pref.width < frame.getX() + frame.getWidth() - 20) { pref.width = frame.getX() + frame.getWidth(); } if (pref.height < frame.getY() + frame.getHeight() - 20) { pref.height = frame.getY() + frame.getHeight(); } } desktop.setPreferredSize(pref); desktop.revalidate(); } private static JDesktopPane createDesktopPane() { final JDesktopPane desktop = new JDesktopPane() { private static final long serialVersionUID = -8272040875621119329L; public void setBounds(int x, int y, int w, int h) { super.setBounds(x, y, w, h); updateDesktopSize(this); } public void remove(Component c) { super.remove(c); updateDesktopSize(this); } public Component add(Component comp) { Component c = super.add(comp); updateDesktopSize(this); return c; } }; desktop.setDesktopManager(new DefaultDesktopManager() { private static final long serialVersionUID = -5987404936292377152L; public void endResizingFrame(JComponent f) { super.endResizingFrame(f); updateDesktopSize(desktop); } public void endDraggingFrame(JComponent f) { super.endDraggingFrame(f); updateDesktopSize(desktop); } }); desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); return desktop; } public static Simulation quickStartSimulationConfig(File config, boolean vis, Long manualRandomSeed) { logger.info("> Starting Cooja"); JDesktopPane desktop = createDesktopPane(); if (vis) { frame = new JFrame(WINDOW_TITLE); } Cooja gui = new Cooja(desktop); if (vis) { configureFrame(gui, false); } if (vis) { gui.doLoadConfig(false, true, config, manualRandomSeed); return gui.getSimulation(); } else { try { Simulation newSim = gui.loadSimulationConfig(config, true, manualRandomSeed); if (newSim == null) { return null; } gui.setSimulation(newSim, false); return newSim; } catch (Exception e) { logger.fatal("Exception when loading simulation: ", e); return null; } } } /** * Allows user to create a simulation with a single mote type. * * @param source Contiki application file name * @return True if simulation was created */ private static Simulation quickStartSimulation(String source) { logger.info("> Starting Cooja"); JDesktopPane desktop = createDesktopPane(); frame = new JFrame(WINDOW_TITLE); Cooja gui = new Cooja(desktop); configureFrame(gui, false); logger.info("> Creating simulation"); Simulation sim = new Simulation(gui); sim.setTitle("Quickstarted simulation: " + source); boolean simOK = CreateSimDialog.showDialog(Cooja.getTopParentContainer(), sim); if (!simOK) { logger.fatal("No simulation, aborting quickstart"); System.exit(1); } gui.setSimulation(sim, true); logger.info("> Creating mote type"); ContikiMoteType moteType = new ContikiMoteType(); moteType.setContikiSourceFile(new File(source)); moteType.setDescription("Cooja mote type (" + source + ")"); try { boolean compileOK = moteType.configureAndInit(Cooja.getTopParentContainer(), sim, true); if (!compileOK) { logger.fatal("Mote type initialization failed, aborting quickstart"); return null; } } catch (MoteTypeCreationException e1) { logger.fatal("Mote type initialization failed, aborting quickstart"); return null; } sim.addMoteType(moteType); logger.info("> Adding motes"); gui.doAddMotes(moteType); return sim; } //// PROJECT CONFIG AND EXTENDABLE PARTS METHODS //// /** * Register new mote type class. * * @param moteTypeClass * Class to register */ public void registerMoteType(Class<? extends MoteType> moteTypeClass) { moteTypeClasses.add(moteTypeClass); } /** * Unregister all mote type classes. */ public void unregisterMoteTypes() { moteTypeClasses.clear(); } /** * @return All registered mote type classes */ public Vector<Class<? extends MoteType>> getRegisteredMoteTypes() { return moteTypeClasses; } /** * Register new positioner class. * * @param positionerClass * Class to register * @return True if class was registered */ public boolean registerPositioner(Class<? extends Positioner> positionerClass) { // Check that interval constructor exists try { positionerClass .getConstructor(new Class[] { int.class, double.class, double.class, double.class, double.class, double.class, double.class }); } catch (Exception e) { logger.fatal("No interval constructor found of positioner: " + positionerClass); return false; } positionerClasses.add(positionerClass); return true; } /** * Unregister all positioner classes. */ public void unregisterPositioners() { positionerClasses.clear(); } /** * @return All registered positioner classes */ public Vector<Class<? extends Positioner>> getRegisteredPositioners() { return positionerClasses; } /** * Register new radio medium class. * * @param radioMediumClass * Class to register * @return True if class was registered */ public boolean registerRadioMedium( Class<? extends RadioMedium> radioMediumClass) { // Check that simulation constructor exists try { radioMediumClass.getConstructor(new Class[] { Simulation.class }); } catch (Exception e) { logger.fatal("No simulation constructor found of radio medium: " + radioMediumClass); return false; } radioMediumClasses.add(radioMediumClass); return true; } /** * Unregister all radio medium classes. */ public void unregisterRadioMediums() { radioMediumClasses.clear(); } /** * @return All registered radio medium classes */ public Vector<Class<? extends RadioMedium>> getRegisteredRadioMediums() { return radioMediumClasses; } /** * Builds new extension configuration using current extension directories settings. * Reregisters mote types, plugins, positioners and radio * mediums. This method may still return true even if all classes could not be * registered, but always returns false if all extension directory configuration * files were not parsed correctly. */ public void reparseProjectConfig() throws ParseProjectsException { if (PROJECT_DEFAULT_CONFIG_FILENAME == null) { if (isVisualizedInApplet()) { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_applet.config"; } else { PROJECT_DEFAULT_CONFIG_FILENAME = "/cooja_default.config"; } } /* Remove current dependencies */ unregisterMoteTypes(); unregisterPlugins(); unregisterPositioners(); unregisterRadioMediums(); projectDirClassLoader = null; /* Build cooja configuration */ try { projectConfig = new ProjectConfig(true); } catch (FileNotFoundException e) { logger.fatal("Could not find default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Could not find default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } catch (IOException e) { logger.fatal("Error when reading default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME); throw (ParseProjectsException) new ParseProjectsException( "Error when reading default extension config file: " + PROJECT_DEFAULT_CONFIG_FILENAME).initCause(e); } if (!isVisualizedInApplet()) { for (COOJAProject project: currentProjects) { try { projectConfig.appendProjectDir(project.dir); } catch (FileNotFoundException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when loading extension: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when reading extension config: " + e.getMessage()).initCause(e); } } /* Create extension class loader */ try { projectDirClassLoader = createClassLoader(currentProjects); } catch (ClassLoaderCreationException e) { throw (ParseProjectsException) new ParseProjectsException( "Error when creating class loader").initCause(e); } } // Register mote types String[] moteTypeClassNames = projectConfig.getStringArrayValue(Cooja.class, "MOTETYPES"); if (moteTypeClassNames != null) { for (String moteTypeClassName : moteTypeClassNames) { if (moteTypeClassName.trim().isEmpty()) { continue; } Class<? extends MoteType> moteTypeClass = tryLoadClass(this, MoteType.class, moteTypeClassName); if (moteTypeClass != null) { registerMoteType(moteTypeClass); // logger.info("Loaded mote type class: " + moteTypeClassName); } else { logger.warn("Could not load mote type class: " + moteTypeClassName); } } } // Register plugins registerPlugin(SimControl.class); registerPlugin(SimInformation.class); registerPlugin(MoteTypeInformation.class); String[] pluginClassNames = projectConfig.getStringArrayValue(Cooja.class, "PLUGINS"); if (pluginClassNames != null) { for (String pluginClassName : pluginClassNames) { Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass != null) { registerPlugin(pluginClass); // logger.info("Loaded plugin class: " + pluginClassName); } else { logger.warn("Could not load plugin class: " + pluginClassName); } } } // Register positioners String[] positionerClassNames = projectConfig.getStringArrayValue( Cooja.class, "POSITIONERS"); if (positionerClassNames != null) { for (String positionerClassName : positionerClassNames) { Class<? extends Positioner> positionerClass = tryLoadClass(this, Positioner.class, positionerClassName); if (positionerClass != null) { registerPositioner(positionerClass); // logger.info("Loaded positioner class: " + positionerClassName); } else { logger .warn("Could not load positioner class: " + positionerClassName); } } } // Register radio mediums String[] radioMediumsClassNames = projectConfig.getStringArrayValue( Cooja.class, "RADIOMEDIUMS"); if (radioMediumsClassNames != null) { for (String radioMediumClassName : radioMediumsClassNames) { Class<? extends RadioMedium> radioMediumClass = tryLoadClass(this, RadioMedium.class, radioMediumClassName); if (radioMediumClass != null) { registerRadioMedium(radioMediumClass); // logger.info("Loaded radio medium class: " + radioMediumClassName); } else { logger.warn("Could not load radio medium class: " + radioMediumClassName); } } } } /** * Returns the current extension configuration common to the entire simulator. * * @return Current extension configuration */ public ProjectConfig getProjectConfig() { return projectConfig; } /** * Returns the current extension directories common to the entire simulator. * * @return Current extension directories. */ public COOJAProject[] getProjects() { return currentProjects.toArray(new COOJAProject[0]); } // // PLUGIN METHODS //// /** * Show a started plugin in working area. * * @param plugin Plugin */ public void showPlugin(final Plugin plugin) { new RunnableInEDT<Boolean>() { public Boolean work() { JInternalFrame pluginFrame = plugin.getCooja(); if (pluginFrame == null) { logger.fatal("Failed trying to show plugin without visualizer."); return false; } int nrFrames = myDesktopPane.getAllFrames().length; myDesktopPane.add(pluginFrame); /* Set size if not already specified by plugin */ if (pluginFrame.getWidth() <= 0 || pluginFrame.getHeight() <= 0) { pluginFrame.setSize(FRAME_STANDARD_WIDTH, FRAME_STANDARD_HEIGHT); } /* Set location if not already visible */ if (pluginFrame.getLocation().x <= 0 && pluginFrame.getLocation().y <= 0) { pluginFrame.setLocation( nrFrames * FRAME_NEW_OFFSET, nrFrames * FRAME_NEW_OFFSET); } pluginFrame.setVisible(true); /* Select plugin */ try { for (JInternalFrame existingPlugin : myDesktopPane.getAllFrames()) { existingPlugin.setSelected(false); } pluginFrame.setSelected(true); } catch (Exception e) { } myDesktopPane.moveToFront(pluginFrame); return true; } }.invokeAndWait(); } /** * Close all mote plugins for given mote. * * @param mote Mote */ public void closeMotePlugins(Mote mote) { for (Plugin p: startedPlugins.toArray(new Plugin[0])) { if (!(p instanceof MotePlugin)) { continue; } Mote pluginMote = ((MotePlugin)p).getMote(); if (pluginMote == mote) { removePlugin(p, false); } } } /** * Remove a plugin from working area. * * @param plugin * Plugin to remove * @param askUser * If plugin is the last one, ask user if we should remove current * simulation also? */ public void removePlugin(final Plugin plugin, final boolean askUser) { new RunnableInEDT<Boolean>() { public Boolean work() { /* Free resources */ plugin.closePlugin(); startedPlugins.remove(plugin); updateGUIComponentState(); /* Dispose visualized components */ if (plugin.getCooja() != null) { plugin.getCooja().dispose(); } /* (OPTIONAL) Remove simulation if all plugins are closed */ if (getSimulation() != null && askUser && startedPlugins.isEmpty()) { doRemoveSimulation(true); } return true; } }.invokeAndWait(); } /** * Same as the {@link #startPlugin(Class, Cooja, Simulation, Mote)} method, * but does not throw exceptions. If COOJA is visualised, an error dialog * is shown if plugin could not be started. * * @see #startPlugin(Class, Cooja, Simulation, Mote) * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin */ private Plugin tryStartPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote, boolean activate) { try { return startPlugin(pluginClass, argGUI, argSimulation, argMote, activate); } catch (PluginConstructionException ex) { if (Cooja.isVisualized()) { Cooja.showErrorDialog(Cooja.getTopParentContainer(), "Error when starting plugin", ex, false); } else { /* If the plugin requires visualization, inform user */ Throwable cause = ex; do { if (cause instanceof PluginRequiresVisualizationException) { logger.info("Visualized plugin was not started: " + pluginClass); return null; } } while (cause != null && (cause=cause.getCause()) != null); logger.fatal("Error when starting plugin", ex); } } return null; } public Plugin tryStartPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote) { return tryStartPlugin(pluginClass, argGUI, argSimulation, argMote, true); } public Plugin startPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote) throws PluginConstructionException { return startPlugin(pluginClass, argGUI, argSimulation, argMote, true); } /** * Starts given plugin. If visualized, the plugin is also shown. * * @see PluginType * @param pluginClass Plugin class * @param argGUI Plugin GUI argument * @param argSimulation Plugin simulation argument * @param argMote Plugin mote argument * @return Started plugin * @throws PluginConstructionException At errors */ private Plugin startPlugin(final Class<? extends Plugin> pluginClass, final Cooja argGUI, final Simulation argSimulation, final Mote argMote, boolean activate) throws PluginConstructionException { // Check that plugin class is registered if (!pluginClasses.contains(pluginClass)) { throw new PluginConstructionException("Tool class not registered: " + pluginClass); } // Construct plugin depending on plugin type int pluginType = pluginClass.getAnnotation(PluginType.class).value(); Plugin plugin; try { if (pluginType == PluginType.MOTE_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for mote plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for mote plugin"); } if (argMote == null) { throw new PluginConstructionException("No mote argument for mote plugin"); } plugin = pluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, Cooja.class }) .newInstance(argMote, argSimulation, argGUI); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for simulation plugin"); } if (argSimulation == null) { throw new PluginConstructionException("No simulation argument for simulation plugin"); } plugin = pluginClass.getConstructor(new Class[] { Simulation.class, Cooja.class }) .newInstance(argSimulation, argGUI); } else if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { if (argGUI == null) { throw new PluginConstructionException("No GUI argument for GUI plugin"); } plugin = pluginClass.getConstructor(new Class[] { Cooja.class }) .newInstance(argGUI); } else { throw new PluginConstructionException("Bad plugin type: " + pluginType); } } catch (PluginRequiresVisualizationException e) { PluginConstructionException ex = new PluginConstructionException("Tool class requires visualization: " + pluginClass.getName()); ex.initCause(e); throw ex; } catch (Exception e) { PluginConstructionException ex = new PluginConstructionException("Construction error for tool of class: " + pluginClass.getName()); ex.initCause(e); throw ex; } if (activate) { plugin.startPlugin(); } // Add to active plugins list startedPlugins.add(plugin); updateGUIComponentState(); // Show plugin if visualizer type if (activate && plugin.getCooja() != null) { cooja.showPlugin(plugin); } return plugin; } /** * Unregister a plugin class. Removes any plugin menu items links as well. * * @param pluginClass Plugin class */ public void unregisterPlugin(Class<? extends Plugin> pluginClass) { pluginClasses.remove(pluginClass); menuMotePluginClasses.remove(pluginClass); } /** * Register a plugin to be included in the GUI. * * @param pluginClass New plugin to register * @return True if this plugin was registered ok, false otherwise */ public boolean registerPlugin(final Class<? extends Plugin> pluginClass) { /* Check plugin type */ final int pluginType; if (pluginClass.isAnnotationPresent(PluginType.class)) { pluginType = pluginClass.getAnnotation(PluginType.class).value(); } else { logger.fatal("Could not register plugin, no plugin type found: " + pluginClass); return false; } /* Check plugin constructor */ try { if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { pluginClass.getConstructor(new Class[] { Cooja.class }); } else if (pluginType == PluginType.SIM_PLUGIN || pluginType == PluginType.SIM_STANDARD_PLUGIN) { pluginClass.getConstructor(new Class[] { Simulation.class, Cooja.class }); } else if (pluginType == PluginType.MOTE_PLUGIN) { pluginClass.getConstructor(new Class[] { Mote.class, Simulation.class, Cooja.class }); menuMotePluginClasses.add(pluginClass); } else { logger.fatal("Could not register plugin, bad plugin type: " + pluginType); return false; } pluginClasses.add(pluginClass); } catch (NoClassDefFoundError e) { logger.fatal("No plugin class: " + pluginClass + ": " + e.getMessage()); return false; } catch (NoSuchMethodException e) { logger.fatal("No plugin class constructor: " + pluginClass + ": " + e.getMessage()); return false; } return true; } /** * Unregister all plugin classes */ public void unregisterPlugins() { menuMotePluginClasses.clear(); pluginClasses.clear(); } /** * Returns started plugin that ends with given class name, if any. * * @param classname Class name * @return Plugin instance */ public Plugin getPlugin(String classname) { for (Plugin p: startedPlugins) { if (p.getClass().getName().endsWith(classname)) { return p; } } return null; } /** * Returns started plugin with given class name, if any. * * @param classname Class name * @return Plugin instance * @deprecated */ @Deprecated public Plugin getStartedPlugin(String classname) { return getPlugin(classname); } public Plugin[] getStartedPlugins() { return startedPlugins.toArray(new Plugin[0]); } private boolean isMotePluginCompatible(Class<? extends Plugin> motePluginClass, Mote mote) { if (motePluginClass.getAnnotation(SupportedArguments.class) == null) { return true; } /* Check mote interfaces */ boolean moteInterfacesOK = true; Class<? extends MoteInterface>[] moteInterfaces = motePluginClass.getAnnotation(SupportedArguments.class).moteInterfaces(); StringBuilder moteTypeInterfacesError = new StringBuilder(); moteTypeInterfacesError.append( "The plugin:\n" + getDescriptionOf(motePluginClass) + "\nrequires the following mote interfaces:\n" ); for (Class<? extends MoteInterface> requiredMoteInterface: moteInterfaces) { moteTypeInterfacesError.append(getDescriptionOf(requiredMoteInterface) + "\n"); if (mote.getInterfaces().getInterfaceOfType(requiredMoteInterface) == null) { moteInterfacesOK = false; } } /* Check mote type */ boolean moteTypeOK = false; Class<? extends Mote>[] motes = motePluginClass.getAnnotation(SupportedArguments.class).motes(); StringBuilder moteTypeError = new StringBuilder(); moteTypeError.append( "The plugin:\n" + getDescriptionOf(motePluginClass) + "\ndoes not support motes of type:\n" + getDescriptionOf(mote) + "\n\nIt only supports motes of types:\n" ); for (Class<? extends Mote> supportedMote: motes) { moteTypeError.append(getDescriptionOf(supportedMote) + "\n"); if (supportedMote.isAssignableFrom(mote.getClass())) { moteTypeOK = true; } } /*if (!moteInterfacesOK) { menuItem.setToolTipText( "<html><pre>" + moteTypeInterfacesError + "</html>" ); } if (!moteTypeOK) { menuItem.setToolTipText( "<html><pre>" + moteTypeError + "</html>" ); }*/ return moteInterfacesOK && moteTypeOK; } public JMenu createMotePluginsSubmenu(Class<? extends Plugin> pluginClass) { JMenu menu = new JMenu(getDescriptionOf(pluginClass)); if (getSimulation() == null || getSimulation().getMotesCount() == 0) { menu.setEnabled(false); return menu; } ActionListener menuItemListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Object pluginClass = ((JMenuItem)e.getSource()).getClientProperty("class"); Object mote = ((JMenuItem)e.getSource()).getClientProperty("mote"); tryStartPlugin((Class<? extends Plugin>) pluginClass, cooja, getSimulation(), (Mote)mote); } }; final int MAX_PER_ROW = 30; final int MAX_COLUMNS = 5; int added = 0; for (Mote mote: getSimulation().getMotes()) { if (!isMotePluginCompatible(pluginClass, mote)) { continue; } JMenuItem menuItem = new JMenuItem(mote.toString() + "..."); menuItem.putClientProperty("class", pluginClass); menuItem.putClientProperty("mote", mote); menuItem.addActionListener(menuItemListener); menu.add(menuItem); added++; if (added == MAX_PER_ROW) { menu.getPopupMenu().setLayout(new GridLayout(MAX_PER_ROW, MAX_COLUMNS)); } if (added >= MAX_PER_ROW*MAX_COLUMNS) { break; } } if (added == 0) { menu.setEnabled(false); } return menu; } /** * Return a mote plugins submenu for given mote. * * @param mote Mote * @return Mote plugins menu */ public JMenu createMotePluginsSubmenu(Mote mote) { JMenu menuMotePlugins = new JMenu("Mote tools for " + mote); for (Class<? extends Plugin> motePluginClass: menuMotePluginClasses) { if (!isMotePluginCompatible(motePluginClass, mote)) { continue; } GUIAction guiAction = new StartPluginGUIAction(getDescriptionOf(motePluginClass) + "..."); JMenuItem menuItem = new JMenuItem(guiAction); menuItem.putClientProperty("class", motePluginClass); menuItem.putClientProperty("mote", mote); menuMotePlugins.add(menuItem); } return menuMotePlugins; } // // GUI CONTROL METHODS //// /** * @return Current simulation */ public Simulation getSimulation() { return mySimulation; } public void setSimulation(Simulation sim, boolean startPlugins) { if (sim != null) { doRemoveSimulation(false); } mySimulation = sim; updateGUIComponentState(); // Set frame title if (frame != null) { frame.setTitle(sim.getTitle() + " - " + WINDOW_TITLE); } // Open standard plugins (if none opened already) if (startPlugins) { for (Class<? extends Plugin> pluginClass : pluginClasses) { int pluginType = pluginClass.getAnnotation(PluginType.class).value(); if (pluginType == PluginType.SIM_STANDARD_PLUGIN) { tryStartPlugin(pluginClass, this, sim, null); } } } setChanged(); notifyObservers(); } /** * Creates a new mote type of the given mote type class. * This may include displaying a dialog for user configurations. * * If mote type is created successfully, the add motes dialog will appear. * * @param moteTypeClass Mote type class */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass) { doCreateMoteType(moteTypeClass, true); } /** * Creates a new mote type of the given mote type class. * This may include displaying a dialog for user configurations. * * @param moteTypeClass Mote type class * @param addMotes Show add motes dialog after successfully adding mote type */ public void doCreateMoteType(Class<? extends MoteType> moteTypeClass, boolean addMotes) { if (mySimulation == null) { logger.fatal("Can't create mote type (no simulation)"); return; } mySimulation.stopSimulation(); // Create mote type MoteType newMoteType = null; try { newMoteType = moteTypeClass.newInstance(); if (!newMoteType.configureAndInit(Cooja.getTopParentContainer(), mySimulation, isVisualized())) { return; } mySimulation.addMoteType(newMoteType); } catch (Exception e) { logger.fatal("Exception when creating mote type", e); if (isVisualized()) { showErrorDialog(getTopParentContainer(), "Mote type creation error", e, false); } return; } /* Allow user to immediately add motes */ if (addMotes) { doAddMotes(newMoteType); } } /** * Remove current simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? * @return True if no simulation exists when method returns */ public boolean doRemoveSimulation(boolean askForConfirmation) { if (mySimulation == null) { return true; } if (askForConfirmation) { boolean ok = new RunnableInEDT<Boolean>() { public Boolean work() { String s1 = "Remove"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog(Cooja.getTopParentContainer(), "You have an active simulation.\nDo you want to remove it?", "Remove current simulation?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s2); if (n != JOptionPane.YES_OPTION) { return false; } return true; } }.invokeAndWait(); if (!ok) { return false; } } // Close all started non-GUI plugins for (Object startedPlugin : startedPlugins.toArray()) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); if (pluginType != PluginType.COOJA_PLUGIN && pluginType != PluginType.COOJA_STANDARD_PLUGIN) { removePlugin((Plugin) startedPlugin, false); } } // Delete simulation mySimulation.deleteObservers(); mySimulation.stopSimulation(); mySimulation.removed(); /* Clear current mote relations */ MoteRelation relations[] = getMoteRelations(); for (MoteRelation r: relations) { removeMoteRelation(r.source, r.dest); } mySimulation = null; updateGUIComponentState(); // Reset frame title if (isVisualizedInFrame()) { frame.setTitle(WINDOW_TITLE); } setChanged(); notifyObservers(); return true; } /** * Load a simulation configuration file from disk * * @param askForConfirmation Ask for confirmation before removing any current simulation * @param quick Quick-load simulation * @param configFile Configuration file to load, if null a dialog will appear */ public void doLoadConfig(boolean askForConfirmation, final boolean quick, File configFile, Long manualRandomSeed) { if (isVisualizedInApplet()) { return; } /* Warn about memory usage */ if (warnMemory()) { return; } /* Remove current simulation */ if (!doRemoveSimulation(true)) { return; } /* Use provided configuration, or open File Chooser */ if (configFile != null && !configFile.isDirectory()) { if (!configFile.exists() || !configFile.canRead()) { logger.fatal("No read access to file: " + configFile.getAbsolutePath()); /* File does not exist, open dialog */ doLoadConfig(askForConfirmation, quick, null, manualRandomSeed); return; } } else { final File suggestedFile = configFile; configFile = new RunnableInEDT<File>() { public File work() { JFileChooser fc = new JFileChooser(); fc.setFileFilter(Cooja.SAVED_SIMULATIONS_FILES); if (suggestedFile != null && suggestedFile.isDirectory()) { fc.setCurrentDirectory(suggestedFile); } else { /* Suggest file using file history */ File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } } int returnVal = fc.showOpenDialog(Cooja.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { logger.info("Load command cancelled by user..."); return null; } File file = fc.getSelectedFile(); if (!file.exists()) { /* Try default file extension */ file = new File(file.getParent(), file.getName() + SAVED_SIMULATIONS_FILES); } if (!file.exists() || !file.canRead()) { logger.fatal("No read access to file"); return null; } return file; } }.invokeAndWait(); if (configFile == null) { return; } } addToFileHistory(configFile); final JDialog progressDialog; final String progressTitle = configFile == null ? "Loading" : ("Loading " + configFile.getAbsolutePath()); if (quick) { final Thread loadThread = Thread.currentThread(); progressDialog = new RunnableInEDT<JDialog>() { public JDialog work() { final JDialog progressDialog = new JDialog((Window) Cooja.getTopParentContainer(), progressTitle, ModalityType.APPLICATION_MODAL); JPanel progressPanel = new JPanel(new BorderLayout()); JProgressBar progressBar; JButton button; progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ button = new JButton("Abort"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } } }); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(Cooja.getTopParentContainer()); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { progressDialog.setVisible(true); } }); return progressDialog; } }.invokeAndWait(); } else { progressDialog = null; } // Load simulation in this thread, while showing progress monitor final File fileToLoad = configFile; Simulation newSim = null; boolean shouldRetry = false; do { try { shouldRetry = false; cooja.doRemoveSimulation(false); PROGRESS_WARNINGS.clear(); newSim = loadSimulationConfig(fileToLoad, quick, manualRandomSeed); cooja.setSimulation(newSim, false); /* Optionally show compilation warnings */ boolean hideWarn = Boolean.parseBoolean( Cooja.getExternalToolsSetting("HIDE_WARNINGS", "false") ); if (quick && !hideWarn && !PROGRESS_WARNINGS.isEmpty()) { showWarningsDialog(frame, PROGRESS_WARNINGS.toArray(new String[0])); } PROGRESS_WARNINGS.clear(); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(Cooja.getTopParentContainer(), "Simulation load error", e, true); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(Cooja.getTopParentContainer(), "Simulation load error", e, true); } } while (shouldRetry); if (progressDialog != null && progressDialog.isDisplayable()) { progressDialog.dispose(); } return; } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * * @param autoStart Start executing simulation when loaded * @param randomSeed Simulation's next random seed */ public void reloadCurrentSimulation(final boolean autoStart, final long randomSeed) { if (getSimulation() == null) { logger.fatal("No simulation to reload"); return; } /* Warn about memory usage */ if (warnMemory()) { return; } final JDialog progressDialog = new JDialog(frame, "Reloading", true); final Thread loadThread = new Thread(new Runnable() { public void run() { /* Get current simulation configuration */ Element root = new Element("simconf"); Element simulationElement = new Element("simulation"); simulationElement.addContent(getSimulation().getConfigXML()); root.addContent(simulationElement); Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } /* Remove current simulation, and load config */ boolean shouldRetry = false; do { try { shouldRetry = false; cooja.doRemoveSimulation(false); PROGRESS_WARNINGS.clear(); Simulation newSim = loadSimulationConfig(root, true, new Long(randomSeed)); cooja.setSimulation(newSim, false); if (autoStart) { newSim.startSimulation(); } /* Optionally show compilation warnings */ boolean hideWarn = Boolean.parseBoolean( Cooja.getExternalToolsSetting("HIDE_WARNINGS", "false") ); if (!hideWarn && !PROGRESS_WARNINGS.isEmpty()) { showWarningsDialog(frame, PROGRESS_WARNINGS.toArray(new String[0])); } PROGRESS_WARNINGS.clear(); } catch (UnsatisfiedLinkError e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); cooja.doRemoveSimulation(false); } catch (SimulationCreationException e) { shouldRetry = showErrorDialog(frame, "Simulation reload error", e, true); cooja.doRemoveSimulation(false); } } while (shouldRetry); if (progressDialog.isDisplayable()) { progressDialog.dispose(); } } }); // Display progress dialog while reloading JProgressBar progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setIndeterminate(true); PROGRESS_BAR = progressBar; /* Allow various parts of COOJA to show messages */ JButton button = new JButton("Abort"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (loadThread.isAlive()) { loadThread.interrupt(); doRemoveSimulation(false); } } }); JPanel progressPanel = new JPanel(new BorderLayout()); progressPanel.add(BorderLayout.CENTER, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setSize(400, 200); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setLocationRelativeTo(frame); progressDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); loadThread.start(); progressDialog.setVisible(true); } private boolean warnMemory() { long max = Runtime.getRuntime().maxMemory(); long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); double memRatio = (double) used / (double) max; if (memRatio < 0.8) { return false; } DecimalFormat format = new DecimalFormat("0.000"); logger.warn("Memory usage is getting critical. Reboot Cooja to avoid out of memory error. Current memory usage is " + format.format(100*memRatio) + "%."); if (isVisualized()) { int n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "Reboot Cooja to avoid out of memory error.\n" + "Current memory usage is " + format.format(100*memRatio) + "%.", "Out of memory warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] { "Continue", "Abort"}, "Abort"); if (n != JOptionPane.YES_OPTION) { return true; } } return false; } /** * Reload currently configured simulation. * Reloading a simulation may include recompiling Contiki. * The same random seed is used. * * @see #reloadCurrentSimulation(boolean, long) * @param autoStart Start executing simulation when loaded */ public void reloadCurrentSimulation(boolean autoStart) { reloadCurrentSimulation(autoStart, getSimulation().getRandomSeed()); } /** * Save current simulation configuration to disk * * @param askForConfirmation * Ask for confirmation before overwriting file */ public File doSaveConfig(boolean askForConfirmation) { if (isVisualizedInApplet()) { return null; } if (mySimulation == null) { return null; } mySimulation.stopSimulation(); JFileChooser fc = new JFileChooser(); fc.setFileFilter(Cooja.SAVED_SIMULATIONS_FILES); // Suggest file using history File suggestedFile = getLastOpenedFile(); if (suggestedFile != null) { fc.setSelectedFile(suggestedFile); } int returnVal = fc.showSaveDialog(myDesktopPane); if (returnVal == JFileChooser.APPROVE_OPTION) { File saveFile = fc.getSelectedFile(); if (!fc.accept(saveFile)) { saveFile = new File(saveFile.getParent(), saveFile.getName() + SAVED_SIMULATIONS_FILES); } if (saveFile.exists()) { if (askForConfirmation) { String s1 = "Overwrite"; String s2 = "Cancel"; Object[] options = { s1, s2 }; int n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, s1); if (n != JOptionPane.YES_OPTION) { return null; } } } if (!saveFile.exists() || saveFile.canWrite()) { saveSimulationConfig(saveFile); addToFileHistory(saveFile); return saveFile; } else { JOptionPane.showMessageDialog( getTopParentContainer(), "No write access to " + saveFile, "Save failed", JOptionPane.ERROR_MESSAGE); logger.fatal("No write access to file: " + saveFile.getAbsolutePath()); } } else { logger.info("Save command cancelled by user..."); } return null; } /** * Add new mote to current simulation */ public void doAddMotes(MoteType moteType) { if (mySimulation != null) { mySimulation.stopSimulation(); Vector<Mote> newMotes = AddMoteDialog.showDialog(getTopParentContainer(), mySimulation, moteType); if (newMotes != null) { for (Mote newMote : newMotes) { mySimulation.addMote(newMote); } } } else { logger.warn("No simulation active"); } } /** * Create a new simulation * * @param askForConfirmation * Should we ask for confirmation if a simulation is already active? */ public void doCreateSimulation(boolean askForConfirmation) { /* Remove current simulation */ if (!doRemoveSimulation(askForConfirmation)) { return; } // Create new simulation Simulation newSim = new Simulation(this); boolean createdOK = CreateSimDialog.showDialog(Cooja.getTopParentContainer(), newSim); if (createdOK) { cooja.setSimulation(newSim, true); } } /** * Quit program * * @param askForConfirmation Should we ask for confirmation before quitting? */ public void doQuit(boolean askForConfirmation) { doQuit(askForConfirmation, 0); } public void doQuit(boolean askForConfirmation, int exitCode) { if (isVisualizedInApplet()) { return; } if (askForConfirmation) { if (getSimulation() != null) { /* Save? */ String s1 = "Yes"; String s2 = "No"; String s3 = "Cancel"; Object[] options = { s1, s2, s3 }; int n = JOptionPane.showOptionDialog(Cooja.getTopParentContainer(), "Do you want to save the current simulation?", WINDOW_TITLE, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, s1); if (n == JOptionPane.YES_OPTION) { if (cooja.doSaveConfig(true) == null) { return; } } else if (n == JOptionPane.CANCEL_OPTION) { return; } else if (n != JOptionPane.NO_OPTION) { return; } } } if (getSimulation() != null) { doRemoveSimulation(false); } // Clean up resources Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } /* Store frame size and position */ if (isVisualizedInFrame()) { setExternalToolsSetting("FRAME_SCREEN", frame.getGraphicsConfiguration().getDevice().getIDstring()); setExternalToolsSetting("FRAME_POS_X", "" + frame.getLocationOnScreen().x); setExternalToolsSetting("FRAME_POS_Y", "" + frame.getLocationOnScreen().y); if (frame.getExtendedState() == JFrame.MAXIMIZED_BOTH) { setExternalToolsSetting("FRAME_WIDTH", "" + Integer.MAX_VALUE); setExternalToolsSetting("FRAME_HEIGHT", "" + Integer.MAX_VALUE); } else { setExternalToolsSetting("FRAME_WIDTH", "" + frame.getWidth()); setExternalToolsSetting("FRAME_HEIGHT", "" + frame.getHeight()); } } saveExternalToolsUserSettings(); System.exit(exitCode); } // // EXTERNAL TOOLS SETTINGS METHODS //// /** * @return Number of external tools settings */ public static int getExternalToolsSettingsCount() { return externalToolsSettingNames.length; } /** * Get name of external tools setting at given index. * * @param index * Setting index * @return Name */ public static String getExternalToolsSettingName(int index) { return externalToolsSettingNames[index]; } /** * @param name * Name of setting * @return Value */ public static String getExternalToolsSetting(String name) { return getExternalToolsSetting(name, null); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsSetting(String name, String defaultValue) { if (specifiedContikiPath != null && "PATH_CONTIKI".equals(name)) { return specifiedContikiPath; } return currentExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param defaultValue * Default value * @return Value */ public static String getExternalToolsDefaultSetting(String name, String defaultValue) { return defaultExternalToolsSettings.getProperty(name, defaultValue); } /** * @param name * Name of setting * @param newVal * New value */ public static void setExternalToolsSetting(String name, String newVal) { currentExternalToolsSettings.setProperty(name, newVal); } /** * Load external tools settings from default file. */ public static void loadExternalToolsDefaultSettings() { String osName = System.getProperty("os.name").toLowerCase(); String osArch = System.getProperty("os.arch").toLowerCase(); String filename = null; if (osName.startsWith("win")) { filename = Cooja.EXTERNAL_TOOLS_WIN32_SETTINGS_FILENAME; } else if (osName.startsWith("mac os x")) { filename = Cooja.EXTERNAL_TOOLS_MACOSX_SETTINGS_FILENAME; } else if (osName.startsWith("freebsd")) { filename = Cooja.EXTERNAL_TOOLS_FREEBSD_SETTINGS_FILENAME; } else if (osName.startsWith("linux")) { filename = Cooja.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; if (osArch.startsWith("amd64")) { filename = Cooja.EXTERNAL_TOOLS_LINUX_64_SETTINGS_FILENAME; } } else { logger.warn("Unknown system: " + osName); logger.warn("Using default linux external tools configuration"); filename = Cooja.EXTERNAL_TOOLS_LINUX_SETTINGS_FILENAME; } try { InputStream in = Cooja.class.getResourceAsStream(EXTERNAL_TOOLS_SETTINGS_FILENAME); if (in == null) { throw new FileNotFoundException(filename + " not found"); } Properties settings = new Properties(); settings.load(in); in.close(); in = Cooja.class.getResourceAsStream(filename); if (in == null) { throw new FileNotFoundException(filename + " not found"); } settings.load(in); in.close(); currentExternalToolsSettings = settings; defaultExternalToolsSettings = (Properties) currentExternalToolsSettings.clone(); logger.info("External tools default settings: " + filename); } catch (IOException e) { logger.warn("Error when reading external tools settings from " + filename, e); } finally { if (currentExternalToolsSettings == null) { defaultExternalToolsSettings = new Properties(); currentExternalToolsSettings = new Properties(); } } } /** * Load user values from external properties file */ public static void loadExternalToolsUserSettings() { if (externalToolsUserSettingsFile == null) { return; } try { FileInputStream in = new FileInputStream(externalToolsUserSettingsFile); Properties settings = new Properties(); settings.load(in); in.close(); Enumeration<Object> en = settings.keys(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); setExternalToolsSetting(key, settings.getProperty(key)); } logger.info("External tools user settings: " + externalToolsUserSettingsFile); } catch (FileNotFoundException e) { logger.warn("Error when reading user settings from: " + externalToolsUserSettingsFile); } catch (IOException e) { logger.warn("Error when reading user settings from: " + externalToolsUserSettingsFile); } } /** * Save external tools user settings to file. */ public static void saveExternalToolsUserSettings() { if (isVisualizedInApplet()) { return; } if (externalToolsUserSettingsFileReadOnly) { return; } try { FileOutputStream out = new FileOutputStream(externalToolsUserSettingsFile); Properties differingSettings = new Properties(); Enumeration keyEnum = currentExternalToolsSettings.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); String defaultSetting = getExternalToolsDefaultSetting(key, ""); String currentSetting = currentExternalToolsSettings.getProperty(key, ""); if (!defaultSetting.equals(currentSetting)) { differingSettings.setProperty(key, currentSetting); } } differingSettings.store(out, "Cooja External Tools (User specific)"); out.close(); } catch (FileNotFoundException ex) { // Could not open settings file for writing, aborting logger.warn("Could not save external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } catch (IOException ex) { // Could not open settings file for writing, aborting logger.warn("Error while saving external tools user settings to " + externalToolsUserSettingsFile + ", aborting"); } } // // GUI EVENT HANDLER //// private class GUIEventHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("create mote type")) { cooja.doCreateMoteType((Class<? extends MoteType>) ((JMenuItem) e .getSource()).getClientProperty("class")); } else if (e.getActionCommand().equals("add motes")) { cooja.doAddMotes((MoteType) ((JMenuItem) e.getSource()) .getClientProperty("motetype")); } else if (e.getActionCommand().equals("edit paths")) { ExternalToolsDialog.showDialog(Cooja.getTopParentContainer()); } else if (e.getActionCommand().equals("manage extensions")) { COOJAProject[] newProjects = ProjectDirectoriesDialog.showDialog( Cooja.getTopParentContainer(), Cooja.this, getProjects() ); if (newProjects != null) { currentProjects.clear(); for (COOJAProject p: newProjects) { currentProjects.add(p); } try { reparseProjectConfig(); } catch (ParseProjectsException ex) { logger.fatal("Error when loading extensions: " + ex.getMessage(), ex); if (isVisualized()) { JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), "All Cooja extensions could not load.\n\n" + "To manage Cooja extensions:\n" + "Menu->Settings->Cooja extensions", "Reconfigure Cooja extensions", JOptionPane.INFORMATION_MESSAGE); } showErrorDialog(getTopParentContainer(), "Cooja extensions load error", ex, false); } } } else if (e.getActionCommand().equals("configuration wizard")) { ConfigurationWizard.startWizard(Cooja.getTopParentContainer(), Cooja.this); } else { logger.warn("Unhandled action: " + e.getActionCommand()); } } } // // VARIOUS HELP METHODS //// /** * Help method that tries to load and initialize a class with given name. * * @param <N> Class extending given class type * @param classType Class type * @param className Class name * @return Class extending given class type or null if not found */ public <N extends Object> Class<? extends N> tryLoadClass( Object callingObject, Class<N> classType, String className) { if (callingObject != null) { try { return callingObject.getClass().getClassLoader().loadClass(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } try { return Class.forName(className).asSubclass(classType); } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } if (!isVisualizedInApplet()) { try { if (projectDirClassLoader != null) { return projectDirClassLoader.loadClass(className).asSubclass( classType); } } catch (NoClassDefFoundError e) { } catch (ClassNotFoundException e) { } catch (UnsupportedClassVersionError e) { } } return null; } private ClassLoader createClassLoader(Collection<COOJAProject> projects) throws ClassLoaderCreationException { return createClassLoader(ClassLoader.getSystemClassLoader(), projects); } public static File findJarFile(File projectDir, String jarfile) { File fp = new File(jarfile); if (!fp.exists()) { fp = new File(projectDir, jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "java/lib/" + jarfile); } if (!fp.exists()) { fp = new File(projectDir, "lib/" + jarfile); } return fp.exists() ? fp : null; } private ClassLoader createClassLoader(ClassLoader parent, Collection<COOJAProject> projects) throws ClassLoaderCreationException { if (projects == null || projects.isEmpty()) { return parent; } /* Create class loader from JARs */ ArrayList<URL> urls = new ArrayList<URL>(); for (COOJAProject project: projects) { File projectDir = project.dir; try { urls.add((new File(projectDir, "java")).toURI().toURL()); // Read configuration to check if any JAR files should be loaded ProjectConfig projectConfig = new ProjectConfig(false); projectConfig.appendProjectDir(projectDir); String[] projectJarFiles = projectConfig.getStringArrayValue( Cooja.class, "JARFILES"); if (projectJarFiles != null && projectJarFiles.length > 0) { for (String jarfile : projectJarFiles) { File jarpath = findJarFile(projectDir, jarfile); if (jarpath == null) { throw new FileNotFoundException(jarfile); } urls.add(jarpath.toURI().toURL()); } } } catch (Exception e) { logger.fatal("Error when trying to read JAR-file in " + projectDir + ": " + e); throw (ClassLoaderCreationException) new ClassLoaderCreationException( "Error when trying to read JAR-file in " + projectDir).initCause(e); } } URL[] urlsArray = urls.toArray(new URL[urls.size()]); /* TODO Load from webserver if applet */ return new URLClassLoader(urlsArray, parent); } /** * Help method that returns the description for given object. This method * reads from the object's class annotations if existing. Otherwise it returns * the simple class name of object's class. * * @param object * Object * @return Description */ public static String getDescriptionOf(Object object) { return getDescriptionOf(object.getClass()); } /** * Help method that returns the description for given class. This method reads * from class annotations if existing. Otherwise it returns the simple class * name. * * @param clazz * Class * @return Description */ public static String getDescriptionOf(Class<? extends Object> clazz) { if (clazz.isAnnotationPresent(ClassDescription.class)) { return clazz.getAnnotation(ClassDescription.class).value(); } return clazz.getSimpleName(); } /** * Help method that returns the abstraction level description for given mote type class. * * @param clazz * Class * @return Description */ public static String getAbstractionLevelDescriptionOf(Class<? extends MoteType> clazz) { if (clazz.isAnnotationPresent(AbstractionLevelDescription.class)) { return clazz.getAnnotation(AbstractionLevelDescription.class).value(); } return null; } /** * Load configurations and create a GUI. * * @param args * null */ public static void main(String[] args) { String logConfigFile = null; Long randomSeed = null; for (String element : args) { if (element.startsWith("-log4j=")) { String arg = element.substring("-log4j=".length()); logConfigFile = arg; } } try { // Configure logger if (logConfigFile != null) { if (new File(logConfigFile).exists()) { DOMConfigurator.configure(logConfigFile); } else { System.err.println("Failed to open " + logConfigFile); System.exit(1); } } else if (new File(LOG_CONFIG_FILE).exists()) { DOMConfigurator.configure(LOG_CONFIG_FILE); } else { // Used when starting from jar DOMConfigurator.configure(Cooja.class.getResource("/" + LOG_CONFIG_FILE)); } externalToolsUserSettingsFile = new File(System.getProperty("user.home"), EXTERNAL_TOOLS_USER_SETTINGS_FILENAME); } catch (AccessControlException e) { BasicConfigurator.configure(); externalToolsUserSettingsFile = null; } /* Look and Feel: Nimbus */ setLookAndFeel(); /* Warn at no JAVA_HOME */ String javaHome = System.getenv().get("JAVA_HOME"); if (javaHome == null || javaHome.equals("")) { logger.warn("JAVA_HOME environment variable not set, Cooja motes may not compile"); } // Parse general command arguments for (String element : args) { if (element.startsWith("-contiki=")) { String arg = element.substring("-contiki=".length()); Cooja.specifiedContikiPath = arg; } if (element.startsWith("-external_tools_config=")) { String arg = element.substring("-external_tools_config=".length()); File specifiedExternalToolsConfigFile = new File(arg); if (!specifiedExternalToolsConfigFile.exists()) { logger.fatal("Specified external tools configuration not found: " + specifiedExternalToolsConfigFile); specifiedExternalToolsConfigFile = null; System.exit(1); } else { Cooja.externalToolsUserSettingsFile = specifiedExternalToolsConfigFile; Cooja.externalToolsUserSettingsFileReadOnly = true; } } if (element.startsWith("-random-seed=")) { String arg = element.substring("-random-seed=".length()); try { randomSeed = Long.valueOf(arg); } catch (Exception e) { logger.error("Failed to convert \"" + arg +"\" to an integer."); } } } // Check if simulator should be quick-started if (args.length > 0 && args[0].startsWith("-quickstart=")) { String contikiApp = args[0].substring("-quickstart=".length()); /* Cygwin fix */ if (contikiApp.startsWith("/cygdrive/")) { char driveCharacter = contikiApp.charAt("/cygdrive/".length()); contikiApp = contikiApp.replace("/cygdrive/" + driveCharacter + "/", driveCharacter + ":/"); } Simulation sim = null; if (contikiApp.endsWith(".csc")) { sim = quickStartSimulationConfig(new File(contikiApp), true, randomSeed); } else { if (contikiApp.endsWith(".cooja")) { contikiApp = contikiApp.substring(0, contikiApp.length() - ".cooja".length()); } if (!contikiApp.endsWith(".c")) { contikiApp += ".c"; } sim = quickStartSimulation(contikiApp); } if (sim == null) { System.exit(1); } } else if (args.length > 0 && args[0].startsWith("-nogui=")) { /* Load simulation */ String config = args[0].substring("-nogui=".length()); File configFile = new File(config); Simulation sim = quickStartSimulationConfig(configFile, false, randomSeed); if (sim == null) { System.exit(1); } Cooja gui = sim.getCooja(); /* Make sure at least one test editor is controlling the simulation */ boolean hasEditor = false; for (Plugin startedPlugin : gui.startedPlugins) { if (startedPlugin instanceof ScriptRunner) { hasEditor = true; break; } } /* Backwards compatibility: * simulation has no test editor, but has external (old style) test script. * We will manually start a test editor from here. */ if (!hasEditor) { File scriptFile = new File(config.substring(0, config.length()-4) + ".js"); if (scriptFile.exists()) { logger.info("Detected old simulation test, starting test editor manually from: " + scriptFile); ScriptRunner plugin = (ScriptRunner) gui.tryStartPlugin(ScriptRunner.class, gui, sim, null); if (plugin == null) { System.exit(1); } plugin.updateScript(scriptFile); try { plugin.setScriptActive(true); } catch (Exception e) { logger.fatal("Error: " + e.getMessage(), e); System.exit(1); } } else { logger.fatal("No test editor controlling simulation, aborting"); System.exit(1); } } sim.setSpeedLimit(null); sim.startSimulation(); } else if (args.length > 0 && args[0].startsWith("-applet")) { String tmpWebPath=null, tmpBuildPath=null, tmpEsbFirmware=null, tmpSkyFirmware=null; for (int i = 1; i < args.length; i++) { if (args[i].startsWith("-web=")) { tmpWebPath = args[i].substring("-web=".length()); } else if (args[i].startsWith("-sky_firmware=")) { tmpSkyFirmware = args[i].substring("-sky_firmware=".length()); } else if (args[i].startsWith("-esb_firmware=")) { tmpEsbFirmware = args[i].substring("-esb_firmware=".length()); } else if (args[i].startsWith("-build=")) { tmpBuildPath = args[i].substring("-build=".length()); } } // Applet start-up final String webPath = tmpWebPath, buildPath = tmpBuildPath; final String skyFirmware = tmpSkyFirmware, esbFirmware = tmpEsbFirmware; javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); applet = CoojaApplet.applet; Cooja gui = new Cooja(desktop); Cooja.setExternalToolsSetting("PATH_CONTIKI_BUILD", buildPath); Cooja.setExternalToolsSetting("PATH_CONTIKI_WEB", webPath); Cooja.setExternalToolsSetting("SKY_FIRMWARE", skyFirmware); Cooja.setExternalToolsSetting("ESB_FIRMWARE", esbFirmware); configureApplet(gui, false); } }); } else { // Frame start-up javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JDesktopPane desktop = createDesktopPane(); frame = new JFrame(WINDOW_TITLE); Cooja gui = new Cooja(desktop); configureFrame(gui, false); } }); } } /** * Loads a simulation configuration from given file. * * When loading Contiki mote types, the libraries must be recompiled. User may * change mote type settings at this point. * * @see #saveSimulationConfig(File) * @param file * File to read * @return New simulation or null if recompiling failed or aborted * @throws UnsatisfiedLinkError * If associated libraries could not be loaded */ public Simulation loadSimulationConfig(File file, boolean quick, Long manualRandomSeed) throws UnsatisfiedLinkError, SimulationCreationException { this.currentConfigFile = file; /* Used to generate config relative paths */ try { this.currentConfigFile = this.currentConfigFile.getCanonicalFile(); } catch (IOException e) { } try { SAXBuilder builder = new SAXBuilder(); InputStream in = new FileInputStream(file); if (file.getName().endsWith(".gz")) { in = new GZIPInputStream(in); } Document doc = builder.build(in); Element root = doc.getRootElement(); in.close(); return loadSimulationConfig(root, quick, manualRandomSeed); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException("Config not wellformed").initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException("Load simulation error").initCause(e); } } public Simulation loadSimulationConfig(Element root, boolean quick, Long manualRandomSeed) throws SimulationCreationException { Simulation newSim = null; try { // Check that config file version is correct if (!root.getName().equals("simconf")) { logger.fatal("Not a valid Cooja simulation config."); return null; } /* Verify extension directories */ boolean projectsOk = verifyProjects(root.getChildren(), !quick); /* GENERATE UNIQUE MOTE TYPE IDENTIFIERS */ root.detach(); String configString = new XMLOutputter().outputString(new Document(root)); /* Locate Contiki mote types in config */ Properties moteTypeIDMappings = new Properties(); String identifierExtraction = ContikiMoteType.class.getName() + "[\\s\\n]*<identifier>([^<]*)</identifier>"; Matcher matcher = Pattern.compile(identifierExtraction).matcher(configString); while (matcher.find()) { moteTypeIDMappings.setProperty(matcher.group(1), ""); } /* Create old to new identifier mappings */ Enumeration<Object> existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); MoteType[] existingMoteTypes = null; if (mySimulation != null) { existingMoteTypes = mySimulation.getMoteTypes(); } ArrayList<Object> reserved = new ArrayList<Object>(); reserved.addAll(moteTypeIDMappings.keySet()); reserved.addAll(moteTypeIDMappings.values()); String newID = ContikiMoteType.generateUniqueMoteTypeID(existingMoteTypes, reserved); moteTypeIDMappings.setProperty(existingIdentifier, newID); } /* Create new config */ existingIdentifiers = moteTypeIDMappings.keys(); while (existingIdentifiers.hasMoreElements()) { String existingIdentifier = (String) existingIdentifiers.nextElement(); configString = configString.replaceAll( "<identifier>" + existingIdentifier + "</identifier>", "<identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</identifier>"); configString = configString.replaceAll( "<motetype_identifier>" + existingIdentifier + "</motetype_identifier>", "<motetype_identifier>" + moteTypeIDMappings.get(existingIdentifier) + "</motetype_identifier>"); } /* Replace existing config */ root = new SAXBuilder().build(new StringReader(configString)).getRootElement(); // Create new simulation from config for (Object element : root.getChildren()) { if (((Element) element).getName().equals("simulation")) { Collection<Element> config = ((Element) element).getChildren(); newSim = new Simulation(this); System.gc(); boolean createdOK = newSim.setConfigXML(config, !quick, manualRandomSeed); if (!createdOK) { logger.info("Simulation not loaded"); return null; } } } // Restart plugins from config setPluginsConfigXML(root.getChildren(), newSim, !quick); } catch (JDOMException e) { throw (SimulationCreationException) new SimulationCreationException( "Configuration file not wellformed: " + e.getMessage()).initCause(e); } catch (IOException e) { throw (SimulationCreationException) new SimulationCreationException( "No access to configuration file: " + e.getMessage()).initCause(e); } catch (MoteTypeCreationException e) { throw (SimulationCreationException) new SimulationCreationException( "Mote type creation error: " + e.getMessage()).initCause(e); } catch (Exception e) { throw (SimulationCreationException) new SimulationCreationException( "Unknown error: " + e.getMessage()).initCause(e); } return newSim; } /** * Saves current simulation configuration to given file and notifies * observers. * * @see #loadSimulationConfig(File, boolean) * @param file * File to write */ public void saveSimulationConfig(File file) { this.currentConfigFile = file; /* Used to generate config relative paths */ try { this.currentConfigFile = this.currentConfigFile.getCanonicalFile(); } catch (IOException e) { } try { // Create and write to document Document doc = new Document(extractSimulationConfig()); OutputStream out = new FileOutputStream(file); if (file.getName().endsWith(".gz")) { out = new GZIPOutputStream(out); } XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); outputter.output(doc, out); out.close(); logger.info("Saved to file: " + file.getAbsolutePath()); } catch (Exception e) { logger.warn("Exception while saving simulation config: " + e); e.printStackTrace(); } } public Element extractSimulationConfig() { // Create simulation config Element root = new Element("simconf"); /* Store extension directories meta data */ for (COOJAProject project: currentProjects) { Element projectElement = new Element("project"); projectElement.addContent(createPortablePath(project.dir).getPath().replaceAll("\\\\", "/")); projectElement.setAttribute("EXPORT", "discard"); root.addContent(projectElement); } Element simulationElement = new Element("simulation"); simulationElement.addContent(mySimulation.getConfigXML()); root.addContent(simulationElement); // Create started plugins config Collection<Element> pluginsConfig = getPluginsConfigXML(); if (pluginsConfig != null) { root.addContent(pluginsConfig); } return root; } /** * Returns started plugins config. * * @return Config or null */ public Collection<Element> getPluginsConfigXML() { ArrayList<Element> config = new ArrayList<Element>(); Element pluginElement, pluginSubElement; /* Loop over all plugins */ for (Plugin startedPlugin : startedPlugins) { int pluginType = startedPlugin.getClass().getAnnotation(PluginType.class).value(); // Ignore GUI plugins if (pluginType == PluginType.COOJA_PLUGIN || pluginType == PluginType.COOJA_STANDARD_PLUGIN) { continue; } pluginElement = new Element("plugin"); pluginElement.setText(startedPlugin.getClass().getName()); // Create mote argument config (if mote plugin) if (pluginType == PluginType.MOTE_PLUGIN) { pluginSubElement = new Element("mote_arg"); Mote taggedMote = ((MotePlugin) startedPlugin).getMote(); for (int moteNr = 0; moteNr < mySimulation.getMotesCount(); moteNr++) { if (mySimulation.getMote(moteNr) == taggedMote) { pluginSubElement.setText(Integer.toString(moteNr)); pluginElement.addContent(pluginSubElement); break; } } } // Create plugin specific configuration Collection<Element> pluginXML = startedPlugin.getConfigXML(); if (pluginXML != null) { pluginSubElement = new Element("plugin_config"); pluginSubElement.addContent(pluginXML); pluginElement.addContent(pluginSubElement); } // If plugin is visualizer plugin, create visualization arguments if (startedPlugin.getCooja() != null) { JInternalFrame pluginFrame = startedPlugin.getCooja(); pluginSubElement = new Element("width"); pluginSubElement.setText("" + pluginFrame.getSize().width); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("z"); pluginSubElement.setText("" + getDesktopPane().getComponentZOrder(pluginFrame)); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("height"); pluginSubElement.setText("" + pluginFrame.getSize().height); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_x"); pluginSubElement.setText("" + pluginFrame.getLocation().x); pluginElement.addContent(pluginSubElement); pluginSubElement = new Element("location_y"); pluginSubElement.setText("" + pluginFrame.getLocation().y); pluginElement.addContent(pluginSubElement); if (pluginFrame.isIcon()) { pluginSubElement = new Element("minimized"); pluginSubElement.setText("" + true); pluginElement.addContent(pluginSubElement); } } config.add(pluginElement); } return config; } public boolean verifyProjects(Collection<Element> configXML, boolean visAvailable) { boolean allOk = true; /* Match current extensions against extensions in simulation config */ for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("project")) { File projectFile = restorePortablePath(new File(pluginElement.getText())); try { projectFile = projectFile.getCanonicalFile(); } catch (IOException e) { } boolean found = false; for (COOJAProject currentProject: currentProjects) { if (projectFile.getPath().replaceAll("\\\\", "/"). equals(currentProject.dir.getPath().replaceAll("\\\\", "/"))) { found = true; break; } } if (!found) { logger.warn("Loaded simulation may depend on not found extension: '" + projectFile + "'"); allOk = false; } } } return allOk; } /** * Starts plugins with arguments in given config. * * @param configXML * Config XML elements * @param simulation * Simulation on which to start plugins * @return True if all plugins started, false otherwise */ public boolean setPluginsConfigXML(Collection<Element> configXML, Simulation simulation, boolean visAvailable) { for (final Element pluginElement : configXML.toArray(new Element[0])) { if (pluginElement.getName().equals("plugin")) { // Read plugin class String pluginClassName = pluginElement.getText().trim(); /* Backwards compatibility: se.sics -> org.contikios */ if (pluginClassName.startsWith("se.sics")) { pluginClassName = pluginClassName.replaceFirst("se\\.sics", "org.contikios"); } /* Backwards compatibility: old visualizers were replaced */ if (pluginClassName.equals("org.contikios.cooja.plugins.VisUDGM") || pluginClassName.equals("org.contikios.cooja.plugins.VisBattery") || pluginClassName.equals("org.contikios.cooja.plugins.VisTraffic") || pluginClassName.equals("org.contikios.cooja.plugins.VisState") || pluginClassName.equals("org.contikios.cooja.plugins.VisUDGM")) { logger.warn("Old simulation config detected: visualizers have been remade"); pluginClassName = "org.contikios.cooja.plugins.Visualizer"; } Class<? extends Plugin> pluginClass = tryLoadClass(this, Plugin.class, pluginClassName); if (pluginClass == null) { logger.fatal("Could not load plugin class: " + pluginClassName); return false; } // Parse plugin mote argument (if any) Mote mote = null; for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("mote_arg")) { int moteNr = Integer.parseInt(pluginSubElement.getText()); if (moteNr >= 0 && moteNr < simulation.getMotesCount()) { mote = simulation.getMote(moteNr); } } } /* Start plugin */ final Plugin startedPlugin = tryStartPlugin(pluginClass, this, simulation, mote, false); if (startedPlugin == null) { continue; } /* Apply plugin specific configuration */ for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("plugin_config")) { startedPlugin.setConfigXML(pluginSubElement.getChildren(), visAvailable); } } /* Activate plugin */ startedPlugin.startPlugin(); /* If Cooja not visualized, ignore window configuration */ if (startedPlugin.getCooja() == null) { continue; } // If plugin is visualizer plugin, parse visualization arguments new RunnableInEDT<Boolean>() { public Boolean work() { Dimension size = new Dimension(100, 100); Point location = new Point(100, 100); for (Element pluginSubElement : (List<Element>) pluginElement.getChildren()) { if (pluginSubElement.getName().equals("width")) { size.width = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setSize(size); } else if (pluginSubElement.getName().equals("height")) { size.height = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setSize(size); } else if (pluginSubElement.getName().equals("z")) { int zOrder = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().putClientProperty("zorder", zOrder); } else if (pluginSubElement.getName().equals("location_x")) { location.x = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setLocation(location); } else if (pluginSubElement.getName().equals("location_y")) { location.y = Integer.parseInt(pluginSubElement.getText()); startedPlugin.getCooja().setLocation(location); } else if (pluginSubElement.getName().equals("minimized")) { boolean minimized = Boolean.parseBoolean(pluginSubElement.getText()); final JInternalFrame pluginGUI = startedPlugin.getCooja(); if (minimized && pluginGUI != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { pluginGUI.setIcon(true); } catch (PropertyVetoException e) { } }; }); } } } showPlugin(startedPlugin); return true; } }.invokeAndWait(); } } /* Z order visualized plugins */ try { for (int z=0; z < getDesktopPane().getAllFrames().length; z++) { for (JInternalFrame plugin : getDesktopPane().getAllFrames()) { if (plugin.getClientProperty("zorder") == null) { continue; } int zOrder = ((Integer) plugin.getClientProperty("zorder")).intValue(); if (zOrder != z) { continue; } getDesktopPane().setComponentZOrder(plugin, zOrder); if (z == 0) { plugin.setSelected(true); } plugin.putClientProperty("zorder", null); break; } getDesktopPane().repaint(); } } catch (Exception e) { } return true; } public class ParseProjectsException extends Exception { private static final long serialVersionUID = 1508168026300714850L; public ParseProjectsException(String message) { super(message); } } public class ClassLoaderCreationException extends Exception { private static final long serialVersionUID = 1578001681266277774L; public ClassLoaderCreationException(String message) { super(message); } } public class SimulationCreationException extends Exception { private static final long serialVersionUID = -2414899187405770448L; public SimulationCreationException(String message) { super(message); } } public class PluginConstructionException extends Exception { private static final long serialVersionUID = 8004171223353676751L; public PluginConstructionException(String message) { super(message); } } /** * A simple error dialog with compilation output and stack trace. * * @param parentComponent * Parent component * @param title * Title of error window * @param exception * Exception causing window to be shown * @param retryAvailable * If true, a retry option is presented * @return Retry failed operation */ public static boolean showErrorDialog(final Component parentComponent, final String title, final Throwable exception, final boolean retryAvailable) { return new RunnableInEDT<Boolean>() { public Boolean work() { JTabbedPane tabbedPane = new JTabbedPane(); final JDialog errorDialog; if (parentComponent instanceof Dialog) { errorDialog = new JDialog((Dialog) parentComponent, title, true); } else if (parentComponent instanceof Frame) { errorDialog = new JDialog((Frame) parentComponent, title, true); } else { errorDialog = new JDialog((Frame) null, title); } Box buttonBox = Box.createHorizontalBox(); if (exception != null) { /* Contiki error */ if (exception instanceof ContikiError) { String contikiError = ((ContikiError) exception).getContikiError(); MessageList list = new MessageList(); for (String l: contikiError.split("\n")) { list.addMessage(l); } list.addPopupMenuItem(null, true); tabbedPane.addTab("Contiki error", new JScrollPane(list)); } /* Compilation output */ MessageList compilationOutput = null; if (exception instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception).getCompilationOutput(); } else if (exception.getCause() != null && exception.getCause() instanceof MoteTypeCreationException && ((MoteTypeCreationException) exception.getCause()).hasCompilationOutput()) { compilationOutput = ((MoteTypeCreationException) exception.getCause()).getCompilationOutput(); } if (compilationOutput != null) { compilationOutput.addPopupMenuItem(null, true); tabbedPane.addTab("Compilation output", new JScrollPane(compilationOutput)); } /* Stack trace */ MessageList stackTrace = new MessageList(); PrintStream printStream = stackTrace.getInputStream(MessageList.NORMAL); exception.printStackTrace(printStream); stackTrace.addPopupMenuItem(null, true); tabbedPane.addTab("Java stack trace", new JScrollPane(stackTrace)); /* Exception message */ buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(new JLabel(exception.getMessage())); buttonBox.add(Box.createHorizontalStrut(10)); } buttonBox.add(Box.createHorizontalGlue()); if (retryAvailable) { Action retryAction = new AbstractAction() { private static final long serialVersionUID = 2370456199250998435L; public void actionPerformed(ActionEvent e) { errorDialog.setTitle("-RETRY-"); errorDialog.dispose(); } }; JButton retryButton = new JButton(retryAction); retryButton.setText("Retry Ctrl+R"); buttonBox.add(retryButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK, false), "retry"); errorDialog.getRootPane().getActionMap().put("retry", retryAction); } AbstractAction closeAction = new AbstractAction(){ private static final long serialVersionUID = 6225539435993362733L; public void actionPerformed(ActionEvent e) { errorDialog.dispose(); } }; JButton closeButton = new JButton(closeAction); closeButton.setText("Close"); buttonBox.add(closeButton); InputMap inputMap = errorDialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "close"); errorDialog.getRootPane().getActionMap().put("close", closeAction); errorDialog.getRootPane().setDefaultButton(closeButton); errorDialog.getContentPane().add(BorderLayout.CENTER, tabbedPane); errorDialog.getContentPane().add(BorderLayout.SOUTH, buttonBox); errorDialog.setSize(700, 500); errorDialog.setLocationRelativeTo(parentComponent); errorDialog.setVisible(true); /* BLOCKS */ if (errorDialog.getTitle().equals("-RETRY-")) { return true; } return false; } }.invokeAndWait(); } private static void showWarningsDialog(final Frame parent, final String[] warnings) { new RunnableInEDT<Boolean>() { public Boolean work() { final JDialog dialog = new JDialog(parent, "Compilation warnings", false); Box buttonBox = Box.createHorizontalBox(); /* Warnings message list */ MessageList compilationOutput = new MessageList(); for (String w: warnings) { compilationOutput.addMessage(w, MessageList.ERROR); } compilationOutput.addPopupMenuItem(null, true); /* Checkbox */ buttonBox.add(Box.createHorizontalGlue()); JCheckBox hideButton = new JCheckBox("Hide compilation warnings", false); hideButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Cooja.setExternalToolsSetting("HIDE_WARNINGS", "" + ((JCheckBox)e.getSource()).isSelected()); }; }); buttonBox.add(Box.createHorizontalStrut(10)); buttonBox.add(hideButton); /* Close on escape */ AbstractAction closeAction = new AbstractAction(){ private static final long serialVersionUID = 2646163984382201634L; public void actionPerformed(ActionEvent e) { dialog.dispose(); } }; InputMap inputMap = dialog.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "close"); dialog.getRootPane().getActionMap().put("close", closeAction); /* Layout */ dialog.getContentPane().add(BorderLayout.CENTER, new JScrollPane(compilationOutput)); dialog.getContentPane().add(BorderLayout.SOUTH, buttonBox); dialog.setSize(700, 500); dialog.setLocationRelativeTo(parent); dialog.setVisible(true); return true; } }.invokeAndWait(); } /** * Runs work method in event dispatcher thread. * Worker method returns a value. * * @author Fredrik Osterlind */ public static abstract class RunnableInEDT<T> { private T val; /** * Work method to be implemented. * * @return Return value */ public abstract T work(); /** * Runs worker method in event dispatcher thread. * * @see #work() * @return Worker method return value */ public T invokeAndWait() { if(java.awt.EventQueue.isDispatchThread()) { return RunnableInEDT.this.work(); } try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { val = RunnableInEDT.this.work(); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return val; } } /** * This method can be used by various different modules in the simulator to * indicate for example that a mote has been selected. All mote highlight * listeners will be notified. An example application of mote highlightinh is * a simulator visualizer that highlights the mote. * * @see #addMoteHighlightObserver(Observer) * @param m * Mote to highlight */ public void signalMoteHighlight(Mote m) { moteHighlightObservable.setChangedAndNotify(m); } /** * Adds directed relation between given motes. * * @param source Source mote * @param dest Destination mote */ public void addMoteRelation(Mote source, Mote dest) { addMoteRelation(source, dest, null); } /** * Adds directed relation between given motes. * * @param source Source mote * @param dest Destination mote * @param color The color to use when visualizing the mote relation */ public void addMoteRelation(Mote source, Mote dest, Color color) { if (source == null || dest == null) { return; } removeMoteRelation(source, dest); /* Unique relations */ moteRelations.add(new MoteRelation(source, dest, color)); moteRelationObservable.setChangedAndNotify(); } /** * Removes the relations between given motes. * * @param source Source mote * @param dest Destination mote */ public void removeMoteRelation(Mote source, Mote dest) { if (source == null || dest == null) { return; } MoteRelation[] arr = getMoteRelations(); for (MoteRelation r: arr) { if (r.source == source && r.dest == dest) { moteRelations.remove(r); /* Relations are unique */ moteRelationObservable.setChangedAndNotify(); break; } } } /** * @return All current mote relations. * * @see #addMoteRelationsObserver(Observer) */ public MoteRelation[] getMoteRelations() { return moteRelations.toArray(new MoteRelation[moteRelations.size()]); } /** * Adds mote relation observer. * Typically used by visualizer plugins. * * @param newObserver Observer */ public void addMoteRelationsObserver(Observer newObserver) { moteRelationObservable.addObserver(newObserver); } /** * Removes mote relation observer. * Typically used by visualizer plugins. * * @param observer Observer */ public void deleteMoteRelationsObserver(Observer observer) { moteRelationObservable.deleteObserver(observer); } /** * Tries to convert given file to be "portable". * The portable path is either relative to Contiki, or to the configuration (.csc) file. * * If this method fails, it returns the original file. * * @param file Original file * @return Portable file, or original file is conversion failed */ public File createPortablePath(File file) { return createPortablePath(file, true); } public File createPortablePath(File file, boolean allowConfigRelativePaths) { File portable = null; portable = createContikiRelativePath(file); if (portable != null) { /*logger.info("Generated Contiki relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } if (allowConfigRelativePaths) { portable = createConfigRelativePath(file); if (portable != null) { /*logger.info("Generated config relative path '" + file.getPath() + "' to '" + portable.getPath() + "'");*/ return portable; } } logger.warn("Path is not portable: '" + file.getPath()); return file; } /** * Tries to restore a previously "portable" file to be "absolute". * If the given file already exists, no conversion is performed. * * @see #createPortablePath(File) * @param file Portable file * @return Absolute file */ public File restorePortablePath(File file) { if (file == null || file.exists()) { /* No conversion possible/needed */ return file; } File absolute = null; absolute = restoreContikiRelativePath(file); if (absolute != null) { /*logger.info("Restored Contiki relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } absolute = restoreConfigRelativePath(file); if (absolute != null) { /*logger.info("Restored config relative path '" + file.getPath() + "' to '" + absolute.getPath() + "'");*/ return absolute; } /*logger.info("Portable path was not restored: '" + file.getPath());*/ return file; } private final static String[][] PATH_IDENTIFIER = { {"[CONTIKI_DIR]","PATH_CONTIKI",""}, {"[COOJA_DIR]","PATH_COOJA","/tools/cooja"}, {"[APPS_DIR]","PATH_APPS","/tools/cooja/apps"} }; private File createContikiRelativePath(File file) { try { int elem = PATH_IDENTIFIER.length; File path[] = new File [elem]; String canonicals[] = new String[elem]; int match = -1; int mlength = 0; String fileCanonical = file.getCanonicalPath(); //No so nice, but goes along with GUI.getExternalToolsSetting String defp = Cooja.getExternalToolsSetting("PATH_CONTIKI", null); for(int i = 0; i < elem; i++){ path[i] = new File(Cooja.getExternalToolsSetting(PATH_IDENTIFIER[i][1], defp + PATH_IDENTIFIER[i][2])); canonicals[i] = path[i].getCanonicalPath(); if (fileCanonical.startsWith(canonicals[i])){ if(mlength < canonicals[i].length()){ mlength = canonicals[i].length(); match = i; } } } if(match == -1) return null; /* Replace Contiki's canonical path with Contiki identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(canonicals[match]), java.util.regex.Matcher.quoteReplacement(PATH_IDENTIFIER[match][0])); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreContikiRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to Contiki relative path: " + e1.getMessage());*/ return null; } } private File restoreContikiRelativePath(File portable) { int elem = PATH_IDENTIFIER.length; File path = null; String canonical = null; try { String portablePath = portable.getPath(); int i = 0; //logger.info("PPATH: " + portablePath); for(; i < elem; i++){ if (portablePath.startsWith(PATH_IDENTIFIER[i][0])) break; } if(i == elem) return null; //logger.info("Found: " + PATH_IDENTIFIER[i][0]); //No so nice, but goes along with GUI.getExternalToolsSetting String defp = Cooja.getExternalToolsSetting("PATH_CONTIKI", null); path = new File(Cooja.getExternalToolsSetting(PATH_IDENTIFIER[i][1], defp + PATH_IDENTIFIER[i][2])); //logger.info("Config: " + PATH_IDENTIFIER[i][1] + ", " + defp + PATH_IDENTIFIER[i][2] + " = " + path.toString()); canonical = path.getCanonicalPath(); File absolute = new File(portablePath.replace(PATH_IDENTIFIER[i][0], canonical)); if(!absolute.exists()){ logger.warn("Replaced " + portable + " with " + absolute.toString() + " (default: "+ defp + PATH_IDENTIFIER[i][2] +"), but could not find it. This does not have to be an error, as the file might be created later."); } return absolute; } catch (IOException e) { return null; } } private final static String PATH_CONFIG_IDENTIFIER = "[CONFIG_DIR]"; public File currentConfigFile = null; /* Used to generate config relative paths */ private File createConfigRelativePath(File file) { String id = PATH_CONFIG_IDENTIFIER; if (currentConfigFile == null) { return null; } try { File configPath = currentConfigFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String configCanonical = configPath.getCanonicalPath(); String fileCanonical = file.getCanonicalPath(); if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow one parent directory */ File parent = new File(configCanonical).getParentFile(); if (parent != null) { configCanonical = parent.getCanonicalPath(); id += "/.."; } } if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow two parent directories */ File parent = new File(configCanonical).getParentFile(); if (parent != null) { configCanonical = parent.getCanonicalPath(); id += "/.."; } } if (!fileCanonical.startsWith(configCanonical)) { /* SPECIAL CASE: Allow three parent directories */ File parent = new File(configCanonical).getParentFile(); if (parent != null) { configCanonical = parent.getCanonicalPath(); id += "/.."; } } if (!fileCanonical.startsWith(configCanonical)) { /* File is not in a config subdirectory */ /*logger.info("File is not in a config subdirectory: " + file.getAbsolutePath());*/ return null; } /* Replace config's canonical path with config identifier */ String portablePath = fileCanonical.replaceFirst( java.util.regex.Matcher.quoteReplacement(configCanonical), java.util.regex.Matcher.quoteReplacement(id)); File portable = new File(portablePath); /* Verify conversion */ File verify = restoreConfigRelativePath(portable); if (verify == null || !verify.exists()) { /* Error: did file even exist pre-conversion? */ return null; } return portable; } catch (IOException e1) { /*logger.warn("Error when converting to config relative path: " + e1.getMessage());*/ return null; } } private File restoreConfigRelativePath(File portable) { return restoreConfigRelativePath(currentConfigFile, portable); } public static File restoreConfigRelativePath(File configFile, File portable) { if (configFile == null) { return null; } File configPath = configFile.getParentFile(); if (configPath == null) { /* File is in current directory */ configPath = new File(""); } String portablePath = portable.getPath(); if (!portablePath.startsWith(PATH_CONFIG_IDENTIFIER)) { return null; } File absolute = new File(portablePath.replace(PATH_CONFIG_IDENTIFIER, configPath.getAbsolutePath())); return absolute; } private static JProgressBar PROGRESS_BAR = null; private static ArrayList<String> PROGRESS_WARNINGS = new ArrayList<String>(); public static void setProgressMessage(String msg) { setProgressMessage(msg, MessageList.NORMAL); } public static void setProgressMessage(String msg, int type) { if (PROGRESS_BAR != null && PROGRESS_BAR.isShowing()) { PROGRESS_BAR.setString(msg); PROGRESS_BAR.setStringPainted(true); } if (type != MessageList.NORMAL) { PROGRESS_WARNINGS.add(msg); } } /** * Load quick help for given object or identifier. Note that this method does not * show the quick help pane. * * @param obj If string: help identifier. Else, the class name of the argument * is used as help identifier. */ public void loadQuickHelp(final Object obj) { if (obj == null) { return; } String key; if (obj instanceof String) { key = (String) obj; } else { key = obj.getClass().getName(); } String help = null; if (obj instanceof HasQuickHelp) { help = ((HasQuickHelp) obj).getQuickHelp(); } else { if (quickHelpProperties == null) { /* Load quickhelp.txt */ try { quickHelpProperties = new Properties(); quickHelpProperties.load(new FileReader("quickhelp.txt")); } catch (Exception e) { quickHelpProperties = null; help = "<html><b>Failed to read quickhelp.txt:</b><p>" + e.getMessage() + "</html>"; } } if (quickHelpProperties != null) { help = quickHelpProperties.getProperty(key); } } if (help != null) { quickHelpTextPane.setText("<html>" + help + "</html>"); } else { quickHelpTextPane.setText( "<html><b>" + getDescriptionOf(obj) +"</b>" + "<p>No help available</html>"); } quickHelpTextPane.setCaretPosition(0); } /* GUI actions */ abstract class GUIAction extends AbstractAction { private static final long serialVersionUID = 6946179457635198477L; public GUIAction(String name) { super(name); } public GUIAction(String name, int nmenomic) { this(name); putValue(Action.MNEMONIC_KEY, nmenomic); } public GUIAction(String name, KeyStroke accelerator) { this(name); putValue(Action.ACCELERATOR_KEY, accelerator); } public GUIAction(String name, int nmenomic, KeyStroke accelerator) { this(name, nmenomic); putValue(Action.ACCELERATOR_KEY, accelerator); } public abstract boolean shouldBeEnabled(); } GUIAction newSimulationAction = new GUIAction("New simulation...", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)) { private static final long serialVersionUID = 5053703908505299911L; public void actionPerformed(ActionEvent e) { cooja.doCreateSimulation(true); } public boolean shouldBeEnabled() { return true; } }; GUIAction closeSimulationAction = new GUIAction("Close simulation", KeyEvent.VK_C) { private static final long serialVersionUID = -4783032948880161189L; public void actionPerformed(ActionEvent e) { cooja.doRemoveSimulation(true); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction reloadSimulationAction = new GUIAction("Reload with same random seed", KeyEvent.VK_K, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK)) { private static final long serialVersionUID = 66579555555421977L; public void actionPerformed(ActionEvent e) { if (getSimulation() == null) { /* Reload last opened simulation */ final File file = getLastOpenedFile(); new Thread(new Runnable() { public void run() { cooja.doLoadConfig(true, true, file, null); } }).start(); return; } /* Reload current simulation */ long seed = getSimulation().getRandomSeed(); reloadCurrentSimulation(getSimulation().isRunning(), seed); } public boolean shouldBeEnabled() { return true; } }; GUIAction reloadRandomSimulationAction = new GUIAction("Reload with new random seed", KeyEvent.VK_N, KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)) { private static final long serialVersionUID = -4494402222740250203L; public void actionPerformed(ActionEvent e) { /* Replace seed before reloading */ if (getSimulation() != null) { getSimulation().setRandomSeed(getSimulation().getRandomSeed()+1); reloadSimulationAction.actionPerformed(null); } } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction saveSimulationAction = new GUIAction("Save simulation as...", KeyEvent.VK_S) { private static final long serialVersionUID = 1132582220401954286L; public void actionPerformed(ActionEvent e) { cooja.doSaveConfig(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return getSimulation() != null; } }; /* GUIAction closePluginsAction = new GUIAction("Close all plugins") { private static final long serialVersionUID = -37575622808266989L; public void actionPerformed(ActionEvent e) { Object[] plugins = startedPlugins.toArray(); for (Object plugin : plugins) { removePlugin((Plugin) plugin, false); } } public boolean shouldBeEnabled() { return !startedPlugins.isEmpty(); } };*/ GUIAction exportExecutableJARAction = new GUIAction("Export simulation...") { private static final long serialVersionUID = -203601967460630049L; public void actionPerformed(ActionEvent e) { getSimulation().stopSimulation(); /* Info message */ String[] options = new String[] { "OK", "Cancel" }; int n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "This function attempts to build an executable Cooja JAR from the current simulation.\n" + "The JAR will contain all simulation dependencies, including extension JAR files and mote firmware files.\n" + "\nExecutable simulations can be used to run already prepared simulations on several computers.\n" + "\nThis is an experimental feature.", "Export simulation to executable JAR", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); if (n != JOptionPane.OK_OPTION) { return; } /* Select output file */ JFileChooser fc = new JFileChooser(); FileFilter jarFilter = new FileFilter() { public boolean accept(File file) { if (file.isDirectory()) { return true; } if (file.getName().endsWith(".jar")) { return true; } return false; } public String getDescription() { return "Java archive"; } public String toString() { return ".jar"; } }; fc.setFileFilter(jarFilter); File suggest = new File(getExternalToolsSetting("EXECUTE_JAR_LAST", "cooja_simulation.jar")); fc.setSelectedFile(suggest); int returnVal = fc.showSaveDialog(Cooja.getTopParentContainer()); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File outputFile = fc.getSelectedFile(); if (outputFile.exists()) { options = new String[] { "Overwrite", "Cancel" }; n = JOptionPane.showOptionDialog( Cooja.getTopParentContainer(), "A file with the same name already exists.\nDo you want to remove it?", "Overwrite existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n != JOptionPane.YES_OPTION) { return; } outputFile.delete(); } final File finalOutputFile = outputFile; setExternalToolsSetting("EXECUTE_JAR_LAST", outputFile.getPath()); new Thread() { public void run() { try { ExecuteJAR.buildExecutableJAR(Cooja.this, finalOutputFile); } catch (RuntimeException ex) { JOptionPane.showMessageDialog(Cooja.getTopParentContainer(), ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } }.start(); } public boolean shouldBeEnabled() { return getSimulation() != null; } }; GUIAction exitCoojaAction = new GUIAction("Exit", 'x') { private static final long serialVersionUID = 7523822251658687665L; public void actionPerformed(ActionEvent e) { cooja.doQuit(true); } public boolean shouldBeEnabled() { if (isVisualizedInApplet()) { return false; } return true; } }; GUIAction startStopSimulationAction = new GUIAction("Start simulation", KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)) { private static final long serialVersionUID = 6750107157493939710L; public void actionPerformed(ActionEvent e) { /* Start/Stop current simulation */ Simulation s = getSimulation(); if (s == null) { return; } if (s.isRunning()) { s.stopSimulation(); } else { s.startSimulation(); } } public void setEnabled(boolean newValue) { if (getSimulation() == null) { putValue(NAME, "Start simulation"); } else if (getSimulation().isRunning()) { putValue(NAME, "Pause simulation"); } else { putValue(NAME, "Start simulation"); } super.setEnabled(newValue); } public boolean shouldBeEnabled() { return getSimulation() != null && getSimulation().isRunnable(); } }; class StartPluginGUIAction extends GUIAction { private static final long serialVersionUID = 7368495576372376196L; public StartPluginGUIAction(String name) { super(name); } public void actionPerformed(final ActionEvent e) { new Thread(new Runnable() { public void run() { Class<Plugin> pluginClass = (Class<Plugin>) ((JMenuItem) e.getSource()).getClientProperty("class"); Mote mote = (Mote) ((JMenuItem) e.getSource()).getClientProperty("mote"); tryStartPlugin(pluginClass, cooja, mySimulation, mote); } }).start(); } public boolean shouldBeEnabled() { return getSimulation() != null; } } GUIAction removeAllMotesAction = new GUIAction("Remove all motes") { private static final long serialVersionUID = 4709776747913364419L; public void actionPerformed(ActionEvent e) { Simulation s = getSimulation(); if (s.isRunning()) { s.stopSimulation(); } while (s.getMotesCount() > 0) { s.removeMote(getSimulation().getMote(0)); } } public boolean shouldBeEnabled() { Simulation s = getSimulation(); return s != null && s.getMotesCount() > 0; } }; GUIAction showQuickHelpAction = new GUIAction("Quick help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)) { private static final long serialVersionUID = 3151729036597971681L; public void actionPerformed(ActionEvent e) { if (!(e.getSource() instanceof JCheckBoxMenuItem)) { return; } boolean show = ((JCheckBoxMenuItem) e.getSource()).isSelected(); quickHelpTextPane.setVisible(show); quickHelpScroll.setVisible(show); setExternalToolsSetting("SHOW_QUICKHELP", new Boolean(show).toString()); ((JPanel)frame.getContentPane()).revalidate(); updateDesktopSize(getDesktopPane()); } public boolean shouldBeEnabled() { return true; } }; GUIAction showGettingStartedAction = new GUIAction("Getting started") { private static final long serialVersionUID = 2382848024856978524L; public void actionPerformed(ActionEvent e) { loadQuickHelp("GETTING_STARTED"); JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } public boolean shouldBeEnabled() { return true; } }; GUIAction showKeyboardShortcutsAction = new GUIAction("Keyboard shortcuts") { private static final long serialVersionUID = 2382848024856978524L; public void actionPerformed(ActionEvent e) { loadQuickHelp("KEYBOARD_SHORTCUTS"); JCheckBoxMenuItem checkBox = ((JCheckBoxMenuItem)showQuickHelpAction.getValue("checkbox")); if (checkBox == null) { return; } if (checkBox.isSelected()) { return; } checkBox.doClick(); } public boolean shouldBeEnabled() { return true; } }; GUIAction showBufferSettingsAction = new GUIAction("Buffer sizes...") { private static final long serialVersionUID = 7018661735211901837L; public void actionPerformed(ActionEvent e) { if (mySimulation == null) { return; } BufferSettings.showDialog(myDesktopPane, mySimulation); } public boolean shouldBeEnabled() { return mySimulation != null; } }; }
[cooja] Set location of newly created plugins relative to second last activated plugin. Setting the position based on the number of total inner frames was very inflexible and caused pad positioning for larger number of frames. Setting the location of new plugin frames to the second last activated one tries to meet two requirements: - Avoid covering the last activated plugin frame, i.e. the one that was active when new plugin start was invoked. - Set new plugin near an actively used desktop pane location and allow 'diagonal stacking'
tools/cooja/java/org/contikios/cooja/Cooja.java
[cooja] Set location of newly created plugins relative to second last activated plugin.
<ide><path>ools/cooja/java/org/contikios/cooja/Cooja.java <ide> return false; <ide> } <ide> <del> int nrFrames = myDesktopPane.getAllFrames().length; <ide> myDesktopPane.add(pluginFrame); <ide> <ide> /* Set size if not already specified by plugin */ <ide> pluginFrame.setSize(FRAME_STANDARD_WIDTH, FRAME_STANDARD_HEIGHT); <ide> } <ide> <del> /* Set location if not already visible */ <add> /* Set location if not already set */ <ide> if (pluginFrame.getLocation().x <= 0 && pluginFrame.getLocation().y <= 0) { <del> pluginFrame.setLocation( <del> nrFrames * FRAME_NEW_OFFSET, <del> nrFrames * FRAME_NEW_OFFSET); <add> pluginFrame.setLocation(determineNewPluginLocation()); <ide> } <ide> <ide> pluginFrame.setVisible(true); <ide> return true; <ide> } <ide> }.invokeAndWait(); <add> } <add> <add> /** <add> * Determines suitable location for placing new plugin. <add> * <p> <add> * If possible, this is below right of the second last activated <add> * internfal frame (offset is determined by FRAME_NEW_OFFSET). <add> * <add> * @return Resulting placement position <add> */ <add> private Point determineNewPluginLocation() { <add> Point topFrameLoc; <add> JInternalFrame[] iframes = myDesktopPane.getAllFrames(); <add> if (iframes.length > 1) { <add> topFrameLoc = iframes[1].getLocation(); <add> } else { <add> topFrameLoc = new Point( <add> myDesktopPane.getSize().width / 2, <add> myDesktopPane.getSize().height / 2); <add> } <add> return new Point( <add> topFrameLoc.x + FRAME_NEW_OFFSET, <add> topFrameLoc.y + FRAME_NEW_OFFSET); <ide> } <ide> <ide> /**
Java
epl-1.0
9ec5bbaf41d0bdfa789c5de24df467564e18c18c
0
theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,debrief/debrief,theanuradha/debrief,debrief/debrief,theanuradha/debrief,theanuradha/debrief,theanuradha/debrief,debrief/debrief,debrief/debrief
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package MWC.GUI.JFreeChart; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.chart.axis.TickUnits; import MWC.GUI.Properties.AbstractPropertyEditor; public class DateAxisEditor extends AbstractPropertyEditor { public static class DatedRNFormatter extends SimpleDateFormat { /** * */ private static final long serialVersionUID = 1L; /** * pattern for the on-the-day values. Note: we currently ignore this, since we just prepend the * date value as a 2-digit value */ @SuppressWarnings("unused") private final String _datePattern; /** * Construct a SimpleDateFormat using the given pattern in the default locale. <b>Note:</b> Not * all locales support SimpleDateFormat; for full generality, use the factory methods in the * DateFormat class. */ public DatedRNFormatter(final String pattern, final String datePattern) { super(pattern); _datePattern = datePattern; this.setTimeZone(TimeZone.getTimeZone("GMT")); } @SuppressWarnings("deprecation") @Override public StringBuffer format(final Date arg0, final StringBuffer arg1, final FieldPosition arg2) { StringBuffer timeBit = super.format(arg0, arg1, arg2); // see if we're on the exact day if ((arg0.getHours() == 0) && (arg0.getMinutes() == 0) && (arg0 .getSeconds() == 0)) { // ok, use the suffix final DecimalFormat df = new DecimalFormat("00"); final String prefix = df.format(arg0.getDate()); final StringBuffer res = new StringBuffer(); res.append(prefix); res.append(timeBit); timeBit = res; } return timeBit; } } /***************************************************************************** * class to store components of tick unit in accessible form ****************************************************************************/ public static class MWCDateTickUnitWrapper { public static MWCDateTickUnitWrapper getAutoScale() { return new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 0, null); } // //////////////////////////////////////////////// // member variables // //////////////////////////////////////////////// /** * components of DateTickUnit */ protected DateTickUnitType _unit; protected int _count; protected String _formatter; public MWCDateTickUnitWrapper(final DateTickUnitType unit, final int count, final String formatter) { _unit = unit; _count = count; _formatter = formatter; } public DateTickUnit getUnit() { DateTickUnit res = null; if (_formatter != DateAxisEditor.RELATIVE_DTG_FORMAT) { final SimpleDateFormat sdf = new SimpleDateFormat(_formatter); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); res = new OptimisedDateTickUnit(_unit, _count, sdf); } else { final SimpleDateFormat sdf = new SimpleDateFormat(_formatter); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); res = new OptimisedDateTickUnit(_unit, _count, sdf) { /** * */ private static final long serialVersionUID = 1L; /** * Formats a date. * * @param date * the date. * @return the formatted date. */ @Override public String dateToString(final Date date) { String res1 = null; // how many secs? final long secs = date.getTime() / 1000; res1 = secs + "s"; return res1; } }; } return res; } private String getUnitLabel() { switch (_unit.getCalendarField()) { case (Calendar.YEAR): return "Year"; case (Calendar.MONTH): return "Month"; case (Calendar.DAY_OF_MONTH): return "Day"; case (Calendar.HOUR): case (Calendar.HOUR_OF_DAY): return "Hour"; case (Calendar.MINUTE): return "Min"; case (Calendar.SECOND): return "Sec"; default: return "Milli"; } } public boolean isAutoScale() { return (_formatter == null); } @Override public String toString() { String res = null; if (_formatter == null) { res = "Auto-scale"; } else { res = _count + " " + getUnitLabel() + " " + _formatter; } return res; } } public static class OptimisedDateTickUnit extends DateTickUnit { /** * */ private static final long serialVersionUID = 1L; /** * static calendar instance, to reduce object allocation * */ private static Calendar _myCal = null; public OptimisedDateTickUnit(final DateTickUnitType unitType, final int multiple) { super(unitType, multiple); } public OptimisedDateTickUnit(final DateTickUnitType unitType, final int multiple, final DateFormat formatter) { super(unitType, multiple, formatter); } public OptimisedDateTickUnit(final DateTickUnitType unitType, final int multiple, final DateTickUnitType rollUnitType, final int rollMultiple, final DateFormat formatter) { super(unitType, multiple, rollUnitType, rollMultiple, formatter); } /** * Overrides parent implementation, in order that we can use static Calendar instance rather * than creating it lots of times. */ @Override @SuppressWarnings("deprecation") public Date addToDate(final Date base, final TimeZone zone) { // do we have a calenar already? if (_myCal == null) _myCal = Calendar.getInstance(zone); _myCal.setTime(base); _myCal.add(this.getUnitType().getCalendarField(), this.getCount()); return _myCal.getTime(); } } public static class RNFormatter extends SimpleDateFormat { /** * */ private static final long serialVersionUID = 1L; /** * Construct a SimpleDateFormat using the given pattern in the default locale. <b>Note:</b> Not * all locales support SimpleDateFormat; for full generality, use the factory methods in the * DateFormat class. */ public RNFormatter(final String pattern) { super(pattern); this.setTimeZone(TimeZone.getTimeZone("GMT")); } } /** * the string format used to denote a relative time description */ public static final String RELATIVE_DTG_FORMAT = "T+SSS"; // //////////////////////////////////////////////// // member methods // //////////////////////////////////////////////// /** * a list of strings representing the tick units */ private static String[] _theTags = null; /** * the actual tick units in use */ private static MWCDateTickUnitWrapper[] _theData = null; /** * Returns a collection of standard date tick units. This collection will be used by default, but * you are free to create your own collection if you want to (see the setStandardTickUnits(...) * method inherited from the ValueAxis class). * * @return a collection of standard date tick units. */ public static ArrayList<MWCDateTickUnitWrapper> createStandardDateTickUnitsAsArrayList() { final ArrayList<MWCDateTickUnitWrapper> units = new ArrayList<MWCDateTickUnitWrapper>(); units.add(MWCDateTickUnitWrapper.getAutoScale()); // ////////////////////////////////////////////////////// // milliseconds units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MILLISECOND, 500, "HH:mm:ss.SSS")); // seconds units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 1, "HH:mm:ss")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 5, "HH:mm:ss")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 10, "HH:mm:ss")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 30, "HH:mm:ss")); // minutes units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 1, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 2, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 5, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 10, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 15, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 20, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 30, "HH:mm")); // hours units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 1, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 2, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 4, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 6, "ddHHmm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 12, "ddHHmm")); // days units.add(new MWCDateTickUnitWrapper(DateTickUnitType.DAY, 1, "d-MMM")); // absolute seconds units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 1, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 5, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 10, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 30, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 60, RELATIVE_DTG_FORMAT)); return units; } public static TickUnits createStandardDateTickUnitsAsTickUnits() { final TickUnits units = new TickUnits(); // milliseconds units.add(new OptimisedDateTickUnit(DateTickUnitType.MILLISECOND, 500, new RNFormatter("HH:mm:ss.SSS"))); // seconds units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 1, new RNFormatter("HH:mm:ss"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 5, new RNFormatter("HH:mm:ss"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 10, new RNFormatter("HH:mm:ss"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 30, new RNFormatter("HH:mm:ss"))); // minutes units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 1, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 2, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 5, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 10, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 15, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 20, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 30, new RNFormatter("HH:mm"))); // hours units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 1, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 2, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 4, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 6, new RNFormatter("ddHHmm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 12, new RNFormatter("ddHHmm"))); // days units.add(new OptimisedDateTickUnit(DateTickUnitType.DAY, 1, new RNFormatter("d-MMM"))); return units; } protected synchronized void checkCreated() { // have they been created? if (_theData == null) { // create them final ArrayList<MWCDateTickUnitWrapper> theList = createStandardDateTickUnitsAsArrayList(); // _theDates = new TickUnits(); _theTags = new String[theList.size()]; _theData = new MWCDateTickUnitWrapper[theList.size()]; // work through the list for (int i = 0; i < theList.size(); i++) { final MWCDateTickUnitWrapper unit = theList.get(i); _theData[i] = unit; // and create the strings _theTags[i] = unit.toString(); } } } public MWCDateTickUnitWrapper getDateTickUnit() { final Integer index = (Integer) this.getValue(); final MWCDateTickUnitWrapper theUnit = _theData[index.intValue()]; return theUnit; } /** * retrieve the list of tags we display * * @return the list of options */ @Override public String[] getTags() { // check we're ready checkCreated(); return _theTags; } /** * return the currently selected string * * @return */ @Override public Object getValue() { // check we have the data checkCreated(); final Integer theIndex = (Integer) super.getValue(); return _theData[theIndex.intValue()]; } /** * select this vlaue * * @param p1 */ @Override public void setValue(final Object p1) { // check we have the data checkCreated(); if (p1 instanceof MWCDateTickUnitWrapper) { // pass through to match for (int i = 0; i < _theData.length; i++) { final MWCDateTickUnitWrapper unit = _theData[i]; if (unit.equals(p1)) { this.setValue(new Integer(i)); } } } else super.setValue(p1); } }
org.mwc.cmap.legacy/src/MWC/GUI/JFreeChart/DateAxisEditor.java
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package MWC.GUI.JFreeChart; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.DateTickUnitType; import org.jfree.chart.axis.TickUnits; import MWC.GUI.Properties.AbstractPropertyEditor; public class DateAxisEditor extends AbstractPropertyEditor { /***************************************************************************** * class to store components of tick unit in accessible form ****************************************************************************/ public static class MWCDateTickUnitWrapper { public static MWCDateTickUnitWrapper getAutoScale() { return new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 0, null); } // //////////////////////////////////////////////// // member variables // //////////////////////////////////////////////// /** * components of DateTickUnit */ protected DateTickUnitType _unit; protected int _count; protected String _formatter; public MWCDateTickUnitWrapper(final DateTickUnitType unit, final int count, final String formatter) { _unit = unit; _count = count; _formatter = formatter; } public DateTickUnit getUnit() { DateTickUnit res = null; if (_formatter != DateAxisEditor.RELATIVE_DTG_FORMAT) { final SimpleDateFormat sdf = new SimpleDateFormat(_formatter); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); res = new OptimisedDateTickUnit(_unit, _count, sdf); } else { final SimpleDateFormat sdf = new SimpleDateFormat(_formatter); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); res = new OptimisedDateTickUnit(_unit, _count, sdf) { /** * */ private static final long serialVersionUID = 1L; /** * Formats a date. * * @param date * the date. * @return the formatted date. */ @Override public String dateToString(final Date date) { String res1 = null; // how many secs? final long secs = date.getTime() / 1000; res1 = secs + "s"; return res1; } }; } return res; } private String getUnitLabel() { switch (_unit.getCalendarField()) { case (Calendar.YEAR): return "Year"; case (Calendar.MONTH): return "Month"; case (Calendar.DAY_OF_MONTH): return "Day"; case (Calendar.HOUR): case (Calendar.HOUR_OF_DAY): return "Hour"; case (Calendar.MINUTE): return "Min"; case (Calendar.SECOND): return "Sec"; default: return "Milli"; } } public boolean isAutoScale() { return (_formatter == null); } @Override public String toString() { String res = null; if (_formatter == null) { res = "Auto-scale"; } else { res = _count + " " + getUnitLabel() + " " + _formatter; } return res; } } // //////////////////////////////////////////////// // member variables // //////////////////////////////////////////////// public static class OptimisedDateTickUnit extends DateTickUnit { /** * */ private static final long serialVersionUID = 1L; /** * static calendar instance, to reduce object allocation * */ private static Calendar _myCal = null; public OptimisedDateTickUnit(final DateTickUnitType unitType, final int multiple) { super(unitType, multiple); } public OptimisedDateTickUnit(final DateTickUnitType unitType, final int multiple, final DateFormat formatter) { super(unitType, multiple, formatter); } public OptimisedDateTickUnit(final DateTickUnitType unitType, final int multiple, final DateTickUnitType rollUnitType, final int rollMultiple, final DateFormat formatter) { super(unitType, multiple, rollUnitType, rollMultiple, formatter); } /** * Overrides parent implementation, in order that we can use static Calendar instance rather * than creating it lots of times. */ @Override @SuppressWarnings("deprecation") public Date addToDate(final Date base, final TimeZone zone) { // do we have a calenar already? if (_myCal == null) _myCal = Calendar.getInstance(zone); _myCal.setTime(base); _myCal.add(this.getUnitType().getCalendarField(), this.getCount()); return _myCal.getTime(); } } public static class RNFormatter extends SimpleDateFormat { /** * */ private static final long serialVersionUID = 1L; /** * Construct a SimpleDateFormat using the given pattern in the default locale. <b>Note:</b> Not * all locales support SimpleDateFormat; for full generality, use the factory methods in the * DateFormat class. */ public RNFormatter(final String pattern) { super(pattern); this.setTimeZone(TimeZone.getTimeZone("GMT")); } } /** * the string format used to denote a relative time description */ public static final String RELATIVE_DTG_FORMAT = "T+SSS"; // //////////////////////////////////////////////// // member methods // //////////////////////////////////////////////// /** * a list of strings representing the tick units */ private static String[] _theTags = null; /** * the actual tick units in use */ private static MWCDateTickUnitWrapper[] _theData = null; /** * Returns a collection of standard date tick units. This collection will be used by default, but * you are free to create your own collection if you want to (see the setStandardTickUnits(...) * method inherited from the ValueAxis class). * * @return a collection of standard date tick units. */ public static ArrayList<MWCDateTickUnitWrapper> createStandardDateTickUnitsAsArrayList() { final ArrayList<MWCDateTickUnitWrapper> units = new ArrayList<MWCDateTickUnitWrapper>(); units.add(MWCDateTickUnitWrapper.getAutoScale()); // ////////////////////////////////////////////////////// // milliseconds units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MILLISECOND, 500, "HH:mm:ss.SSS")); // seconds units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 1, "HH:mm:ss")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 5, "HH:mm:ss")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 10, "HH:mm:ss")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 30, "HH:mm:ss")); // minutes units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 1, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 2, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 5, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 10, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 15, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 20, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 30, "HH:mm")); // hours units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 1, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 2, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 4, "HH:mm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 6, "ddHHmm")); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 12, "ddHHmm")); // days units.add(new MWCDateTickUnitWrapper(DateTickUnitType.DAY, 1, "d-MMM")); // absolute seconds units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 1, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 5, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 10, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 30, RELATIVE_DTG_FORMAT)); units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 60, RELATIVE_DTG_FORMAT)); return units; } public static TickUnits createStandardDateTickUnitsAsTickUnits() { final TickUnits units = new TickUnits(); // milliseconds units.add(new OptimisedDateTickUnit(DateTickUnitType.MILLISECOND, 500, new RNFormatter("HH:mm:ss.SSS"))); // seconds units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 1, new RNFormatter("HH:mm:ss"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 5, new RNFormatter("HH:mm:ss"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 10, new RNFormatter("HH:mm:ss"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 30, new RNFormatter("HH:mm:ss"))); // minutes units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 1, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 2, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 5, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 10, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 15, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 20, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 30, new RNFormatter("HH:mm"))); // hours units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 1, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 2, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 4, new RNFormatter("HH:mm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 6, new RNFormatter("ddHHmm"))); units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 12, new RNFormatter("ddHHmm"))); // days units.add(new OptimisedDateTickUnit(DateTickUnitType.DAY, 1, new RNFormatter("d-MMM"))); return units; } protected synchronized void checkCreated() { // have they been created? if (_theData == null) { // create them final ArrayList<MWCDateTickUnitWrapper> theList = createStandardDateTickUnitsAsArrayList(); // _theDates = new TickUnits(); _theTags = new String[theList.size()]; _theData = new MWCDateTickUnitWrapper[theList.size()]; // work through the list for (int i = 0; i < theList.size(); i++) { final MWCDateTickUnitWrapper unit = theList.get(i); _theData[i] = unit; // and create the strings _theTags[i] = unit.toString(); } } } public MWCDateTickUnitWrapper getDateTickUnit() { final Integer index = (Integer) this.getValue(); final MWCDateTickUnitWrapper theUnit = _theData[index.intValue()]; return theUnit; } /** * retrieve the list of tags we display * * @return the list of options */ @Override public String[] getTags() { // check we're ready checkCreated(); return _theTags; } /** * return the currently selected string * * @return */ @Override public Object getValue() { // check we have the data checkCreated(); final Integer theIndex = (Integer) super.getValue(); return _theData[theIndex.intValue()]; } /** * select this vlaue * * @param p1 */ @Override public void setValue(final Object p1) { // check we have the data checkCreated(); if (p1 instanceof MWCDateTickUnitWrapper) { // pass through to match for (int i = 0; i < _theData.length; i++) { final MWCDateTickUnitWrapper unit = _theData[i]; if (unit.equals(p1)) { this.setValue(new Integer(i)); } } } else super.setValue(p1); } }
Introduce new formatter, to handle showing DATE at 0000
org.mwc.cmap.legacy/src/MWC/GUI/JFreeChart/DateAxisEditor.java
Introduce new formatter, to handle showing DATE at 0000
<ide><path>rg.mwc.cmap.legacy/src/MWC/GUI/JFreeChart/DateAxisEditor.java <ide> package MWC.GUI.JFreeChart; <ide> <ide> import java.text.DateFormat; <add>import java.text.DecimalFormat; <add>import java.text.FieldPosition; <ide> import java.text.SimpleDateFormat; <ide> import java.util.ArrayList; <ide> import java.util.Calendar; <ide> <ide> public class DateAxisEditor extends AbstractPropertyEditor <ide> { <add> <add> public static class DatedRNFormatter extends SimpleDateFormat <add> { <add> /** <add> * <add> */ <add> private static final long serialVersionUID = 1L; <add> <add> /** <add> * pattern for the on-the-day values. Note: we currently ignore this, since we just prepend the <add> * date value as a 2-digit value <add> */ <add> @SuppressWarnings("unused") <add> private final String _datePattern; <add> <add> /** <add> * Construct a SimpleDateFormat using the given pattern in the default locale. <b>Note:</b> Not <add> * all locales support SimpleDateFormat; for full generality, use the factory methods in the <add> * DateFormat class. <add> */ <add> public DatedRNFormatter(final String pattern, final String datePattern) <add> { <add> super(pattern); <add> <add> _datePattern = datePattern; <add> <add> this.setTimeZone(TimeZone.getTimeZone("GMT")); <add> } <add> <add> @SuppressWarnings("deprecation") <add> @Override <add> public StringBuffer format(final Date arg0, final StringBuffer arg1, <add> final FieldPosition arg2) <add> { <add> StringBuffer timeBit = super.format(arg0, arg1, arg2); <add> <add> // see if we're on the exact day <add> if ((arg0.getHours() == 0) && (arg0.getMinutes() == 0) && (arg0 <add> .getSeconds() == 0)) <add> { <add> // ok, use the suffix <add> final DecimalFormat df = new DecimalFormat("00"); <add> final String prefix = df.format(arg0.getDate()); <add> final StringBuffer res = new StringBuffer(); <add> res.append(prefix); <add> res.append(timeBit); <add> timeBit = res; <add> } <add> <add> return timeBit; <add> } <add> <add> } <ide> <ide> /***************************************************************************** <ide> * class to store components of tick unit in accessible form <ide> } <ide> } <ide> <del> // //////////////////////////////////////////////// <del> // member variables <del> // //////////////////////////////////////////////// <del> <ide> public static class OptimisedDateTickUnit extends DateTickUnit <ide> { <ide> <ide> public RNFormatter(final String pattern) <ide> { <ide> super(pattern); <add> <ide> this.setTimeZone(TimeZone.getTimeZone("GMT")); <ide> } <ide> }
Java
mit
50d7de38390befef09ee7a9d02011314ed4bae3f
0
bladecoder/blade-ink
package com.bladecoder.ink.runtime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.Stack; import com.bladecoder.ink.runtime.CallStack.Element; /** * A Story is the core class that represents a complete Ink narrative, and * manages the evaluation and state of it. */ public class Story extends RTObject implements VariablesState.VariableChanged { /** * General purpose delegate definition for bound EXTERNAL function * definitions from ink. Note that this version isn't necessary if you have * a function with three arguments or less - see the overloads of * BindExternalFunction. */ public interface ExternalFunction { Object call(Object[] args) throws Exception; } // Version numbers are for engine itself and story file, rather // than the story state save format (which is um, currently nonexistant) // -- old engine, new format: always fail // -- new engine, old format: possibly cope, based on this number // When incrementing the version number above, the question you // should ask yourself is: // -- Will the engine be able to load an old story file from // before I made these changes to the engine? // If possible, you should support it, though it's not as // critical as loading old save games, since it's an // in-development problem only. /** * Delegate definition for variable observation - see ObserveVariable. */ public interface VariableObserver { void call(String variableName, Object newValue); } /** * The current version of the ink story file format. */ public static final int inkVersionCurrent = 17; /** * The minimum legacy version of ink that can be loaded by the current * version of the code. */ public static final int inkVersionMinimumCompatible = 16; private Container mainContentContainer; private ListDefinitionsOrigin listsDefinitions; /** * An ink file can provide a fallback functions for when when an EXTERNAL * has been left unbound by the client, and the fallback function will be * called instead. Useful when testing a story in playmode, when it's not * possible to write a client-side C# external function, but you don't want * it to fail to run. */ private boolean allowExternalFunctionFallbacks; private HashMap<String, ExternalFunction> externals; private boolean hasValidatedExternals; private StoryState state; private Container temporaryEvaluationContainer; private HashMap<String, List<VariableObserver>> variableObservers; private HashSet<Container> prevContainerSet; // Warning: When creating a Story using this constructor, you need to // call ResetState on it before use. Intended for compiler use only. // For normal use, use the constructor that takes a json string. Story(Container contentContainer, List<ListDefinition> lists) { mainContentContainer = contentContainer; if (lists != null) { listsDefinitions = new ListDefinitionsOrigin(lists); } externals = new HashMap<String, ExternalFunction>(); } Story(Container contentContainer) { this(contentContainer, null); } /** * Construct a Story Object using a JSON String compiled through inklecate. */ public Story(String jsonString) throws Exception { this((Container) null); HashMap<String, Object> rootObject = SimpleJson.textToHashMap(jsonString); Object versionObj = rootObject.get("inkVersion"); if (versionObj == null) throw new Exception("ink version number not found. Are you sure it's a valid .ink.json file?"); int formatFromFile = versionObj instanceof String ? Integer.parseInt((String) versionObj) : (int) versionObj; if (formatFromFile > inkVersionCurrent) { throw new Exception("Version of ink used to build story was newer than the current verison of the engine"); } else if (formatFromFile < inkVersionMinimumCompatible) { throw new Exception( "Version of ink used to build story is too old to be loaded by this version of the engine"); } else if (formatFromFile != inkVersionCurrent) { System.out.println( "WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising."); } Object rootToken = rootObject.get("root"); if (rootToken == null) throw new Exception("Root node for ink not found. Are you sure it's a valid .ink.json file?"); Object listDefsObj = rootObject.get("listDefs"); if (listDefsObj != null) { listsDefinitions = Json.jTokenToListDefinitions(listDefsObj); } mainContentContainer = Json.jTokenToRuntimeObject(rootToken) instanceof Container ? (Container) Json.jTokenToRuntimeObject(rootToken) : null; resetState(); } void addError(String message, boolean useEndLineNumber) throws Exception { DebugMetadata dm = currentDebugMetadata(); if (dm != null) { int lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber; message = String.format("RUNTIME ERROR: '%s' line %d: %s", dm.fileName, lineNum, message); } else if( state.getCurrentPath() != null ) { message = String.format ("RUNTIME ERROR: (%s): %s", state.getCurrentPath().toString(), message); } else { message = "RUNTIME ERROR: " + message; } state.addError(message); // In a broken state don't need to know about any other errors. state.forceEnd(); } void Assert(boolean condition, Object... formatParams) throws Exception { Assert(condition, null, formatParams); } void Assert(boolean condition, String message, Object... formatParams) throws Exception { if (condition == false) { if (message == null) { message = "Story assert"; } if (formatParams != null && formatParams.length > 0) { message = String.format(message, formatParams); } throw new Exception(message + " " + currentDebugMetadata()); } } /** * Most general form of function binding that returns an Object and takes an * array of Object parameters. The only way to bind a function with more * than 3 arguments. * * @param funcName * EXTERNAL ink function name to bind to. * @param func * The Java function to bind. */ public void bindExternalFunction(String funcName, ExternalFunction func) throws Exception { Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound."); externals.put(funcName, func); } @SuppressWarnings("unchecked") public <T> T tryCoerce(Object value, Class<T> type) throws Exception { if (value == null) return null; if (type.isAssignableFrom(value.getClass())) return (T) value; if (value instanceof Float && type == Integer.class) { Integer intVal = (int) Math.round((Float) value); return (T) intVal; } if (value instanceof Integer && type == Float.class) { Float floatVal = Float.valueOf((Integer) value); return (T) floatVal; } if (value instanceof Integer && type == Boolean.class) { int intVal = (Integer) value; return (T) (intVal == 0 ? new Boolean(false) : new Boolean(true)); } if (type == String.class) { return (T) value.toString(); } Assert(false, "Failed to cast " + value.getClass().getCanonicalName() + " to " + type.getCanonicalName()); return null; } /** * Get any global tags associated with the story. These are defined as hash * tags defined at the very top of the story. * * @throws Exception */ public List<String> getGlobalTags() throws Exception { return tagsAtStartOfFlowContainerWithPathString(""); } /** * Gets any tags associated with a particular knot or knot.stitch. These are * defined as hash tags defined at the very top of a knot or stitch. * * @param path * The path of the knot or stitch, in the form "knot" or * "knot.stitch". * @throws Exception */ public List<String> tagsForContentAtPath(String path) throws Exception { return tagsAtStartOfFlowContainerWithPathString(path); } List<String> tagsAtStartOfFlowContainerWithPathString(String pathString) throws Exception { Path path = new Path(pathString); // Expected to be global story, knot or stitch Container flowContainer = null; RTObject c = contentAtPath(path); if (c instanceof Container) flowContainer = (Container) c; while (true) { RTObject firstContent = flowContainer.getContent().get(0); if (firstContent instanceof Container) flowContainer = (Container) firstContent; else break; } // Any initial tag objects count as the "main tags" associated with that // story/knot/stitch List<String> tags = null; for (RTObject c2 : flowContainer.getContent()) { Tag tag = null; if (c2 instanceof Tag) tag = (Tag) c2; if (tag != null) { if (tags == null) tags = new ArrayList<String>(); tags.add(tag.getText()); } else break; } return tags; } /** * Useful when debugging a (very short) story, to visualise the state of the * story. Add this call as a watch and open the extended text. A left-arrow * mark will denote the current point of the story. It's only recommended * that this is used on very short debug stories, since it can end up * generate a large quantity of text otherwise. */ public String buildStringOfHierarchy() { StringBuilder sb = new StringBuilder(); mainContentContainer.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject()); return sb.toString(); } void callExternalFunction(String funcName, int numberOfArguments) throws Exception { Container fallbackFunctionContainer = null; ExternalFunction func = externals.get(funcName); // Try to use fallback function? if (func == null) { if (allowExternalFunctionFallbacks) { RTObject contentAtPath = contentAtPath(new Path(funcName)); fallbackFunctionContainer = contentAtPath instanceof Container ? (Container) contentAtPath : null; Assert(fallbackFunctionContainer != null, "Trying to call EXTERNAL function '" + funcName + "' which has not been bound, and fallback ink function could not be found."); // Divert direct into fallback function and we're done state.getCallStack().push(PushPopType.Function); state.setDivertedTargetObject(fallbackFunctionContainer); return; } else { Assert(false, "Trying to call EXTERNAL function '" + funcName + "' which has not been bound (and ink fallbacks disabled)."); } } // Pop arguments ArrayList<Object> arguments = new ArrayList<Object>(); for (int i = 0; i < numberOfArguments; ++i) { Value<?> poppedObj = (Value<?>) state.popEvaluationStack(); Object valueObj = poppedObj.getValueObject(); arguments.add(valueObj); } // Reverse arguments from the order they were popped, // so they're the right way round again. Collections.reverse(arguments); // Run the function! Object funcResult = func.call(arguments.toArray()); // Convert return value (if any) to the a type that the ink engine can // use RTObject returnObj = null; if (funcResult != null) { returnObj = AbstractValue.create(funcResult); Assert(returnObj != null, "Could not create ink value from returned Object of type " + funcResult.getClass().getCanonicalName()); } else { returnObj = new Void(); } state.pushEvaluationStack(returnObj); } /** * Check whether more content is available if you were to call Continue() - * i.e. are we mid story rather than at a choice point or at the end. * * @return true if it's possible to call Continue() */ public boolean canContinue() { return state.canContinue(); } /** * Chooses the Choice from the currentChoices list with the given index. * Internally, this sets the current content path to that pointed to by the * Choice, ready to continue story evaluation. */ public void chooseChoiceIndex(int choiceIdx) throws Exception { List<Choice> choices = getCurrentChoices(); Assert(choiceIdx >= 0 && choiceIdx < choices.size(), "choice out of range"); // Replace callstack with the one from the thread at the choosing point, // so that we can jump into the right place in the flow. // This is important in case the flow was forked by a new thread, which // can create multiple leading edges for the story, each of // which has its own context. Choice choiceToChoose = choices.get(choiceIdx); state.getCallStack().setCurrentThread(choiceToChoose.getThreadAtGeneration()); choosePath(choiceToChoose.getchoicePoint().getChoiceTarget().getPath()); } void choosePath(Path p) throws Exception { state.setChosenPath(p); // Take a note of newly visited containers for read counts etc visitChangedContainersDueToDivert(); } /** * Change the current position of the story to the given path. From here you * can call Continue() to evaluate the next line. The path String is a * dot-separated path as used ly by the engine. These examples should work: * * myKnot myKnot.myStitch * * Note however that this won't necessarily work: * * myKnot.myStitch.myLabelledChoice * * ...because of the way that content is nested within a weave structure. * * @param path * A dot-separted path string, as specified above. * @param arguments * Optional set of arguments to pass, if path is to a knot that * takes them. */ public void choosePathString(String path, Object[] arguments) throws Exception { state.passArgumentsToEvaluationStack(arguments); choosePath(new Path(path)); } public void choosePathString(String path) throws Exception { choosePathString(path, null); } RTObject contentAtPath(Path path) throws Exception { return mainContentContainer().contentAtPath(path); } /** * Continue the story for one line of content, if possible. If you're not * sure if there's more content available, for example if you want to check * whether you're at a choice point or at the end of the story, you should * call canContinue before calling this function. * * @return The line of text content. */ public String Continue() throws StoryException, Exception { // TODO: Should we leave this to the client, since it could be // slow to iterate through all the content an extra time? if (!hasValidatedExternals) validateExternalBindings(); return continueInternal(); } String continueInternal() throws StoryException, Exception { if (!canContinue()) { throw new StoryException("Can't continue - should check canContinue before calling Continue"); } state.resetOutput(); state.setDidSafeExit(false); state.getVariablesState().setbatchObservingVariableChanges(true); // _previousContainer = null; try { StoryState stateAtLastNewline = null; // The basic algorithm here is: // // do { Step() } while( canContinue && !outputStreamEndsInNewline ); // // But the complexity comes from: // - Stepping beyond the newline in case it'll be absorbed by glue // later // - Ensuring that non-text content beyond newlines are generated - // i.e. choices, // which are actually built out of text content. // So we have to take a snapshot of the state, continue // prospectively, // and rewind if necessary. // This code is slightly fragile :-/ // do { // Run main step function (walks through content) step(); // Run out of content and we have a default invisible choice // that we can follow? if (!canContinue()) { tryFollowDefaultInvisibleChoice(); } // Don't save/rewind during String evaluation, which is e.g. // used for choices if (!getState().inStringEvaluation()) { // We previously found a newline, but were we just double // checking that // it wouldn't immediately be removed by glue? if (stateAtLastNewline != null) { // Cover cases that non-text generated content was // evaluated last step String currText = getCurrentText(); int prevTextLength = stateAtLastNewline.getCurrentText().length(); // Take tags into account too, so that a tag following a // content line: // Content // # tag // ... doesn't cause the tag to be wrongly associated // with the content above. int prevTagCount = stateAtLastNewline.getCurrentTags().size(); // Output has been extended? if (!currText.equals(stateAtLastNewline.getCurrentText()) || prevTagCount != getCurrentTags().size()) { // Original newline still exists? if (currText.length() >= prevTextLength && currText.charAt(prevTextLength - 1) == '\n') { restoreStateSnapshot(stateAtLastNewline); break; } // Newline that previously existed is no longer // valid - e.g. // glue was encounted that caused it to be removed. else { stateAtLastNewline = null; } } } // Current content ends in a newline - approaching end of // our evaluation if (getState().outputStreamEndsInNewline()) { // If we can continue evaluation for a bit: // Create a snapshot in case we need to rewind. // We're going to continue stepping in case we see glue // or some // non-text content such as choices. if (canContinue()) { // Don't bother to record the state beyond the // current newline. // e.g.: // Hello world\n // record state at the end of here // ~ complexCalculation() // don't actually need this unless it generates text if (stateAtLastNewline == null) stateAtLastNewline = stateSnapshot(); } // Can't continue, so we're about to exit - make sure we // don't have an old state hanging around. else { stateAtLastNewline = null; } } } } while (canContinue()); // Need to rewind, due to evaluating further than we should? if (stateAtLastNewline != null) { restoreStateSnapshot(stateAtLastNewline); } // Finished a section of content / reached a choice point? if (!canContinue()) { if (getState().getCallStack().canPopThread()) { error("Thread available to pop, threads should always be flat by the end of evaluation?"); } if (getState().getGeneratedChoices().size() == 0 && !getState().isDidSafeExit() && temporaryEvaluationContainer == null) { if (getState().getCallStack().canPop(PushPopType.Tunnel)) { error("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"); } else if (getState().getCallStack().canPop(PushPopType.Function)) { error("unexpectedly reached end of content. Do you need a '~ return'?"); } else if (!getState().getCallStack().canPop()) { error("ran out of content. Do you need a '-> DONE' or '-> END'?"); } else { error("unexpectedly reached end of content for unknown reason. Please debug compiler!"); } } } } catch (StoryException e) { addError(e.getMessage(), e.useEndLineNumber); } finally { getState().setDidSafeExit(false); state.getVariablesState().setbatchObservingVariableChanges(false); } return getCurrentText(); } /** * Continue the story until the next choice point or until it runs out of * content. This is as opposed to the Continue() method which only evaluates * one line of output at a time. * * @return The resulting text evaluated by the ink engine, concatenated * together. */ public String continueMaximally() throws StoryException, Exception { StringBuilder sb = new StringBuilder(); while (canContinue()) { sb.append(Continue()); } return sb.toString(); } DebugMetadata currentDebugMetadata() { DebugMetadata dm; // Try to get from the current path first RTObject currentContent = state.getCurrentContentObject(); if (currentContent != null) { dm = currentContent.getDebugMetadata(); if (dm != null) { return dm; } } // Move up callstack if possible for (int i = state.getCallStack().getElements().size() - 1; i >= 0; --i) { RTObject currentObj = state.getCallStack().getElements().get(i).currentRTObject; if (currentObj != null && currentObj.getDebugMetadata() != null) { return currentObj.getDebugMetadata(); } } // Current/previous path may not be valid if we've just had an error, // or if we've simply run out of content. // As a last resort, try to grab something from the output stream for (int i = state.getOutputStream().size() - 1; i >= 0; --i) { RTObject outputObj = state.getOutputStream().get(i); dm = outputObj.getDebugMetadata(); if (dm != null) { return dm; } } return null; } int currentLineNumber() throws Exception { DebugMetadata dm = currentDebugMetadata(); if (dm != null) { return dm.startLineNumber; } return 0; } void error(String message) throws Exception { error(message, false); } // Throw an exception that gets caught and causes AddError to be called, // then exits the flow. void error(String message, boolean useEndLineNumber) throws Exception { StoryException e = new StoryException(message); e.useEndLineNumber = useEndLineNumber; throw e; } // Evaluate a "hot compiled" piece of ink content, as used by the REPL-like // CommandLinePlayer. RTObject evaluateExpression(Container exprContainer) throws StoryException, Exception { int startCallStackHeight = state.getCallStack().getElements().size(); state.getCallStack().push(PushPopType.Tunnel); temporaryEvaluationContainer = exprContainer; state.goToStart(); int evalStackHeight = state.getEvaluationStack().size(); Continue(); temporaryEvaluationContainer = null; // Should have fallen off the end of the Container, which should // have auto-popped, but just in case we didn't for some reason, // manually pop to restore the state (including currentPath). if (state.getCallStack().getElements().size() > startCallStackHeight) { state.getCallStack().pop(); } int endStackHeight = state.getEvaluationStack().size(); if (endStackHeight > evalStackHeight) { return state.popEvaluationStack(); } else { return null; } } /** * The list of Choice Objects available at the current point in the Story. * This list will be populated as the Story is stepped through with the * Continue() method. Once canContinue becomes false, this list will be * populated, and is usually (but not always) on the final Continue() step. */ public List<Choice> getCurrentChoices() { // Don't include invisible choices for external usage. List<Choice> choices = new ArrayList<Choice>(); for (Choice c : state.getCurrentChoices()) { if (!c.getchoicePoint().isInvisibleDefault()) { c.setIndex(choices.size()); choices.add(c); } } return choices; } /** * Gets a list of tags as defined with '#' in source that were seen during * the latest Continue() call. */ public List<String> getCurrentTags() { return state.getCurrentTags(); } /** * Any errors generated during evaluation of the Story. */ public List<String> getCurrentErrors() { return state.getCurrentErrors(); } /** * The latest line of text to be generated from a Continue() call. */ public String getCurrentText() { return state.getCurrentText(); } /** * The entire current state of the story including (but not limited to): * * * Global variables * Temporary variables * Read/visit and turn counts * * The callstack and evaluation stacks * The current threads * */ public StoryState getState() { return state; } /** * The VariablesState Object contains all the global variables in the story. * However, note that there's more to the state of a Story than just the * global variables. This is a convenience accessor to the full state * Object. */ public VariablesState getVariablesState() { return state.getVariablesState(); } public ListDefinitionsOrigin getListDefinitions() { return listsDefinitions; } /** * Whether the currentErrors list contains any errors. */ public boolean hasError() { return state.hasError(); } boolean incrementContentPointer() { boolean successfulIncrement = true; Element currEl = state.getCallStack().getCurrentElement(); currEl.currentContentIndex++; // Each time we step off the end, we fall out to the next container, all // the // while we're in indexed rather than named content while (currEl.currentContentIndex >= currEl.currentContainer.getContent().size()) { successfulIncrement = false; Container nextAncestor = currEl.currentContainer.getParent() instanceof Container ? (Container) currEl.currentContainer.getParent() : null; if (nextAncestor == null) { break; } int indexInAncestor = nextAncestor.getContent().indexOf(currEl.currentContainer); if (indexInAncestor == -1) { break; } currEl.currentContainer = nextAncestor; currEl.currentContentIndex = indexInAncestor + 1; successfulIncrement = true; } if (!successfulIncrement) currEl.currentContainer = null; return successfulIncrement; } void incrementVisitCountForContainer(Container container) { String containerPathStr = container.getPath().toString(); Integer count = state.getVisitCounts().get(containerPathStr); if (count == null) count = 0; count++; state.getVisitCounts().put(containerPathStr, count); } // Does the expression result represented by this Object evaluate to true? // e.g. is it a Number that's not equal to 1? boolean isTruthy(RTObject obj) throws Exception { boolean truthy = false; if (obj instanceof Value) { Value<?> val = (Value<?>) obj; if (val instanceof DivertTargetValue) { DivertTargetValue divTarget = (DivertTargetValue) val; error("Shouldn't use a divert target (to " + divTarget.getTargetPath() + ") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"); return false; } return val.isTruthy(); } return truthy; } /** * When the named global variable changes it's value, the observer will be * called to notify it of the change. Note that if the value changes * multiple times within the ink, the observer will only be called once, at * the end of the ink's evaluation. If, during the evaluation, it changes * and then changes back again to its original value, it will still be * called. Note that the observer will also be fired if the value of the * variable is changed externally to the ink, by directly setting a value in * story.variablesState. * * @param variableName * The name of the global variable to observe. * @param observer * A delegate function to call when the variable changes. */ public void observeVariable(String variableName, VariableObserver observer) { if (variableObservers == null) variableObservers = new HashMap<String, List<VariableObserver>>(); if (variableObservers.containsKey(variableName)) { variableObservers.get(variableName).add(observer); } else { List<VariableObserver> l = new ArrayList<VariableObserver>(); l.add(observer); variableObservers.put(variableName, l); } } /** * Convenience function to allow multiple variables to be observed with the * same observer delegate function. See the singular ObserveVariable for * details. The observer will get one call for every variable that has * changed. * * @param variableNames * The set of variables to observe. * @param observer * The delegate function to call when any of the named variables * change. */ public void observeVariables(List<String> variableNames, VariableObserver observer) { for (String varName : variableNames) { observeVariable(varName, observer); } } /** * Removes the variable observer, to stop getting variable change * notifications. If you pass a specific variable name, it will stop * observing that particular one. If you pass null (or leave it blank, since * it's optional), then the observer will be removed from all variables that * it's subscribed to. * * @param observer * The observer to stop observing. * @param specificVariableName * (Optional) Specific variable name to stop observing. */ public void removeVariableObserver(VariableObserver observer, String specificVariableName) { if (variableObservers == null) return; // Remove observer for this specific variable if (specificVariableName != null) { if (variableObservers.containsKey(specificVariableName)) { variableObservers.get(specificVariableName).remove(observer); } } else { // Remove observer for all variables for (List<VariableObserver> obs : variableObservers.values()) { obs.remove(observer); } } } public void removeVariableObserver(VariableObserver observer) { removeVariableObserver(observer, null); } @Override public void variableStateDidChangeEvent(String variableName, RTObject newValueObj) throws Exception { if (variableObservers == null) return; List<VariableObserver> observers = variableObservers.get(variableName); if (observers != null) { if (!(newValueObj instanceof Value)) { throw new Exception("Tried to get the value of a variable that isn't a standard type"); } Value<?> val = (Value<?>) newValueObj; for (VariableObserver o : observers) { o.call(variableName, val.getValueObject()); } } } Container mainContentContainer() { if (temporaryEvaluationContainer != null) { return temporaryEvaluationContainer; } else { return mainContentContainer; } } String BuildStringOfContainer(Container container) { StringBuilder sb = new StringBuilder(); container.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject()); return sb.toString(); } private void nextContent() throws Exception { // Setting previousContentObject is critical for // VisitChangedContainersDueToDivert state.setPreviousContentObject(state.getCurrentContentObject()); // Divert step? if (state.getDivertedTargetObject() != null) { state.setCurrentContentObject(state.getDivertedTargetObject()); state.setDivertedTargetObject(null); // Internally uses state.previousContentObject and // state.currentContentObject visitChangedContainersDueToDivert(); // Diverted location has valid content? if (state.getCurrentContentObject() != null) { return; } // Otherwise, if diverted location doesn't have valid content, // drop down and attempt to increment. // This can happen if the diverted path is intentionally jumping // to the end of a container - e.g. a Conditional that's re-joining } boolean successfulPointerIncrement = incrementContentPointer(); // Ran out of content? Try to auto-exit from a function, // or finish evaluating the content of a thread if (!successfulPointerIncrement) { boolean didPop = false; if (state.getCallStack().canPop(PushPopType.Function)) { // Pop from the call stack state.getCallStack().pop(PushPopType.Function); // This pop was due to dropping off the end of a function that // didn't return anything, // so in this case, we make sure that the evaluator has // something to chomp on if it needs it if (state.getInExpressionEvaluation()) { state.pushEvaluationStack(new Void()); } didPop = true; } else if (state.getCallStack().canPopThread()) { state.getCallStack().popThread(); didPop = true; } else { state.tryExitExternalFunctionEvaluation(); } // Step past the point where we last called out if (didPop && state.getCurrentContentObject() != null) { nextContent(); } } } // Note that this is O(n), since it re-evaluates the shuffle indices // from a consistent seed each time. // TODO: Is this the best algorithm it can be? int nextSequenceShuffleIndex() throws Exception { RTObject popEvaluationStack = state.popEvaluationStack(); IntValue numElementsIntVal = popEvaluationStack instanceof IntValue ? (IntValue) popEvaluationStack : null; if (numElementsIntVal == null) { error("expected number of elements in sequence for shuffle index"); return 0; } Container seqContainer = state.currentContainer(); int numElements = numElementsIntVal.value; IntValue seqCountVal = (IntValue) state.popEvaluationStack(); int seqCount = seqCountVal.value; int loopIndex = seqCount / numElements; int iterationIndex = seqCount % numElements; // Generate the same shuffle based on: // - The hash of this container, to make sure it's consistent // each time the runtime returns to the sequence // - How many times the runtime has looped around this full shuffle String seqPathStr = seqContainer.getPath().toString(); int sequenceHash = 0; for (char c : seqPathStr.toCharArray()) { sequenceHash += c; } int randomSeed = sequenceHash + loopIndex + state.getStorySeed(); Random random = new Random(randomSeed); ArrayList<Integer> unpickedIndices = new ArrayList<Integer>(); for (int i = 0; i < numElements; ++i) { unpickedIndices.add(i); } for (int i = 0; i <= iterationIndex; ++i) { int chosen = random.nextInt(Integer.MAX_VALUE) % unpickedIndices.size(); int chosenIndex = unpickedIndices.get(chosen); unpickedIndices.remove(chosen); if (i == iterationIndex) { return chosenIndex; } } throw new Exception("Should never reach here"); } /** * Checks whether contentObj is a control or flow Object rather than a piece * of content, and performs the required command if necessary. * * @return true if Object was logic or flow control, false if it's normal * content. * @param contentObj * Content Object. */ boolean performLogicAndFlowControl(RTObject contentObj) throws Exception { if (contentObj == null) { return false; } // Divert if (contentObj instanceof Divert) { Divert currentDivert = (Divert) contentObj; if (currentDivert.isConditional()) { RTObject conditionValue = state.popEvaluationStack(); // False conditional? Cancel divert if (!isTruthy(conditionValue)) return true; } if (currentDivert.hasVariableTarget()) { String varName = currentDivert.getVariableDivertName(); RTObject varContents = state.getVariablesState().getVariableWithName(varName); if (!(varContents instanceof DivertTargetValue)) { IntValue intContent = varContents instanceof IntValue ? (IntValue) varContents : null; String errorMessage = "Tried to divert to a target from a variable, but the variable (" + varName + ") didn't contain a divert target, it "; if (intContent != null && intContent.value == 0) { errorMessage += "was empty/null (the value 0)."; } else { errorMessage += "contained '" + varContents + "'."; } error(errorMessage); } DivertTargetValue target = (DivertTargetValue) varContents; state.setDivertedTargetObject(contentAtPath(target.getTargetPath())); } else if (currentDivert.isExternal()) { callExternalFunction(currentDivert.getTargetPathString(), currentDivert.getExternalArgs()); return true; } else { state.setDivertedTargetObject(currentDivert.getTargetContent()); } if (currentDivert.getPushesToStack()) { state.getCallStack().push(currentDivert.getStackPushType()); } if (state.getDivertedTargetObject() == null && !currentDivert.isExternal()) { // Human readable name available - runtime divert is part of a // hard-written divert that to missing content if (currentDivert != null && currentDivert.getDebugMetadata().sourceName != null) { error("Divert target doesn't exist: " + currentDivert.getDebugMetadata().sourceName); } else { error("Divert resolution failed: " + currentDivert); } } return true; } // Start/end an expression evaluation? Or print out the result? else if (contentObj instanceof ControlCommand) { ControlCommand evalCommand = (ControlCommand) contentObj; int choiceCount; switch (evalCommand.getCommandType()) { case EvalStart: Assert(state.getInExpressionEvaluation() == false, "Already in expression evaluation?"); state.setInExpressionEvaluation(true); break; case EvalEnd: Assert(state.getInExpressionEvaluation() == true, "Not in expression evaluation mode"); state.setInExpressionEvaluation(false); break; case EvalOutput: // If the expression turned out to be empty, there may not be // anything on the stack if (state.getEvaluationStack().size() > 0) { RTObject output = state.popEvaluationStack(); // Functions may evaluate to Void, in which case we skip // output if (!(output instanceof Void)) { // TODO: Should we really always blanket convert to // string? // It would be okay to have numbers in the output stream // the // only problem is when exporting text for viewing, it // skips over numbers etc. StringValue text = new StringValue(output.toString()); state.pushToOutputStream(text); } } break; case NoOp: break; case Duplicate: state.pushEvaluationStack(state.peekEvaluationStack()); break; case PopEvaluatedValue: state.popEvaluationStack(); break; case PopFunction: case PopTunnel: PushPopType popType = evalCommand.getCommandType() == ControlCommand.CommandType.PopFunction ? PushPopType.Function : PushPopType.Tunnel; // Tunnel onwards is allowed to specify an optional override // divert to go to immediately after returning: ->-> target DivertTargetValue overrideTunnelReturnTarget = null; if (popType == PushPopType.Tunnel) { RTObject popped = state.popEvaluationStack(); if (popped instanceof DivertTargetValue) { overrideTunnelReturnTarget = (DivertTargetValue) popped; } if (overrideTunnelReturnTarget == null) { Assert(popped instanceof Void, "Expected void if ->-> doesn't override target"); } } if (state.tryExitExternalFunctionEvaluation()) { break; } else if (state.getCallStack().getCurrentElement().type != popType || !state.getCallStack().canPop()) { HashMap<PushPopType, String> names = new HashMap<PushPopType, String>(); names.put(PushPopType.Function, "function return statement (~ return)"); names.put(PushPopType.Tunnel, "tunnel onwards statement (->->)"); String expected = names.get(state.getCallStack().getCurrentElement().type); if (!state.getCallStack().canPop()) { expected = "end of flow (-> END or choice)"; } String errorMsg = String.format("Found %s, when expected %s", names.get(popType), expected); error(errorMsg); } else { state.getCallStack().pop(); // Does tunnel onwards override by diverting to a new ->-> // target? if (overrideTunnelReturnTarget != null) state.setDivertedTargetObject(contentAtPath(overrideTunnelReturnTarget.getTargetPath())); } break; case BeginString: state.pushToOutputStream(evalCommand); Assert(state.getInExpressionEvaluation() == true, "Expected to be in an expression when evaluating a string"); state.setInExpressionEvaluation(false); break; case EndString: // Since we're iterating backward through the content, // build a stack so that when we build the string, // it's in the right order Stack<RTObject> contentStackForString = new Stack<RTObject>(); int outputCountConsumed = 0; for (int i = state.getOutputStream().size() - 1; i >= 0; --i) { RTObject obj = state.getOutputStream().get(i); outputCountConsumed++; ControlCommand command = obj instanceof ControlCommand ? (ControlCommand) obj : null; if (command != null && command.getCommandType() == ControlCommand.CommandType.BeginString) { break; } if (obj instanceof StringValue) contentStackForString.push(obj); } // Consume the content that was produced for this string state.getOutputStream() .subList(state.getOutputStream().size() - outputCountConsumed, state.getOutputStream().size()) .clear(); // Build String out of the content we collected StringBuilder sb = new StringBuilder(); while (contentStackForString.size() > 0) { RTObject c = contentStackForString.pop(); sb.append(c.toString()); } // Return to expression evaluation (from content mode) state.setInExpressionEvaluation(true); state.pushEvaluationStack(new StringValue(sb.toString())); break; case ChoiceCount: choiceCount = state.getGeneratedChoices().size(); state.pushEvaluationStack(new IntValue(choiceCount)); break; case TurnsSince: case ReadCount: RTObject target = state.popEvaluationStack(); if (!(target instanceof DivertTargetValue)) { String extraNote = ""; if (target instanceof IntValue) extraNote = ". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"; error("TURNS_SINCE expected a divert target (knot, stitch, label name), but saw " + target + extraNote); break; } DivertTargetValue divertTarget = target instanceof DivertTargetValue ? (DivertTargetValue) target : null; Container container = contentAtPath(divertTarget.getTargetPath()) instanceof Container ? (Container) contentAtPath(divertTarget.getTargetPath()) : null; int eitherCount; if (evalCommand.getCommandType() == ControlCommand.CommandType.TurnsSince) eitherCount = turnsSinceForContainer(container); else eitherCount = visitCountForContainer(container); state.pushEvaluationStack(new IntValue(eitherCount)); break; case Random: { IntValue maxInt = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) maxInt = (IntValue) o; IntValue minInt = null; o = state.popEvaluationStack(); if (o instanceof IntValue) minInt = (IntValue) o; if (minInt == null) error("Invalid value for minimum parameter of RANDOM(min, max)"); if (maxInt == null) error("Invalid value for maximum parameter of RANDOM(min, max)"); // +1 because it's inclusive of min and max, for e.g. // RANDOM(1,6) for a dice roll. int randomRange = maxInt.value - minInt.value + 1; if (randomRange <= 0) error("RANDOM was called with minimum as " + minInt.value + " and maximum as " + maxInt.value + ". The maximum must be larger"); int resultSeed = state.getStorySeed() + state.getPreviousRandom(); Random random = new Random(resultSeed); int nextRandom = random.nextInt(Integer.MAX_VALUE); int chosenValue = (nextRandom % randomRange) + minInt.value; state.pushEvaluationStack(new IntValue(chosenValue)); // Next random number (rather than keeping the Random object // around) state.setPreviousRandom(state.getPreviousRandom() + 1); break; } case SeedRandom: { IntValue seed = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) seed = (IntValue) o; if (seed == null) error("Invalid value passed to SEED_RANDOM"); // Story seed affects both RANDOM and shuffle behaviour state.setStorySeed(seed.value); state.setPreviousRandom(0); // SEED_RANDOM returns nothing. state.pushEvaluationStack(new Void()); break; } case VisitIndex: int count = visitCountForContainer(state.currentContainer()) - 1; // index // not // count state.pushEvaluationStack(new IntValue(count)); break; case SequenceShuffleIndex: int shuffleIndex = nextSequenceShuffleIndex(); state.pushEvaluationStack(new IntValue(shuffleIndex)); break; case StartThread: // Handled in main step function break; case Done: // We may exist in the context of the initial // act of creating the thread, or in the context of // evaluating the content. if (state.getCallStack().canPopThread()) { state.getCallStack().popThread(); } // In normal flow - allow safe exit without warning else { state.setDidSafeExit(true); // Stop flow in current thread state.setCurrentContentObject(null); } break; // Force flow to end completely case End: state.forceEnd(); break; case ListFromInt: { IntValue intVal = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) intVal = (IntValue) o; StringValue listNameVal = null; o = state.popEvaluationStack(); if (o instanceof StringValue) listNameVal = (StringValue) o; if(intVal == null) { throw new StoryException ("Passed non-integer when creating a list element from a numerical value."); } ListValue generatedListValue = null; ListDefinition foundListDef = listsDefinitions.getDefinition(listNameVal.value); if (foundListDef != null) { InkListItem foundItem; foundItem = foundListDef.getItemWithValue(intVal.value); if (foundItem != null) { generatedListValue = new ListValue(foundItem, intVal.value); } } else { throw new StoryException("Failed to find List called " + listNameVal.value); } if (generatedListValue == null) generatedListValue = new ListValue(); state.pushEvaluationStack(generatedListValue); break; } case ListRange: { RTObject max = state.popEvaluationStack(); RTObject min = state.popEvaluationStack(); RTObject targetRT = state.popEvaluationStack(); ListValue targetList = null; if (targetRT instanceof ListValue) targetList = (ListValue) targetRT; if (targetList == null || min == null || max == null) throw new StoryException("Expected List, minimum and maximum for LIST_RANGE"); int minVal = -1; if (min instanceof ListValue) { minVal = (int) ((ListValue) min).getValue().getMaxItem().getValue(); } else if (min instanceof IntValue) { minVal = (int) ((IntValue) min).getValue(); } int maxVal = -1; if (max instanceof ListValue) { maxVal = (int) ((ListValue) min).getValue().getMaxItem().getValue(); } else if (min instanceof IntValue) { maxVal = (int) ((IntValue) min).getValue(); } if (minVal == -1) throw new StoryException("Invalid min range bound passed to LIST_RANGE(): " + min); if (maxVal == -1) throw new StoryException("Invalid max range bound passed to LIST_RANGE(): " + max); // Extract the range of items from the origin set ListValue result = new ListValue(); List<ListDefinition> origins = targetList.value.origins; if (origins != null) { for (ListDefinition origin : origins) { ListValue rangeFromOrigin = origin.listRange(minVal, maxVal); for (Entry<InkListItem, Integer> kv : rangeFromOrigin.getValue().entrySet()) { result.value.put(kv.getKey(), kv.getValue()); } } } state.pushEvaluationStack(result); break; } default: error("unhandled ControlCommand: " + evalCommand); break; } return true; } // Variable assignment else if (contentObj instanceof VariableAssignment) { VariableAssignment varAss = (VariableAssignment) contentObj; RTObject assignedVal = state.popEvaluationStack(); // When in temporary evaluation, don't create new variables purely // within // the temporary context, but attempt to create them globally // var prioritiseHigherInCallStack = _temporaryEvaluationContainer // != null; state.getVariablesState().assign(varAss, assignedVal); return true; } // Variable reference else if (contentObj instanceof VariableReference) { VariableReference varRef = (VariableReference) contentObj; RTObject foundValue = null; // Explicit read count value if (varRef.getPathForCount() != null) { Container container = varRef.getContainerForCount(); int count = visitCountForContainer(container); foundValue = new IntValue(count); } // Normal variable reference else { foundValue = state.getVariablesState().getVariableWithName(varRef.getName()); if (foundValue == null) { error("Uninitialised variable: " + varRef.getName()); foundValue = new IntValue(0); } } state.pushEvaluationStack(foundValue); return true; } // Native function call else if (contentObj instanceof NativeFunctionCall) { NativeFunctionCall func = (NativeFunctionCall) contentObj; List<RTObject> funcParams = state.popEvaluationStack(func.getNumberOfParameters()); RTObject result = func.call(funcParams); state.pushEvaluationStack(result); return true; } // No control content, must be ordinary content return false; } Choice processChoice(ChoicePoint choicePoint) throws Exception { boolean showChoice = true; // Don't create choice if choice point doesn't pass conditional if (choicePoint.hasCondition()) { RTObject conditionValue = state.popEvaluationStack(); if (!isTruthy(conditionValue)) { showChoice = false; } } String startText = ""; String choiceOnlyText = ""; if (choicePoint.hasChoiceOnlyContent()) { StringValue choiceOnlyStrVal = (StringValue) state.popEvaluationStack(); choiceOnlyText = choiceOnlyStrVal.value; } if (choicePoint.hasStartContent()) { StringValue startStrVal = (StringValue) state.popEvaluationStack(); startText = startStrVal.value; } // Don't create choice if player has already read this content if (choicePoint.isOnceOnly()) { int visitCount = visitCountForContainer(choicePoint.getChoiceTarget()); if (visitCount > 0) { showChoice = false; } } Choice choice = new Choice(choicePoint); choice.setThreadAtGeneration(state.getCallStack().getcurrentThread().copy()); // We go through the full process of creating the choice above so // that we consume the content for it, since otherwise it'll // be shown on the output stream. if (!showChoice) { return null; } // Set final text for the choice choice.setText(startText + choiceOnlyText); return choice; } void recordTurnIndexVisitToContainer(Container container) { String containerPathStr = container.getPath().toString(); state.getTurnIndices().put(containerPathStr, state.getCurrentTurnIndex()); } /** * Unwinds the callstack. Useful to reset the Story's evaluation without * actually changing any meaningful state, for example if you want to exit a * section of story prematurely and tell it to go elsewhere with a call to * ChoosePathString(...). Doing so without calling ResetCallstack() could * cause unexpected issues if, for example, the Story was in a tunnel * already. */ public void resetCallstack() throws Exception { state.forceEnd(); } /** * Reset the runtime error list within the state. */ public void resetErrors() { state.resetErrors(); } void resetGlobals() throws Exception { if (mainContentContainer.getNamedContent().containsKey("global decl")) { Path originalPath = getState().getCurrentPath(); choosePathString("global decl"); // Continue, but without validating external bindings, // since we may be doing this reset at initialisation time. continueInternal(); getState().setCurrentPath(originalPath); } } /** * Reset the Story back to its initial state as it was when it was first * constructed. */ public void resetState() throws Exception { state = new StoryState(this); state.getVariablesState().setVariableChangedEvent(this); resetGlobals(); } void restoreStateSnapshot(StoryState state) { this.state = state; } StoryState stateSnapshot() throws Exception { return state.copy(); } void step() throws Exception { boolean shouldAddToStream = true; // Get current content RTObject currentContentObj = state.getCurrentContentObject(); if (currentContentObj == null) { return; } // Step directly to the first element of content in a container (if // necessary) Container currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null; while (currentContainer != null) { // Mark container as being entered visitContainer(currentContainer, true); // No content? the most we can do is step past it if (currentContainer.getContent().size() == 0) break; currentContentObj = currentContainer.getContent().get(0); state.getCallStack().getCurrentElement().currentContentIndex = 0; state.getCallStack().getCurrentElement().currentContainer = currentContainer; currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null; } currentContainer = state.getCallStack().getCurrentElement().currentContainer; // Is the current content Object: // - Normal content // - Or a logic/flow statement - if so, do it // Stop flow if we hit a stack pop when we're unable to pop (e.g. // return/done statement in knot // that was diverted to rather than called as a function) boolean isLogicOrFlowControl = performLogicAndFlowControl(currentContentObj); // Has flow been forced to end by flow control above? if (state.getCurrentContentObject() == null) { return; } if (isLogicOrFlowControl) { shouldAddToStream = false; } // Choice with condition? ChoicePoint choicePoint = currentContentObj instanceof ChoicePoint ? (ChoicePoint) currentContentObj : null; if (choicePoint != null) { Choice choice = processChoice(choicePoint); if (choice != null) { state.getGeneratedChoices().add(choice); } currentContentObj = null; shouldAddToStream = false; } // If the container has no content, then it will be // the "content" itself, but we skip over it. if (currentContentObj instanceof Container) { shouldAddToStream = false; } // Content to add to evaluation stack or the output stream if (shouldAddToStream) { // If we're pushing a variable pointer onto the evaluation stack, // ensure that it's specific // to our current (possibly temporary) context index. And make a // copy of the pointer // so that we're not editing the original runtime Object. VariablePointerValue varPointer = currentContentObj instanceof VariablePointerValue ? (VariablePointerValue) currentContentObj : null; if (varPointer != null && varPointer.getContextIndex() == -1) { // Create new Object so we're not overwriting the story's own // data int contextIdx = state.getCallStack().contextForVariableNamed(varPointer.getVariableName()); currentContentObj = new VariablePointerValue(varPointer.getVariableName(), contextIdx); } // Expression evaluation content if (state.getInExpressionEvaluation()) { state.pushEvaluationStack(currentContentObj); } // Output stream content (i.e. not expression evaluation) else { state.pushToOutputStream(currentContentObj); } } // Increment the content pointer, following diverts if necessary nextContent(); // Starting a thread should be done after the increment to the content // pointer, // so that when returning from the thread, it returns to the content // after this instruction. ControlCommand controlCmd = currentContentObj instanceof ControlCommand ? (ControlCommand) currentContentObj : null; if (controlCmd != null && controlCmd.getCommandType() == ControlCommand.CommandType.StartThread) { state.getCallStack().pushThread(); } } /** * The Story itself in JSON representation. */ public String toJsonString() throws Exception { List<?> rootContainerJsonList = (List<?>) Json.runtimeObjectToJToken(mainContentContainer); HashMap<String, Object> rootObject = new HashMap<String, Object>(); rootObject.put("inkVersion", inkVersionCurrent); rootObject.put("root", rootContainerJsonList); return SimpleJson.HashMapToText(rootObject); } boolean tryFollowDefaultInvisibleChoice() throws Exception { List<Choice> allChoices = state.getCurrentChoices(); // Is a default invisible choice the ONLY choice? // var invisibleChoices = allChoices.Where (c => // c.choicePoint.isInvisibleDefault).ToList(); ArrayList<Choice> invisibleChoices = new ArrayList<Choice>(); for (Choice c : allChoices) { if (c.getchoicePoint().isInvisibleDefault()) { invisibleChoices.add(c); } } if (invisibleChoices.size() == 0 || allChoices.size() > invisibleChoices.size()) return false; Choice choice = invisibleChoices.get(0); choosePath(choice.getchoicePoint().getChoiceTarget().getPath()); return true; } int turnsSinceForContainer(Container container) throws Exception { if (!container.getTurnIndexShouldBeCounted()) { error("TURNS_SINCE() for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown. The story may need to be compiled with countAllVisits flag (-c)."); } String containerPathStr = container.getPath().toString(); Integer index = state.getTurnIndices().get(containerPathStr); if (index != null) { return state.getCurrentTurnIndex() - index; } else { return -1; } } /** * Remove a binding for a named EXTERNAL ink function. */ public void unbindExternalFunction(String funcName) throws Exception { Assert(externals.containsKey(funcName), "Function '" + funcName + "' has not been bound."); externals.remove(funcName); } /** * Check that all EXTERNAL ink functions have a valid bound C# function. * Note that this is automatically called on the first call to Continue(). */ public void validateExternalBindings() throws Exception { HashSet<String> missingExternals = new HashSet<String>(); validateExternalBindings(mainContentContainer, missingExternals); hasValidatedExternals = true; // No problem! Validation complete if (missingExternals.size() == 0) { hasValidatedExternals = true; } else { // Error for all missing externals StringBuilder join = new StringBuilder(); boolean first = true; for (String item : missingExternals) { if (first) first = false; else join.append(", "); join.append(item); } String message = String.format("ERROR: Missing function binding for external%s: '%s' %s", missingExternals.size() > 1 ? "s" : "", join.toString(), allowExternalFunctionFallbacks ? ", and no fallback ink function found." : " (ink fallbacks disabled)"); error(message); } } void validateExternalBindings(Container c, HashSet<String> missingExternals) throws Exception { for (RTObject innerContent : c.getContent()) { Container container = innerContent instanceof Container ? (Container) innerContent : null; if (container == null || !container.hasValidName()) validateExternalBindings(innerContent, missingExternals); } for (INamedContent innerKeyValue : c.getNamedContent().values()) { validateExternalBindings(innerKeyValue instanceof RTObject ? (RTObject) innerKeyValue : (RTObject) null, missingExternals); } } void validateExternalBindings(RTObject o, HashSet<String> missingExternals) throws Exception { Container container = o instanceof Container ? (Container) o : null; if (container != null) { validateExternalBindings(container, missingExternals); return; } Divert divert = o instanceof Divert ? (Divert) o : null; if (divert != null && divert.isExternal()) { String name = divert.getTargetPathString(); if (!externals.containsKey(name)) { if (allowExternalFunctionFallbacks) { boolean fallbackFound = mainContentContainer.getNamedContent().containsKey(name); if (!fallbackFound) { missingExternals.add(name); } } else { missingExternals.add(name); } } } } void visitChangedContainersDueToDivert() { RTObject previousContentObject = state.getPreviousContentObject(); RTObject newContentObject = state.getCurrentContentObject(); if (newContentObject == null) return; // First, find the previously open set of containers if (prevContainerSet == null) prevContainerSet = new HashSet<Container>(); prevContainerSet.clear(); if (previousContentObject != null) { Container prevAncestor = null; if (previousContentObject instanceof Container) { prevAncestor = (Container) previousContentObject; } else if (previousContentObject.getParent() instanceof Container) { prevAncestor = (Container) previousContentObject.getParent(); } while (prevAncestor != null) { prevContainerSet.add(prevAncestor); prevAncestor = prevAncestor.getParent() instanceof Container ? (Container) prevAncestor.getParent() : null; } } // If the new Object is a container itself, it will be visited // automatically at the next actual // content step. However, we need to walk up the new ancestry to see if // there are more new containers RTObject currentChildOfContainer = newContentObject; Container currentContainerAncestor = currentChildOfContainer.getParent() instanceof Container ? (Container) currentChildOfContainer.getParent() : null; while (currentContainerAncestor != null && !prevContainerSet.contains(currentContainerAncestor)) { // Check whether this ancestor container is being entered at the // start, // by checking whether the child Object is the first. boolean enteringAtStart = currentContainerAncestor.getContent().size() > 0 && currentChildOfContainer == currentContainerAncestor.getContent().get(0); // Mark a visit to this container visitContainer(currentContainerAncestor, enteringAtStart); currentChildOfContainer = currentContainerAncestor; currentContainerAncestor = currentContainerAncestor.getParent() instanceof Container ? (Container) currentContainerAncestor.getParent() : null; } } // Mark a container as having been visited void visitContainer(Container container, boolean atStart) { if (!container.getCountingAtStartOnly() || atStart) { if (container.getVisitsShouldBeCounted()) incrementVisitCountForContainer(container); if (container.getTurnIndexShouldBeCounted()) recordTurnIndexVisitToContainer(container); } } int visitCountForContainer(Container container) throws Exception { if (!container.getVisitsShouldBeCounted()) { error("Read count for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown. The story may need to be compiled with countAllVisits flag (-c)."); return 0; } String containerPathStr = container.getPath().toString(); Integer count = state.getVisitCounts().get(containerPathStr); return count == null ? 0 : count; } public boolean allowExternalFunctionFallbacks() { return allowExternalFunctionFallbacks; } public void setAllowExternalFunctionFallbacks(boolean allowExternalFunctionFallbacks) { this.allowExternalFunctionFallbacks = allowExternalFunctionFallbacks; } /** * Evaluates a function defined in ink. * * @param functionName * The name of the function as declared in ink. * @param arguments * The arguments that the ink function takes, if any. Note that * we don't (can't) do any validation on the number of arguments * right now, so make sure you get it right! * @return The return value as returned from the ink function with `~ return * myValue`, or null if nothing is returned. * @throws Exception */ public Object evaluateFunction(String functionName, Object[] arguments) throws Exception { return evaluateFunction(functionName, null, arguments); } public Object evaluateFunction(String functionName) throws Exception { return evaluateFunction(functionName, null, null); } /** * Checks if a function exists. * * @return True if the function exists, else false. * @param functionName * The name of the function as declared in ink. */ public boolean hasFunction(String functionName) { try { return contentAtPath(new Path(functionName)) instanceof Container; } catch (Exception e) { return false; } } /** * Evaluates a function defined in ink, and gathers the possibly multi-line * text as generated by the function. * * @param arguments * The arguments that the ink function takes, if any. Note that * we don't (can't) do any validation on the number of arguments * right now, so make sure you get it right! * @param functionName * The name of the function as declared in ink. * @param textOutput * This text output is any text written as normal content within * the function, as opposed to the return value, as returned with * `~ return`. * @return The return value as returned from the ink function with `~ return * myValue`, or null if nothing is returned. * @throws Exception */ public Object evaluateFunction(String functionName, StringBuffer textOutput, Object[] arguments) throws Exception { // Get the content that we need to run Container funcContainer = null; if (functionName == null) { throw new Exception("Function is null"); } else if (functionName.trim().isEmpty()) { throw new Exception("Function is empty or white space."); } try { RTObject contentAtPath = contentAtPath(new Path(functionName)); if (contentAtPath instanceof Container) funcContainer = (Container) contentAtPath; } catch (StoryException e) { if (e.getMessage().contains("not found")) throw new Exception("Function doesn't exist: '" + functionName + "'"); else throw e; } // State will temporarily replace the callstack in order to evaluate state.startExternalFunctionEvaluation(funcContainer, arguments); // Evaluate the function, and collect the string output while (canContinue()) { String text = Continue(); if (textOutput != null) textOutput.append(text); } // Finish evaluation, and see whether anything was produced Object result = state.completeExternalFunctionEvaluation(); return result; } }
src/main/java/com/bladecoder/ink/runtime/Story.java
package com.bladecoder.ink.runtime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.Stack; import com.bladecoder.ink.runtime.CallStack.Element; /** * A Story is the core class that represents a complete Ink narrative, and * manages the evaluation and state of it. */ public class Story extends RTObject implements VariablesState.VariableChanged { /** * General purpose delegate definition for bound EXTERNAL function * definitions from ink. Note that this version isn't necessary if you have * a function with three arguments or less - see the overloads of * BindExternalFunction. */ public interface ExternalFunction { Object call(Object[] args) throws Exception; } // Version numbers are for engine itself and story file, rather // than the story state save format (which is um, currently nonexistant) // -- old engine, new format: always fail // -- new engine, old format: possibly cope, based on this number // When incrementing the version number above, the question you // should ask yourself is: // -- Will the engine be able to load an old story file from // before I made these changes to the engine? // If possible, you should support it, though it's not as // critical as loading old save games, since it's an // in-development problem only. /** * Delegate definition for variable observation - see ObserveVariable. */ public interface VariableObserver { void call(String variableName, Object newValue); } /** * The current version of the ink story file format. */ public static final int inkVersionCurrent = 17; /** * The minimum legacy version of ink that can be loaded by the current * version of the code. */ public static final int inkVersionMinimumCompatible = 16; private Container mainContentContainer; private ListDefinitionsOrigin listsDefinitions; /** * An ink file can provide a fallback functions for when when an EXTERNAL * has been left unbound by the client, and the fallback function will be * called instead. Useful when testing a story in playmode, when it's not * possible to write a client-side C# external function, but you don't want * it to fail to run. */ private boolean allowExternalFunctionFallbacks; private HashMap<String, ExternalFunction> externals; private boolean hasValidatedExternals; private StoryState state; private Container temporaryEvaluationContainer; private HashMap<String, List<VariableObserver>> variableObservers; private HashSet<Container> prevContainerSet; // Warning: When creating a Story using this constructor, you need to // call ResetState on it before use. Intended for compiler use only. // For normal use, use the constructor that takes a json string. Story(Container contentContainer, List<ListDefinition> lists) { mainContentContainer = contentContainer; if (lists != null) { listsDefinitions = new ListDefinitionsOrigin(lists); } externals = new HashMap<String, ExternalFunction>(); } Story(Container contentContainer) { this(contentContainer, null); } /** * Construct a Story Object using a JSON String compiled through inklecate. */ public Story(String jsonString) throws Exception { this((Container) null); HashMap<String, Object> rootObject = SimpleJson.textToHashMap(jsonString); Object versionObj = rootObject.get("inkVersion"); if (versionObj == null) throw new Exception("ink version number not found. Are you sure it's a valid .ink.json file?"); int formatFromFile = versionObj instanceof String ? Integer.parseInt((String) versionObj) : (int) versionObj; if (formatFromFile > inkVersionCurrent) { throw new Exception("Version of ink used to build story was newer than the current verison of the engine"); } else if (formatFromFile < inkVersionMinimumCompatible) { throw new Exception( "Version of ink used to build story is too old to be loaded by this version of the engine"); } else if (formatFromFile != inkVersionCurrent) { System.out.println( "WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising."); } Object rootToken = rootObject.get("root"); if (rootToken == null) throw new Exception("Root node for ink not found. Are you sure it's a valid .ink.json file?"); Object listDefsObj = rootObject.get("listDefs"); if (listDefsObj != null) { listsDefinitions = Json.jTokenToListDefinitions(listDefsObj); } mainContentContainer = Json.jTokenToRuntimeObject(rootToken) instanceof Container ? (Container) Json.jTokenToRuntimeObject(rootToken) : null; resetState(); } void addError(String message, boolean useEndLineNumber) throws Exception { DebugMetadata dm = currentDebugMetadata(); if (dm != null) { int lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber; message = String.format("RUNTIME ERROR: '%s' line %d: %s", dm.fileName, lineNum, message); } else { message = "RUNTIME ERROR: " + message; } state.addError(message); // In a broken state don't need to know about any other errors. state.forceEnd(); } void Assert(boolean condition, Object... formatParams) throws Exception { Assert(condition, null, formatParams); } void Assert(boolean condition, String message, Object... formatParams) throws Exception { if (condition == false) { if (message == null) { message = "Story assert"; } if (formatParams != null && formatParams.length > 0) { message = String.format(message, formatParams); } throw new Exception(message + " " + currentDebugMetadata()); } } /** * Most general form of function binding that returns an Object and takes an * array of Object parameters. The only way to bind a function with more * than 3 arguments. * * @param funcName * EXTERNAL ink function name to bind to. * @param func * The Java function to bind. */ public void bindExternalFunction(String funcName, ExternalFunction func) throws Exception { Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound."); externals.put(funcName, func); } @SuppressWarnings("unchecked") public <T> T tryCoerce(Object value, Class<T> type) throws Exception { if (value == null) return null; if (type.isAssignableFrom(value.getClass())) return (T) value; if (value instanceof Float && type == Integer.class) { Integer intVal = (int) Math.round((Float) value); return (T) intVal; } if (value instanceof Integer && type == Float.class) { Float floatVal = Float.valueOf((Integer) value); return (T) floatVal; } if (value instanceof Integer && type == Boolean.class) { int intVal = (Integer) value; return (T) (intVal == 0 ? new Boolean(false) : new Boolean(true)); } if (type == String.class) { return (T) value.toString(); } Assert(false, "Failed to cast " + value.getClass().getCanonicalName() + " to " + type.getCanonicalName()); return null; } /** * Get any global tags associated with the story. These are defined as hash * tags defined at the very top of the story. * * @throws Exception */ public List<String> getGlobalTags() throws Exception { return tagsAtStartOfFlowContainerWithPathString(""); } /** * Gets any tags associated with a particular knot or knot.stitch. These are * defined as hash tags defined at the very top of a knot or stitch. * * @param path * The path of the knot or stitch, in the form "knot" or * "knot.stitch". * @throws Exception */ public List<String> tagsForContentAtPath(String path) throws Exception { return tagsAtStartOfFlowContainerWithPathString(path); } List<String> tagsAtStartOfFlowContainerWithPathString(String pathString) throws Exception { Path path = new Path(pathString); // Expected to be global story, knot or stitch Container flowContainer = null; RTObject c = contentAtPath(path); if (c instanceof Container) flowContainer = (Container) c; while (true) { RTObject firstContent = flowContainer.getContent().get(0); if (firstContent instanceof Container) flowContainer = (Container) firstContent; else break; } // Any initial tag objects count as the "main tags" associated with that // story/knot/stitch List<String> tags = null; for (RTObject c2 : flowContainer.getContent()) { Tag tag = null; if (c2 instanceof Tag) tag = (Tag) c2; if (tag != null) { if (tags == null) tags = new ArrayList<String>(); tags.add(tag.getText()); } else break; } return tags; } /** * Useful when debugging a (very short) story, to visualise the state of the * story. Add this call as a watch and open the extended text. A left-arrow * mark will denote the current point of the story. It's only recommended * that this is used on very short debug stories, since it can end up * generate a large quantity of text otherwise. */ public String buildStringOfHierarchy() { StringBuilder sb = new StringBuilder(); mainContentContainer.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject()); return sb.toString(); } void callExternalFunction(String funcName, int numberOfArguments) throws Exception { Container fallbackFunctionContainer = null; ExternalFunction func = externals.get(funcName); // Try to use fallback function? if (func == null) { if (allowExternalFunctionFallbacks) { RTObject contentAtPath = contentAtPath(new Path(funcName)); fallbackFunctionContainer = contentAtPath instanceof Container ? (Container) contentAtPath : null; Assert(fallbackFunctionContainer != null, "Trying to call EXTERNAL function '" + funcName + "' which has not been bound, and fallback ink function could not be found."); // Divert direct into fallback function and we're done state.getCallStack().push(PushPopType.Function); state.setDivertedTargetObject(fallbackFunctionContainer); return; } else { Assert(false, "Trying to call EXTERNAL function '" + funcName + "' which has not been bound (and ink fallbacks disabled)."); } } // Pop arguments ArrayList<Object> arguments = new ArrayList<Object>(); for (int i = 0; i < numberOfArguments; ++i) { Value<?> poppedObj = (Value<?>) state.popEvaluationStack(); Object valueObj = poppedObj.getValueObject(); arguments.add(valueObj); } // Reverse arguments from the order they were popped, // so they're the right way round again. Collections.reverse(arguments); // Run the function! Object funcResult = func.call(arguments.toArray()); // Convert return value (if any) to the a type that the ink engine can // use RTObject returnObj = null; if (funcResult != null) { returnObj = AbstractValue.create(funcResult); Assert(returnObj != null, "Could not create ink value from returned Object of type " + funcResult.getClass().getCanonicalName()); } else { returnObj = new Void(); } state.pushEvaluationStack(returnObj); } /** * Check whether more content is available if you were to call Continue() - * i.e. are we mid story rather than at a choice point or at the end. * * @return true if it's possible to call Continue() */ public boolean canContinue() { return state.canContinue(); } /** * Chooses the Choice from the currentChoices list with the given index. * Internally, this sets the current content path to that pointed to by the * Choice, ready to continue story evaluation. */ public void chooseChoiceIndex(int choiceIdx) throws Exception { List<Choice> choices = getCurrentChoices(); Assert(choiceIdx >= 0 && choiceIdx < choices.size(), "choice out of range"); // Replace callstack with the one from the thread at the choosing point, // so that we can jump into the right place in the flow. // This is important in case the flow was forked by a new thread, which // can create multiple leading edges for the story, each of // which has its own context. Choice choiceToChoose = choices.get(choiceIdx); state.getCallStack().setCurrentThread(choiceToChoose.getThreadAtGeneration()); choosePath(choiceToChoose.getchoicePoint().getChoiceTarget().getPath()); } void choosePath(Path p) throws Exception { state.setChosenPath(p); // Take a note of newly visited containers for read counts etc visitChangedContainersDueToDivert(); } /** * Change the current position of the story to the given path. From here you * can call Continue() to evaluate the next line. The path String is a * dot-separated path as used ly by the engine. These examples should work: * * myKnot myKnot.myStitch * * Note however that this won't necessarily work: * * myKnot.myStitch.myLabelledChoice * * ...because of the way that content is nested within a weave structure. * * @param path * A dot-separted path string, as specified above. * @param arguments * Optional set of arguments to pass, if path is to a knot that * takes them. */ public void choosePathString(String path, Object[] arguments) throws Exception { state.passArgumentsToEvaluationStack(arguments); choosePath(new Path(path)); } public void choosePathString(String path) throws Exception { choosePathString(path, null); } RTObject contentAtPath(Path path) throws Exception { return mainContentContainer().contentAtPath(path); } /** * Continue the story for one line of content, if possible. If you're not * sure if there's more content available, for example if you want to check * whether you're at a choice point or at the end of the story, you should * call canContinue before calling this function. * * @return The line of text content. */ public String Continue() throws StoryException, Exception { // TODO: Should we leave this to the client, since it could be // slow to iterate through all the content an extra time? if (!hasValidatedExternals) validateExternalBindings(); return continueInternal(); } String continueInternal() throws StoryException, Exception { if (!canContinue()) { throw new StoryException("Can't continue - should check canContinue before calling Continue"); } state.resetOutput(); state.setDidSafeExit(false); state.getVariablesState().setbatchObservingVariableChanges(true); // _previousContainer = null; try { StoryState stateAtLastNewline = null; // The basic algorithm here is: // // do { Step() } while( canContinue && !outputStreamEndsInNewline ); // // But the complexity comes from: // - Stepping beyond the newline in case it'll be absorbed by glue // later // - Ensuring that non-text content beyond newlines are generated - // i.e. choices, // which are actually built out of text content. // So we have to take a snapshot of the state, continue // prospectively, // and rewind if necessary. // This code is slightly fragile :-/ // do { // Run main step function (walks through content) step(); // Run out of content and we have a default invisible choice // that we can follow? if (!canContinue()) { tryFollowDefaultInvisibleChoice(); } // Don't save/rewind during String evaluation, which is e.g. // used for choices if (!getState().inStringEvaluation()) { // We previously found a newline, but were we just double // checking that // it wouldn't immediately be removed by glue? if (stateAtLastNewline != null) { // Cover cases that non-text generated content was // evaluated last step String currText = getCurrentText(); int prevTextLength = stateAtLastNewline.getCurrentText().length(); // Take tags into account too, so that a tag following a // content line: // Content // # tag // ... doesn't cause the tag to be wrongly associated // with the content above. int prevTagCount = stateAtLastNewline.getCurrentTags().size(); // Output has been extended? if (!currText.equals(stateAtLastNewline.getCurrentText()) || prevTagCount != getCurrentTags().size()) { // Original newline still exists? if (currText.length() >= prevTextLength && currText.charAt(prevTextLength - 1) == '\n') { restoreStateSnapshot(stateAtLastNewline); break; } // Newline that previously existed is no longer // valid - e.g. // glue was encounted that caused it to be removed. else { stateAtLastNewline = null; } } } // Current content ends in a newline - approaching end of // our evaluation if (getState().outputStreamEndsInNewline()) { // If we can continue evaluation for a bit: // Create a snapshot in case we need to rewind. // We're going to continue stepping in case we see glue // or some // non-text content such as choices. if (canContinue()) { // Don't bother to record the state beyond the // current newline. // e.g.: // Hello world\n // record state at the end of here // ~ complexCalculation() // don't actually need this unless it generates text if (stateAtLastNewline == null) stateAtLastNewline = stateSnapshot(); } // Can't continue, so we're about to exit - make sure we // don't have an old state hanging around. else { stateAtLastNewline = null; } } } } while (canContinue()); // Need to rewind, due to evaluating further than we should? if (stateAtLastNewline != null) { restoreStateSnapshot(stateAtLastNewline); } // Finished a section of content / reached a choice point? if (!canContinue()) { if (getState().getCallStack().canPopThread()) { error("Thread available to pop, threads should always be flat by the end of evaluation?"); } if (getState().getGeneratedChoices().size() == 0 && !getState().isDidSafeExit() && temporaryEvaluationContainer == null) { if (getState().getCallStack().canPop(PushPopType.Tunnel)) { error("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"); } else if (getState().getCallStack().canPop(PushPopType.Function)) { error("unexpectedly reached end of content. Do you need a '~ return'?"); } else if (!getState().getCallStack().canPop()) { error("ran out of content. Do you need a '-> DONE' or '-> END'?"); } else { error("unexpectedly reached end of content for unknown reason. Please debug compiler!"); } } } } catch (StoryException e) { addError(e.getMessage(), e.useEndLineNumber); } finally { getState().setDidSafeExit(false); state.getVariablesState().setbatchObservingVariableChanges(false); } return getCurrentText(); } /** * Continue the story until the next choice point or until it runs out of * content. This is as opposed to the Continue() method which only evaluates * one line of output at a time. * * @return The resulting text evaluated by the ink engine, concatenated * together. */ public String continueMaximally() throws StoryException, Exception { StringBuilder sb = new StringBuilder(); while (canContinue()) { sb.append(Continue()); } return sb.toString(); } DebugMetadata currentDebugMetadata() { DebugMetadata dm; // Try to get from the current path first RTObject currentContent = state.getCurrentContentObject(); if (currentContent != null) { dm = currentContent.getDebugMetadata(); if (dm != null) { return dm; } } // Move up callstack if possible for (int i = state.getCallStack().getElements().size() - 1; i >= 0; --i) { RTObject currentObj = state.getCallStack().getElements().get(i).currentRTObject; if (currentObj != null && currentObj.getDebugMetadata() != null) { return currentObj.getDebugMetadata(); } } // Current/previous path may not be valid if we've just had an error, // or if we've simply run out of content. // As a last resort, try to grab something from the output stream for (int i = state.getOutputStream().size() - 1; i >= 0; --i) { RTObject outputObj = state.getOutputStream().get(i); dm = outputObj.getDebugMetadata(); if (dm != null) { return dm; } } return null; } int currentLineNumber() throws Exception { DebugMetadata dm = currentDebugMetadata(); if (dm != null) { return dm.startLineNumber; } return 0; } void error(String message) throws Exception { error(message, false); } // Throw an exception that gets caught and causes AddError to be called, // then exits the flow. void error(String message, boolean useEndLineNumber) throws Exception { StoryException e = new StoryException(message); e.useEndLineNumber = useEndLineNumber; throw e; } // Evaluate a "hot compiled" piece of ink content, as used by the REPL-like // CommandLinePlayer. RTObject evaluateExpression(Container exprContainer) throws StoryException, Exception { int startCallStackHeight = state.getCallStack().getElements().size(); state.getCallStack().push(PushPopType.Tunnel); temporaryEvaluationContainer = exprContainer; state.goToStart(); int evalStackHeight = state.getEvaluationStack().size(); Continue(); temporaryEvaluationContainer = null; // Should have fallen off the end of the Container, which should // have auto-popped, but just in case we didn't for some reason, // manually pop to restore the state (including currentPath). if (state.getCallStack().getElements().size() > startCallStackHeight) { state.getCallStack().pop(); } int endStackHeight = state.getEvaluationStack().size(); if (endStackHeight > evalStackHeight) { return state.popEvaluationStack(); } else { return null; } } /** * The list of Choice Objects available at the current point in the Story. * This list will be populated as the Story is stepped through with the * Continue() method. Once canContinue becomes false, this list will be * populated, and is usually (but not always) on the final Continue() step. */ public List<Choice> getCurrentChoices() { // Don't include invisible choices for external usage. List<Choice> choices = new ArrayList<Choice>(); for (Choice c : state.getCurrentChoices()) { if (!c.getchoicePoint().isInvisibleDefault()) { c.setIndex(choices.size()); choices.add(c); } } return choices; } /** * Gets a list of tags as defined with '#' in source that were seen during * the latest Continue() call. */ public List<String> getCurrentTags() { return state.getCurrentTags(); } /** * Any errors generated during evaluation of the Story. */ public List<String> getCurrentErrors() { return state.getCurrentErrors(); } /** * The latest line of text to be generated from a Continue() call. */ public String getCurrentText() { return state.getCurrentText(); } /** * The entire current state of the story including (but not limited to): * * * Global variables * Temporary variables * Read/visit and turn counts * * The callstack and evaluation stacks * The current threads * */ public StoryState getState() { return state; } /** * The VariablesState Object contains all the global variables in the story. * However, note that there's more to the state of a Story than just the * global variables. This is a convenience accessor to the full state * Object. */ public VariablesState getVariablesState() { return state.getVariablesState(); } public ListDefinitionsOrigin getListDefinitions() { return listsDefinitions; } /** * Whether the currentErrors list contains any errors. */ public boolean hasError() { return state.hasError(); } boolean incrementContentPointer() { boolean successfulIncrement = true; Element currEl = state.getCallStack().getCurrentElement(); currEl.currentContentIndex++; // Each time we step off the end, we fall out to the next container, all // the // while we're in indexed rather than named content while (currEl.currentContentIndex >= currEl.currentContainer.getContent().size()) { successfulIncrement = false; Container nextAncestor = currEl.currentContainer.getParent() instanceof Container ? (Container) currEl.currentContainer.getParent() : null; if (nextAncestor == null) { break; } int indexInAncestor = nextAncestor.getContent().indexOf(currEl.currentContainer); if (indexInAncestor == -1) { break; } currEl.currentContainer = nextAncestor; currEl.currentContentIndex = indexInAncestor + 1; successfulIncrement = true; } if (!successfulIncrement) currEl.currentContainer = null; return successfulIncrement; } void incrementVisitCountForContainer(Container container) { String containerPathStr = container.getPath().toString(); Integer count = state.getVisitCounts().get(containerPathStr); if (count == null) count = 0; count++; state.getVisitCounts().put(containerPathStr, count); } // Does the expression result represented by this Object evaluate to true? // e.g. is it a Number that's not equal to 1? boolean isTruthy(RTObject obj) throws Exception { boolean truthy = false; if (obj instanceof Value) { Value<?> val = (Value<?>) obj; if (val instanceof DivertTargetValue) { DivertTargetValue divTarget = (DivertTargetValue) val; error("Shouldn't use a divert target (to " + divTarget.getTargetPath() + ") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"); return false; } return val.isTruthy(); } return truthy; } /** * When the named global variable changes it's value, the observer will be * called to notify it of the change. Note that if the value changes * multiple times within the ink, the observer will only be called once, at * the end of the ink's evaluation. If, during the evaluation, it changes * and then changes back again to its original value, it will still be * called. Note that the observer will also be fired if the value of the * variable is changed externally to the ink, by directly setting a value in * story.variablesState. * * @param variableName * The name of the global variable to observe. * @param observer * A delegate function to call when the variable changes. */ public void observeVariable(String variableName, VariableObserver observer) { if (variableObservers == null) variableObservers = new HashMap<String, List<VariableObserver>>(); if (variableObservers.containsKey(variableName)) { variableObservers.get(variableName).add(observer); } else { List<VariableObserver> l = new ArrayList<VariableObserver>(); l.add(observer); variableObservers.put(variableName, l); } } /** * Convenience function to allow multiple variables to be observed with the * same observer delegate function. See the singular ObserveVariable for * details. The observer will get one call for every variable that has * changed. * * @param variableNames * The set of variables to observe. * @param observer * The delegate function to call when any of the named variables * change. */ public void observeVariables(List<String> variableNames, VariableObserver observer) { for (String varName : variableNames) { observeVariable(varName, observer); } } /** * Removes the variable observer, to stop getting variable change * notifications. If you pass a specific variable name, it will stop * observing that particular one. If you pass null (or leave it blank, since * it's optional), then the observer will be removed from all variables that * it's subscribed to. * * @param observer * The observer to stop observing. * @param specificVariableName * (Optional) Specific variable name to stop observing. */ public void removeVariableObserver(VariableObserver observer, String specificVariableName) { if (variableObservers == null) return; // Remove observer for this specific variable if (specificVariableName != null) { if (variableObservers.containsKey(specificVariableName)) { variableObservers.get(specificVariableName).remove(observer); } } else { // Remove observer for all variables for (List<VariableObserver> obs : variableObservers.values()) { obs.remove(observer); } } } public void removeVariableObserver(VariableObserver observer) { removeVariableObserver(observer, null); } @Override public void variableStateDidChangeEvent(String variableName, RTObject newValueObj) throws Exception { if (variableObservers == null) return; List<VariableObserver> observers = variableObservers.get(variableName); if (observers != null) { if (!(newValueObj instanceof Value)) { throw new Exception("Tried to get the value of a variable that isn't a standard type"); } Value<?> val = (Value<?>) newValueObj; for (VariableObserver o : observers) { o.call(variableName, val.getValueObject()); } } } Container mainContentContainer() { if (temporaryEvaluationContainer != null) { return temporaryEvaluationContainer; } else { return mainContentContainer; } } String BuildStringOfContainer(Container container) { StringBuilder sb = new StringBuilder(); container.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject()); return sb.toString(); } private void nextContent() throws Exception { // Setting previousContentObject is critical for // VisitChangedContainersDueToDivert state.setPreviousContentObject(state.getCurrentContentObject()); // Divert step? if (state.getDivertedTargetObject() != null) { state.setCurrentContentObject(state.getDivertedTargetObject()); state.setDivertedTargetObject(null); // Internally uses state.previousContentObject and // state.currentContentObject visitChangedContainersDueToDivert(); // Diverted location has valid content? if (state.getCurrentContentObject() != null) { return; } // Otherwise, if diverted location doesn't have valid content, // drop down and attempt to increment. // This can happen if the diverted path is intentionally jumping // to the end of a container - e.g. a Conditional that's re-joining } boolean successfulPointerIncrement = incrementContentPointer(); // Ran out of content? Try to auto-exit from a function, // or finish evaluating the content of a thread if (!successfulPointerIncrement) { boolean didPop = false; if (state.getCallStack().canPop(PushPopType.Function)) { // Pop from the call stack state.getCallStack().pop(PushPopType.Function); // This pop was due to dropping off the end of a function that // didn't return anything, // so in this case, we make sure that the evaluator has // something to chomp on if it needs it if (state.getInExpressionEvaluation()) { state.pushEvaluationStack(new Void()); } didPop = true; } else if (state.getCallStack().canPopThread()) { state.getCallStack().popThread(); didPop = true; } else { state.tryExitExternalFunctionEvaluation(); } // Step past the point where we last called out if (didPop && state.getCurrentContentObject() != null) { nextContent(); } } } // Note that this is O(n), since it re-evaluates the shuffle indices // from a consistent seed each time. // TODO: Is this the best algorithm it can be? int nextSequenceShuffleIndex() throws Exception { RTObject popEvaluationStack = state.popEvaluationStack(); IntValue numElementsIntVal = popEvaluationStack instanceof IntValue ? (IntValue) popEvaluationStack : null; if (numElementsIntVal == null) { error("expected number of elements in sequence for shuffle index"); return 0; } Container seqContainer = state.currentContainer(); int numElements = numElementsIntVal.value; IntValue seqCountVal = (IntValue) state.popEvaluationStack(); int seqCount = seqCountVal.value; int loopIndex = seqCount / numElements; int iterationIndex = seqCount % numElements; // Generate the same shuffle based on: // - The hash of this container, to make sure it's consistent // each time the runtime returns to the sequence // - How many times the runtime has looped around this full shuffle String seqPathStr = seqContainer.getPath().toString(); int sequenceHash = 0; for (char c : seqPathStr.toCharArray()) { sequenceHash += c; } int randomSeed = sequenceHash + loopIndex + state.getStorySeed(); Random random = new Random(randomSeed); ArrayList<Integer> unpickedIndices = new ArrayList<Integer>(); for (int i = 0; i < numElements; ++i) { unpickedIndices.add(i); } for (int i = 0; i <= iterationIndex; ++i) { int chosen = random.nextInt(Integer.MAX_VALUE) % unpickedIndices.size(); int chosenIndex = unpickedIndices.get(chosen); unpickedIndices.remove(chosen); if (i == iterationIndex) { return chosenIndex; } } throw new Exception("Should never reach here"); } /** * Checks whether contentObj is a control or flow Object rather than a piece * of content, and performs the required command if necessary. * * @return true if Object was logic or flow control, false if it's normal * content. * @param contentObj * Content Object. */ boolean performLogicAndFlowControl(RTObject contentObj) throws Exception { if (contentObj == null) { return false; } // Divert if (contentObj instanceof Divert) { Divert currentDivert = (Divert) contentObj; if (currentDivert.isConditional()) { RTObject conditionValue = state.popEvaluationStack(); // False conditional? Cancel divert if (!isTruthy(conditionValue)) return true; } if (currentDivert.hasVariableTarget()) { String varName = currentDivert.getVariableDivertName(); RTObject varContents = state.getVariablesState().getVariableWithName(varName); if (!(varContents instanceof DivertTargetValue)) { IntValue intContent = varContents instanceof IntValue ? (IntValue) varContents : null; String errorMessage = "Tried to divert to a target from a variable, but the variable (" + varName + ") didn't contain a divert target, it "; if (intContent != null && intContent.value == 0) { errorMessage += "was empty/null (the value 0)."; } else { errorMessage += "contained '" + varContents + "'."; } error(errorMessage); } DivertTargetValue target = (DivertTargetValue) varContents; state.setDivertedTargetObject(contentAtPath(target.getTargetPath())); } else if (currentDivert.isExternal()) { callExternalFunction(currentDivert.getTargetPathString(), currentDivert.getExternalArgs()); return true; } else { state.setDivertedTargetObject(currentDivert.getTargetContent()); } if (currentDivert.getPushesToStack()) { state.getCallStack().push(currentDivert.getStackPushType()); } if (state.getDivertedTargetObject() == null && !currentDivert.isExternal()) { // Human readable name available - runtime divert is part of a // hard-written divert that to missing content if (currentDivert != null && currentDivert.getDebugMetadata().sourceName != null) { error("Divert target doesn't exist: " + currentDivert.getDebugMetadata().sourceName); } else { error("Divert resolution failed: " + currentDivert); } } return true; } // Start/end an expression evaluation? Or print out the result? else if (contentObj instanceof ControlCommand) { ControlCommand evalCommand = (ControlCommand) contentObj; int choiceCount; switch (evalCommand.getCommandType()) { case EvalStart: Assert(state.getInExpressionEvaluation() == false, "Already in expression evaluation?"); state.setInExpressionEvaluation(true); break; case EvalEnd: Assert(state.getInExpressionEvaluation() == true, "Not in expression evaluation mode"); state.setInExpressionEvaluation(false); break; case EvalOutput: // If the expression turned out to be empty, there may not be // anything on the stack if (state.getEvaluationStack().size() > 0) { RTObject output = state.popEvaluationStack(); // Functions may evaluate to Void, in which case we skip // output if (!(output instanceof Void)) { // TODO: Should we really always blanket convert to // string? // It would be okay to have numbers in the output stream // the // only problem is when exporting text for viewing, it // skips over numbers etc. StringValue text = new StringValue(output.toString()); state.pushToOutputStream(text); } } break; case NoOp: break; case Duplicate: state.pushEvaluationStack(state.peekEvaluationStack()); break; case PopEvaluatedValue: state.popEvaluationStack(); break; case PopFunction: case PopTunnel: PushPopType popType = evalCommand.getCommandType() == ControlCommand.CommandType.PopFunction ? PushPopType.Function : PushPopType.Tunnel; // Tunnel onwards is allowed to specify an optional override // divert to go to immediately after returning: ->-> target DivertTargetValue overrideTunnelReturnTarget = null; if (popType == PushPopType.Tunnel) { RTObject popped = state.popEvaluationStack(); if (popped instanceof DivertTargetValue) { overrideTunnelReturnTarget = (DivertTargetValue) popped; } if (overrideTunnelReturnTarget == null) { Assert(popped instanceof Void, "Expected void if ->-> doesn't override target"); } } if (state.tryExitExternalFunctionEvaluation()) { break; } else if (state.getCallStack().getCurrentElement().type != popType || !state.getCallStack().canPop()) { HashMap<PushPopType, String> names = new HashMap<PushPopType, String>(); names.put(PushPopType.Function, "function return statement (~ return)"); names.put(PushPopType.Tunnel, "tunnel onwards statement (->->)"); String expected = names.get(state.getCallStack().getCurrentElement().type); if (!state.getCallStack().canPop()) { expected = "end of flow (-> END or choice)"; } String errorMsg = String.format("Found %s, when expected %s", names.get(popType), expected); error(errorMsg); } else { state.getCallStack().pop(); // Does tunnel onwards override by diverting to a new ->-> // target? if (overrideTunnelReturnTarget != null) state.setDivertedTargetObject(contentAtPath(overrideTunnelReturnTarget.getTargetPath())); } break; case BeginString: state.pushToOutputStream(evalCommand); Assert(state.getInExpressionEvaluation() == true, "Expected to be in an expression when evaluating a string"); state.setInExpressionEvaluation(false); break; case EndString: // Since we're iterating backward through the content, // build a stack so that when we build the string, // it's in the right order Stack<RTObject> contentStackForString = new Stack<RTObject>(); int outputCountConsumed = 0; for (int i = state.getOutputStream().size() - 1; i >= 0; --i) { RTObject obj = state.getOutputStream().get(i); outputCountConsumed++; ControlCommand command = obj instanceof ControlCommand ? (ControlCommand) obj : null; if (command != null && command.getCommandType() == ControlCommand.CommandType.BeginString) { break; } if (obj instanceof StringValue) contentStackForString.push(obj); } // Consume the content that was produced for this string state.getOutputStream() .subList(state.getOutputStream().size() - outputCountConsumed, state.getOutputStream().size()) .clear(); // Build String out of the content we collected StringBuilder sb = new StringBuilder(); while (contentStackForString.size() > 0) { RTObject c = contentStackForString.pop(); sb.append(c.toString()); } // Return to expression evaluation (from content mode) state.setInExpressionEvaluation(true); state.pushEvaluationStack(new StringValue(sb.toString())); break; case ChoiceCount: choiceCount = state.getGeneratedChoices().size(); state.pushEvaluationStack(new IntValue(choiceCount)); break; case TurnsSince: case ReadCount: RTObject target = state.popEvaluationStack(); if (!(target instanceof DivertTargetValue)) { String extraNote = ""; if (target instanceof IntValue) extraNote = ". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?"; error("TURNS_SINCE expected a divert target (knot, stitch, label name), but saw " + target + extraNote); break; } DivertTargetValue divertTarget = target instanceof DivertTargetValue ? (DivertTargetValue) target : null; Container container = contentAtPath(divertTarget.getTargetPath()) instanceof Container ? (Container) contentAtPath(divertTarget.getTargetPath()) : null; int eitherCount; if (evalCommand.getCommandType() == ControlCommand.CommandType.TurnsSince) eitherCount = turnsSinceForContainer(container); else eitherCount = visitCountForContainer(container); state.pushEvaluationStack(new IntValue(eitherCount)); break; case Random: { IntValue maxInt = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) maxInt = (IntValue) o; IntValue minInt = null; o = state.popEvaluationStack(); if (o instanceof IntValue) minInt = (IntValue) o; if (minInt == null) error("Invalid value for minimum parameter of RANDOM(min, max)"); if (maxInt == null) error("Invalid value for maximum parameter of RANDOM(min, max)"); // +1 because it's inclusive of min and max, for e.g. // RANDOM(1,6) for a dice roll. int randomRange = maxInt.value - minInt.value + 1; if (randomRange <= 0) error("RANDOM was called with minimum as " + minInt.value + " and maximum as " + maxInt.value + ". The maximum must be larger"); int resultSeed = state.getStorySeed() + state.getPreviousRandom(); Random random = new Random(resultSeed); int nextRandom = random.nextInt(Integer.MAX_VALUE); int chosenValue = (nextRandom % randomRange) + minInt.value; state.pushEvaluationStack(new IntValue(chosenValue)); // Next random number (rather than keeping the Random object // around) state.setPreviousRandom(state.getPreviousRandom() + 1); break; } case SeedRandom: { IntValue seed = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) seed = (IntValue) o; if (seed == null) error("Invalid value passed to SEED_RANDOM"); // Story seed affects both RANDOM and shuffle behaviour state.setStorySeed(seed.value); state.setPreviousRandom(0); // SEED_RANDOM returns nothing. state.pushEvaluationStack(new Void()); break; } case VisitIndex: int count = visitCountForContainer(state.currentContainer()) - 1; // index // not // count state.pushEvaluationStack(new IntValue(count)); break; case SequenceShuffleIndex: int shuffleIndex = nextSequenceShuffleIndex(); state.pushEvaluationStack(new IntValue(shuffleIndex)); break; case StartThread: // Handled in main step function break; case Done: // We may exist in the context of the initial // act of creating the thread, or in the context of // evaluating the content. if (state.getCallStack().canPopThread()) { state.getCallStack().popThread(); } // In normal flow - allow safe exit without warning else { state.setDidSafeExit(true); // Stop flow in current thread state.setCurrentContentObject(null); } break; // Force flow to end completely case End: state.forceEnd(); break; case ListFromInt: { IntValue intVal = null; RTObject o = state.popEvaluationStack(); if (o instanceof IntValue) intVal = (IntValue) o; StringValue listNameVal = null; o = state.popEvaluationStack(); if (o instanceof StringValue) listNameVal = (StringValue) o; if(intVal == null) { throw new StoryException ("Passed non-integer when creating a list element from a numerical value."); } ListValue generatedListValue = null; ListDefinition foundListDef = listsDefinitions.getDefinition(listNameVal.value); if (foundListDef != null) { InkListItem foundItem; foundItem = foundListDef.getItemWithValue(intVal.value); if (foundItem != null) { generatedListValue = new ListValue(foundItem, intVal.value); } } else { throw new StoryException("Failed to find List called " + listNameVal.value); } if (generatedListValue == null) generatedListValue = new ListValue(); state.pushEvaluationStack(generatedListValue); break; } case ListRange: { RTObject max = state.popEvaluationStack(); RTObject min = state.popEvaluationStack(); RTObject targetRT = state.popEvaluationStack(); ListValue targetList = null; if (targetRT instanceof ListValue) targetList = (ListValue) targetRT; if (targetList == null || min == null || max == null) throw new StoryException("Expected List, minimum and maximum for LIST_RANGE"); int minVal = -1; if (min instanceof ListValue) { minVal = (int) ((ListValue) min).getValue().getMaxItem().getValue(); } else if (min instanceof IntValue) { minVal = (int) ((IntValue) min).getValue(); } int maxVal = -1; if (max instanceof ListValue) { maxVal = (int) ((ListValue) min).getValue().getMaxItem().getValue(); } else if (min instanceof IntValue) { maxVal = (int) ((IntValue) min).getValue(); } if (minVal == -1) throw new StoryException("Invalid min range bound passed to LIST_RANGE(): " + min); if (maxVal == -1) throw new StoryException("Invalid max range bound passed to LIST_RANGE(): " + max); // Extract the range of items from the origin set ListValue result = new ListValue(); List<ListDefinition> origins = targetList.value.origins; if (origins != null) { for (ListDefinition origin : origins) { ListValue rangeFromOrigin = origin.listRange(minVal, maxVal); for (Entry<InkListItem, Integer> kv : rangeFromOrigin.getValue().entrySet()) { result.value.put(kv.getKey(), kv.getValue()); } } } state.pushEvaluationStack(result); break; } default: error("unhandled ControlCommand: " + evalCommand); break; } return true; } // Variable assignment else if (contentObj instanceof VariableAssignment) { VariableAssignment varAss = (VariableAssignment) contentObj; RTObject assignedVal = state.popEvaluationStack(); // When in temporary evaluation, don't create new variables purely // within // the temporary context, but attempt to create them globally // var prioritiseHigherInCallStack = _temporaryEvaluationContainer // != null; state.getVariablesState().assign(varAss, assignedVal); return true; } // Variable reference else if (contentObj instanceof VariableReference) { VariableReference varRef = (VariableReference) contentObj; RTObject foundValue = null; // Explicit read count value if (varRef.getPathForCount() != null) { Container container = varRef.getContainerForCount(); int count = visitCountForContainer(container); foundValue = new IntValue(count); } // Normal variable reference else { foundValue = state.getVariablesState().getVariableWithName(varRef.getName()); if (foundValue == null) { error("Uninitialised variable: " + varRef.getName()); foundValue = new IntValue(0); } } state.pushEvaluationStack(foundValue); return true; } // Native function call else if (contentObj instanceof NativeFunctionCall) { NativeFunctionCall func = (NativeFunctionCall) contentObj; List<RTObject> funcParams = state.popEvaluationStack(func.getNumberOfParameters()); RTObject result = func.call(funcParams); state.pushEvaluationStack(result); return true; } // No control content, must be ordinary content return false; } Choice processChoice(ChoicePoint choicePoint) throws Exception { boolean showChoice = true; // Don't create choice if choice point doesn't pass conditional if (choicePoint.hasCondition()) { RTObject conditionValue = state.popEvaluationStack(); if (!isTruthy(conditionValue)) { showChoice = false; } } String startText = ""; String choiceOnlyText = ""; if (choicePoint.hasChoiceOnlyContent()) { StringValue choiceOnlyStrVal = (StringValue) state.popEvaluationStack(); choiceOnlyText = choiceOnlyStrVal.value; } if (choicePoint.hasStartContent()) { StringValue startStrVal = (StringValue) state.popEvaluationStack(); startText = startStrVal.value; } // Don't create choice if player has already read this content if (choicePoint.isOnceOnly()) { int visitCount = visitCountForContainer(choicePoint.getChoiceTarget()); if (visitCount > 0) { showChoice = false; } } Choice choice = new Choice(choicePoint); choice.setThreadAtGeneration(state.getCallStack().getcurrentThread().copy()); // We go through the full process of creating the choice above so // that we consume the content for it, since otherwise it'll // be shown on the output stream. if (!showChoice) { return null; } // Set final text for the choice choice.setText(startText + choiceOnlyText); return choice; } void recordTurnIndexVisitToContainer(Container container) { String containerPathStr = container.getPath().toString(); state.getTurnIndices().put(containerPathStr, state.getCurrentTurnIndex()); } /** * Unwinds the callstack. Useful to reset the Story's evaluation without * actually changing any meaningful state, for example if you want to exit a * section of story prematurely and tell it to go elsewhere with a call to * ChoosePathString(...). Doing so without calling ResetCallstack() could * cause unexpected issues if, for example, the Story was in a tunnel * already. */ public void resetCallstack() throws Exception { state.forceEnd(); } /** * Reset the runtime error list within the state. */ public void resetErrors() { state.resetErrors(); } void resetGlobals() throws Exception { if (mainContentContainer.getNamedContent().containsKey("global decl")) { Path originalPath = getState().getCurrentPath(); choosePathString("global decl"); // Continue, but without validating external bindings, // since we may be doing this reset at initialisation time. continueInternal(); getState().setCurrentPath(originalPath); } } /** * Reset the Story back to its initial state as it was when it was first * constructed. */ public void resetState() throws Exception { state = new StoryState(this); state.getVariablesState().setVariableChangedEvent(this); resetGlobals(); } void restoreStateSnapshot(StoryState state) { this.state = state; } StoryState stateSnapshot() throws Exception { return state.copy(); } void step() throws Exception { boolean shouldAddToStream = true; // Get current content RTObject currentContentObj = state.getCurrentContentObject(); if (currentContentObj == null) { return; } // Step directly to the first element of content in a container (if // necessary) Container currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null; while (currentContainer != null) { // Mark container as being entered visitContainer(currentContainer, true); // No content? the most we can do is step past it if (currentContainer.getContent().size() == 0) break; currentContentObj = currentContainer.getContent().get(0); state.getCallStack().getCurrentElement().currentContentIndex = 0; state.getCallStack().getCurrentElement().currentContainer = currentContainer; currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null; } currentContainer = state.getCallStack().getCurrentElement().currentContainer; // Is the current content Object: // - Normal content // - Or a logic/flow statement - if so, do it // Stop flow if we hit a stack pop when we're unable to pop (e.g. // return/done statement in knot // that was diverted to rather than called as a function) boolean isLogicOrFlowControl = performLogicAndFlowControl(currentContentObj); // Has flow been forced to end by flow control above? if (state.getCurrentContentObject() == null) { return; } if (isLogicOrFlowControl) { shouldAddToStream = false; } // Choice with condition? ChoicePoint choicePoint = currentContentObj instanceof ChoicePoint ? (ChoicePoint) currentContentObj : null; if (choicePoint != null) { Choice choice = processChoice(choicePoint); if (choice != null) { state.getGeneratedChoices().add(choice); } currentContentObj = null; shouldAddToStream = false; } // If the container has no content, then it will be // the "content" itself, but we skip over it. if (currentContentObj instanceof Container) { shouldAddToStream = false; } // Content to add to evaluation stack or the output stream if (shouldAddToStream) { // If we're pushing a variable pointer onto the evaluation stack, // ensure that it's specific // to our current (possibly temporary) context index. And make a // copy of the pointer // so that we're not editing the original runtime Object. VariablePointerValue varPointer = currentContentObj instanceof VariablePointerValue ? (VariablePointerValue) currentContentObj : null; if (varPointer != null && varPointer.getContextIndex() == -1) { // Create new Object so we're not overwriting the story's own // data int contextIdx = state.getCallStack().contextForVariableNamed(varPointer.getVariableName()); currentContentObj = new VariablePointerValue(varPointer.getVariableName(), contextIdx); } // Expression evaluation content if (state.getInExpressionEvaluation()) { state.pushEvaluationStack(currentContentObj); } // Output stream content (i.e. not expression evaluation) else { state.pushToOutputStream(currentContentObj); } } // Increment the content pointer, following diverts if necessary nextContent(); // Starting a thread should be done after the increment to the content // pointer, // so that when returning from the thread, it returns to the content // after this instruction. ControlCommand controlCmd = currentContentObj instanceof ControlCommand ? (ControlCommand) currentContentObj : null; if (controlCmd != null && controlCmd.getCommandType() == ControlCommand.CommandType.StartThread) { state.getCallStack().pushThread(); } } /** * The Story itself in JSON representation. */ public String toJsonString() throws Exception { List<?> rootContainerJsonList = (List<?>) Json.runtimeObjectToJToken(mainContentContainer); HashMap<String, Object> rootObject = new HashMap<String, Object>(); rootObject.put("inkVersion", inkVersionCurrent); rootObject.put("root", rootContainerJsonList); return SimpleJson.HashMapToText(rootObject); } boolean tryFollowDefaultInvisibleChoice() throws Exception { List<Choice> allChoices = state.getCurrentChoices(); // Is a default invisible choice the ONLY choice? // var invisibleChoices = allChoices.Where (c => // c.choicePoint.isInvisibleDefault).ToList(); ArrayList<Choice> invisibleChoices = new ArrayList<Choice>(); for (Choice c : allChoices) { if (c.getchoicePoint().isInvisibleDefault()) { invisibleChoices.add(c); } } if (invisibleChoices.size() == 0 || allChoices.size() > invisibleChoices.size()) return false; Choice choice = invisibleChoices.get(0); choosePath(choice.getchoicePoint().getChoiceTarget().getPath()); return true; } int turnsSinceForContainer(Container container) throws Exception { if (!container.getTurnIndexShouldBeCounted()) { error("TURNS_SINCE() for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown. The story may need to be compiled with countAllVisits flag (-c)."); } String containerPathStr = container.getPath().toString(); Integer index = state.getTurnIndices().get(containerPathStr); if (index != null) { return state.getCurrentTurnIndex() - index; } else { return -1; } } /** * Remove a binding for a named EXTERNAL ink function. */ public void unbindExternalFunction(String funcName) throws Exception { Assert(externals.containsKey(funcName), "Function '" + funcName + "' has not been bound."); externals.remove(funcName); } /** * Check that all EXTERNAL ink functions have a valid bound C# function. * Note that this is automatically called on the first call to Continue(). */ public void validateExternalBindings() throws Exception { HashSet<String> missingExternals = new HashSet<String>(); validateExternalBindings(mainContentContainer, missingExternals); hasValidatedExternals = true; // No problem! Validation complete if (missingExternals.size() == 0) { hasValidatedExternals = true; } else { // Error for all missing externals StringBuilder join = new StringBuilder(); boolean first = true; for (String item : missingExternals) { if (first) first = false; else join.append(", "); join.append(item); } String message = String.format("ERROR: Missing function binding for external%s: '%s' %s", missingExternals.size() > 1 ? "s" : "", join.toString(), allowExternalFunctionFallbacks ? ", and no fallback ink function found." : " (ink fallbacks disabled)"); error(message); } } void validateExternalBindings(Container c, HashSet<String> missingExternals) throws Exception { for (RTObject innerContent : c.getContent()) { Container container = innerContent instanceof Container ? (Container) innerContent : null; if (container == null || !container.hasValidName()) validateExternalBindings(innerContent, missingExternals); } for (INamedContent innerKeyValue : c.getNamedContent().values()) { validateExternalBindings(innerKeyValue instanceof RTObject ? (RTObject) innerKeyValue : (RTObject) null, missingExternals); } } void validateExternalBindings(RTObject o, HashSet<String> missingExternals) throws Exception { Container container = o instanceof Container ? (Container) o : null; if (container != null) { validateExternalBindings(container, missingExternals); return; } Divert divert = o instanceof Divert ? (Divert) o : null; if (divert != null && divert.isExternal()) { String name = divert.getTargetPathString(); if (!externals.containsKey(name)) { if (allowExternalFunctionFallbacks) { boolean fallbackFound = mainContentContainer.getNamedContent().containsKey(name); if (!fallbackFound) { missingExternals.add(name); } } else { missingExternals.add(name); } } } } void visitChangedContainersDueToDivert() { RTObject previousContentObject = state.getPreviousContentObject(); RTObject newContentObject = state.getCurrentContentObject(); if (newContentObject == null) return; // First, find the previously open set of containers if (prevContainerSet == null) prevContainerSet = new HashSet<Container>(); prevContainerSet.clear(); if (previousContentObject != null) { Container prevAncestor = null; if (previousContentObject instanceof Container) { prevAncestor = (Container) previousContentObject; } else if (previousContentObject.getParent() instanceof Container) { prevAncestor = (Container) previousContentObject.getParent(); } while (prevAncestor != null) { prevContainerSet.add(prevAncestor); prevAncestor = prevAncestor.getParent() instanceof Container ? (Container) prevAncestor.getParent() : null; } } // If the new Object is a container itself, it will be visited // automatically at the next actual // content step. However, we need to walk up the new ancestry to see if // there are more new containers RTObject currentChildOfContainer = newContentObject; Container currentContainerAncestor = currentChildOfContainer.getParent() instanceof Container ? (Container) currentChildOfContainer.getParent() : null; while (currentContainerAncestor != null && !prevContainerSet.contains(currentContainerAncestor)) { // Check whether this ancestor container is being entered at the // start, // by checking whether the child Object is the first. boolean enteringAtStart = currentContainerAncestor.getContent().size() > 0 && currentChildOfContainer == currentContainerAncestor.getContent().get(0); // Mark a visit to this container visitContainer(currentContainerAncestor, enteringAtStart); currentChildOfContainer = currentContainerAncestor; currentContainerAncestor = currentContainerAncestor.getParent() instanceof Container ? (Container) currentContainerAncestor.getParent() : null; } } // Mark a container as having been visited void visitContainer(Container container, boolean atStart) { if (!container.getCountingAtStartOnly() || atStart) { if (container.getVisitsShouldBeCounted()) incrementVisitCountForContainer(container); if (container.getTurnIndexShouldBeCounted()) recordTurnIndexVisitToContainer(container); } } int visitCountForContainer(Container container) throws Exception { if (!container.getVisitsShouldBeCounted()) { error("Read count for target (" + container.getName() + " - on " + container.getDebugMetadata() + ") unknown. The story may need to be compiled with countAllVisits flag (-c)."); return 0; } String containerPathStr = container.getPath().toString(); Integer count = state.getVisitCounts().get(containerPathStr); return count == null ? 0 : count; } public boolean allowExternalFunctionFallbacks() { return allowExternalFunctionFallbacks; } public void setAllowExternalFunctionFallbacks(boolean allowExternalFunctionFallbacks) { this.allowExternalFunctionFallbacks = allowExternalFunctionFallbacks; } /** * Evaluates a function defined in ink. * * @param functionName * The name of the function as declared in ink. * @param arguments * The arguments that the ink function takes, if any. Note that * we don't (can't) do any validation on the number of arguments * right now, so make sure you get it right! * @return The return value as returned from the ink function with `~ return * myValue`, or null if nothing is returned. * @throws Exception */ public Object evaluateFunction(String functionName, Object[] arguments) throws Exception { return evaluateFunction(functionName, null, arguments); } public Object evaluateFunction(String functionName) throws Exception { return evaluateFunction(functionName, null, null); } /** * Checks if a function exists. * * @return True if the function exists, else false. * @param functionName * The name of the function as declared in ink. */ public boolean hasFunction(String functionName) { try { return contentAtPath(new Path(functionName)) instanceof Container; } catch (Exception e) { return false; } } /** * Evaluates a function defined in ink, and gathers the possibly multi-line * text as generated by the function. * * @param arguments * The arguments that the ink function takes, if any. Note that * we don't (can't) do any validation on the number of arguments * right now, so make sure you get it right! * @param functionName * The name of the function as declared in ink. * @param textOutput * This text output is any text written as normal content within * the function, as opposed to the return value, as returned with * `~ return`. * @return The return value as returned from the ink function with `~ return * myValue`, or null if nothing is returned. * @throws Exception */ public Object evaluateFunction(String functionName, StringBuffer textOutput, Object[] arguments) throws Exception { // Get the content that we need to run Container funcContainer = null; if (functionName == null) { throw new Exception("Function is null"); } else if (functionName.trim().isEmpty()) { throw new Exception("Function is empty or white space."); } try { RTObject contentAtPath = contentAtPath(new Path(functionName)); if (contentAtPath instanceof Container) funcContainer = (Container) contentAtPath; } catch (StoryException e) { if (e.getMessage().contains("not found")) throw new Exception("Function doesn't exist: '" + functionName + "'"); else throw e; } // State will temporarily replace the callstack in order to evaluate state.startExternalFunctionEvaluation(funcContainer, arguments); // Evaluate the function, and collect the string output while (canContinue()) { String text = Continue(); if (textOutput != null) textOutput.append(text); } // Finish evaluation, and see whether anything was produced Object result = state.completeExternalFunctionEvaluation(); return result; } }
C# ref. commit: Try to produce more useful runtime error message if you don’t have access to line numbers
src/main/java/com/bladecoder/ink/runtime/Story.java
C# ref. commit: Try to produce more useful runtime error message if you don’t have access to line numbers
<ide><path>rc/main/java/com/bladecoder/ink/runtime/Story.java <ide> if (dm != null) { <ide> int lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber; <ide> message = String.format("RUNTIME ERROR: '%s' line %d: %s", dm.fileName, lineNum, message); <add> } else if( state.getCurrentPath() != null ) { <add> message = String.format ("RUNTIME ERROR: (%s): %s", state.getCurrentPath().toString(), message); <ide> } else { <ide> message = "RUNTIME ERROR: " + message; <ide> }
JavaScript
mit
7343661f33dc8fb6e8a99291632ab7d484a3b3b5
0
Intendit/bolt,joshuan/bolt,marcin-piela/bolt,pygillier/bolt,Raistlfiren/bolt,GawainLynch/bolt,Intendit/bolt,tekjava/bolt,bolt/bolt,marcin-piela/bolt,nantunes/bolt,codesman/bolt,rossriley/bolt,GawainLynch/bolt,rossriley/bolt,nikgo/bolt,one988/cm,nantunes/bolt,lenvanessen/bolt,electrolinux/bolt,Eiskis/bolt-base,richardhinkamp/bolt,romulo1984/bolt,joshuan/bolt,lenvanessen/bolt,pygillier/bolt,tekjava/bolt,nikgo/bolt,hugin2005/bolt,HonzaMikula/masivnipostele,joshuan/bolt,kendoctor/bolt,codesman/bolt,rarila/bolt,Calinou/bolt,hannesl/bolt,marcin-piela/bolt,xeddmc/bolt,nikgo/bolt,Eiskis/bolt-base,hannesl/bolt,cdowdy/bolt,pygillier/bolt,cdowdy/bolt,rarila/bolt,one988/cm,hugin2005/bolt,kendoctor/bolt,pygillier/bolt,lenvanessen/bolt,Calinou/bolt,cdowdy/bolt,rossriley/bolt,richardhinkamp/bolt,HonzaMikula/masivnipostele,Calinou/bolt,codesman/bolt,Intendit/bolt,winiceo/bolt,kendoctor/bolt,nikgo/bolt,nantunes/bolt,one988/cm,electrolinux/bolt,electrolinux/bolt,HonzaMikula/masivnipostele,Raistlfiren/bolt,HonzaMikula/masivnipostele,xeddmc/bolt,nantunes/bolt,richardhinkamp/bolt,winiceo/bolt,lenvanessen/bolt,rossriley/bolt,hugin2005/bolt,codesman/bolt,rarila/bolt,Calinou/bolt,winiceo/bolt,electrolinux/bolt,romulo1984/bolt,richardhinkamp/bolt,bolt/bolt,kendoctor/bolt,romulo1984/bolt,CarsonF/bolt,bolt/bolt,Eiskis/bolt-base,hannesl/bolt,winiceo/bolt,xeddmc/bolt,tekjava/bolt,cdowdy/bolt,Intendit/bolt,rarila/bolt,hannesl/bolt,xeddmc/bolt,joshuan/bolt,one988/cm,Eiskis/bolt-base,GawainLynch/bolt,Raistlfiren/bolt,romulo1984/bolt,CarsonF/bolt,GawainLynch/bolt,marcin-piela/bolt,CarsonF/bolt,hugin2005/bolt,Raistlfiren/bolt,tekjava/bolt,bolt/bolt,CarsonF/bolt
/* global module */ /* * BOOTLINT: HTML linter for Bootstrap projects */ module.exports = function (grunt, options) { var conf = { relaxerror: ['W005'], showallerrors: false, stoponerror: false, stoponwarning: false }; // Override settings require('deep-extend')(conf, options.bootlint); return { /* * TARGET: Check html files in "path.pages" */ pages: { options: conf, src: '<%= path.pages %>/*.html' } }; };
app/src/grunt/bootlint.js
/* global module */ /* * BOOTLINT: HTML linter for Bootstrap projects */ module.exports = function (grunt, options) { var conf = { relaxerror: [], showallerrors: false, stoponerror: false, stoponwarning: false }; // Override settings require('deep-extend')(conf, options.bootlint); return { /* * TARGET: Check html files in "path.pages" */ pages: { options: conf, src: '<%= path.pages %>/*.html' } }; };
Relax bootlint on 'W005' as it can't find jquery inside lib.js
app/src/grunt/bootlint.js
Relax bootlint on 'W005' as it can't find jquery inside lib.js
<ide><path>pp/src/grunt/bootlint.js <ide> */ <ide> module.exports = function (grunt, options) { <ide> var conf = { <del> relaxerror: [], <add> relaxerror: ['W005'], <ide> showallerrors: false, <ide> stoponerror: false, <ide> stoponwarning: false
Java
apache-2.0
7b791b0ae1ee30f50011776a17b353a3a8f35d4e
0
cherryhill/collectionspace-services,cherryhill/collectionspace-services
/** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * * http://www.collectionspace.org * http://wiki.collectionspace.org * * Copyright (c)) 2009 Regents of the University of California * * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.collectionspace.services.client.importer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.apache.log4j.BasicConfigurator; import org.collectionspace.services.client.VocabularyClient; import org.collectionspace.services.client.test.ServiceRequestType; import org.collectionspace.services.vocabulary.VocabulariesCommon; import org.collectionspace.services.vocabulary.VocabularyitemsCommon; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; import org.jboss.resteasy.plugins.providers.multipart.OutputPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * VocabularyServiceTest, carries out tests against a * deployed and running Vocabulary Service. * * $LastChangedRevision: 753 $ * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $ */ public class VocabularyBaseImport { private static final Logger logger = LoggerFactory.getLogger(VocabularyBaseImport.class); // Instance variables specific to this test. private VocabularyClient client = new VocabularyClient(); final String SERVICE_PATH_COMPONENT = "vocabularies"; final String ITEM_SERVICE_PATH_COMPONENT = "items"; public void createEnumeration(String vocabName, List<String> enumValues ) { // Expected status code: 201 Created int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); // Type of service request being tested ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; if(logger.isDebugEnabled()){ logger.debug("Import: Create vocabulary: \"" + vocabName +"\""); } MultipartOutput multipart = createVocabularyInstance(vocabName, "enum"); ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { throw new RuntimeException("Could not create enumeration: \""+vocabName +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); } if(statusCode != EXPECTED_STATUS_CODE) { throw new RuntimeException("Unexpected Status when creating enumeration: \"" +vocabName +"\", Status:"+ statusCode); } // Store the ID returned from this create operation // for additional tests below. String newVocabId = extractId(res); if(logger.isDebugEnabled()){ logger.debug("Import: Created vocabulary: \"" + vocabName +"\" ID:" +newVocabId ); } for(String itemName : enumValues){ createItemInVocab(newVocabId, vocabName, itemName); } } private String createItemInVocab(String vcsid, String vocabName, String itemName) { // Expected status code: 201 Created int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); // Type of service request being tested ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; if(logger.isDebugEnabled()){ logger.debug("Import: Create Item: \""+itemName+"\" in vocabulary: \"" + vocabName +"\""); } MultipartOutput multipart = createVocabularyItemInstance(vcsid, itemName); ClientResponse<Response> res = client.createItem(vcsid, multipart); int statusCode = res.getStatus(); if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { throw new RuntimeException("Could not create Item: \""+itemName +"\" in vocabulary: \"" + vocabName +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); } if(statusCode != EXPECTED_STATUS_CODE) { throw new RuntimeException("Unexpected Status when creating Item: \""+itemName +"\" in vocabulary: \"" + vocabName +"\", Status:"+ statusCode); } return extractId(res); } // --------------------------------------------------------------- // Utility methods used by tests above // --------------------------------------------------------------- private MultipartOutput createVocabularyInstance(String displayName, String vocabType) { VocabulariesCommon vocabulary = new VocabulariesCommon(); vocabulary.setDisplayName(displayName); vocabulary.setVocabType(vocabType); MultipartOutput multipart = new MultipartOutput(); OutputPart commonPart = multipart.addPart(vocabulary, MediaType.APPLICATION_XML_TYPE); commonPart.getHeaders().add("label", client.getCommonPartName()); if(logger.isDebugEnabled()){ logger.debug("to be created, vocabulary common ", vocabulary, VocabulariesCommon.class); } return multipart; } private MultipartOutput createVocabularyItemInstance(String inVocabulary, String displayName) { VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon(); vocabularyItem.setInVocabulary(inVocabulary); vocabularyItem.setDisplayName(displayName); MultipartOutput multipart = new MultipartOutput(); OutputPart commonPart = multipart.addPart(vocabularyItem, MediaType.APPLICATION_XML_TYPE); commonPart.getHeaders().add("label", client.getItemCommonPartName()); if(logger.isDebugEnabled()){ logger.debug("to be created, vocabularyitem common ", vocabularyItem, VocabularyitemsCommon.class); } return multipart; } /** * Returns an error message indicating that the status code returned by a * specific call to a service does not fall within a set of valid status * codes for that service. * * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). * * @param statusCode The invalid status code that was returned in the response, * from submitting that type of request to the service. * * @return An error message. */ protected String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { return "Status code '" + statusCode + "' in response is NOT within the expected set: " + requestType.validStatusCodesAsString(); } protected String extractId(ClientResponse<Response> res) { MultivaluedMap<String, Object> mvm = res.getMetadata(); String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0); if(logger.isDebugEnabled()){ logger.debug("extractId:uri=" + uri); } String[] segments = uri.split("/"); String id = segments[segments.length - 1]; if(logger.isDebugEnabled()){ logger.debug("id=" + id); } return id; } public static void main(String[] args) { BasicConfigurator.configure(); logger.info("VocabularyBaseImport starting..."); VocabularyBaseImport vbi = new VocabularyBaseImport(); final String acquisitionMethodsVocabName = "Acquisition Methods"; final String entryMethodsVocabName = "Entry Methods"; final String entryReasonsVocabName = "Entry Reasons"; final String responsibleDeptsVocabName = "Responsible Departments"; List<String> acquisitionMethodsEnumValues = Arrays.asList("Gift","Purchase","Exchange","Transfer","Treasure"); List<String> entryMethodsEnumValues = Arrays.asList("In person","Post","Found on doorstep"); List<String> entryReasonsEnumValues = Arrays.asList("Enquiry","Commission","Loan"); List<String> respDeptNamesEnumValues = Arrays.asList("Antiquities","Architecture and Design","Decorative Arts", "Ethnography","Herpetology","Media and Performance Art", "Paintings and Sculpture","Paleobotany","Photographs", "Prints and Drawings"); vbi.createEnumeration(acquisitionMethodsVocabName, acquisitionMethodsEnumValues); vbi.createEnumeration(entryMethodsVocabName, entryMethodsEnumValues); vbi.createEnumeration(entryReasonsVocabName, entryReasonsEnumValues); vbi.createEnumeration(responsibleDeptsVocabName, respDeptNamesEnumValues); logger.info("VocabularyBaseImport complete."); } }
services/vocabulary/client/src/main/java/org/collectionspace/services/client/import/VocabularyBaseImport.java
/** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * * http://www.collectionspace.org * http://wiki.collectionspace.org * * Copyright (c)) 2009 Regents of the University of California * * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.collectionspace.services.client.importer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.collectionspace.services.client.VocabularyClient; import org.collectionspace.services.client.test.ServiceRequestType; import org.collectionspace.services.vocabulary.VocabulariesCommon; import org.collectionspace.services.vocabulary.VocabularyitemsCommon; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; import org.jboss.resteasy.plugins.providers.multipart.OutputPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * VocabularyServiceTest, carries out tests against a * deployed and running Vocabulary Service. * * $LastChangedRevision: 753 $ * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $ */ public class VocabularyBaseImport { private final Logger logger = LoggerFactory.getLogger(VocabularyBaseImport.class); // Instance variables specific to this test. private VocabularyClient client = new VocabularyClient(); final String SERVICE_PATH_COMPONENT = "vocabularies"; final String ITEM_SERVICE_PATH_COMPONENT = "items"; public void createEnumeration(String vocabName, List<String> enumValues ) { // Expected status code: 201 Created int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); // Type of service request being tested ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; if(logger.isDebugEnabled()){ logger.debug("Import: Create vocabulary: \"" + vocabName +"\""); } MultipartOutput multipart = createVocabularyInstance(vocabName, "enum"); ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { throw new RuntimeException("Could not create enumeration: \""+vocabName +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); } if(statusCode != EXPECTED_STATUS_CODE) { throw new RuntimeException("Unexpected Status when creating enumeration: \"" +vocabName +"\", Status:"+ statusCode); } // Store the ID returned from this create operation // for additional tests below. String newVocabId = extractId(res); if(logger.isDebugEnabled()){ logger.debug("Import: Created vocabulary: \"" + vocabName +"\" ID:" +newVocabId ); } for(String itemName : enumValues){ createItemInVocab(newVocabId, vocabName, itemName); } } private String createItemInVocab(String vcsid, String vocabName, String itemName) { // Expected status code: 201 Created int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); // Type of service request being tested ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; if(logger.isDebugEnabled()){ logger.debug("Import: Create Item: \""+itemName+"\" in vocabulary: \"" + vocabName +"\""); } MultipartOutput multipart = createVocabularyItemInstance(vcsid, itemName); ClientResponse<Response> res = client.createItem(vcsid, multipart); int statusCode = res.getStatus(); if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { throw new RuntimeException("Could not create Item: \""+itemName +"\" in vocabulary: \"" + vocabName +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); } if(statusCode != EXPECTED_STATUS_CODE) { throw new RuntimeException("Unexpected Status when creating Item: \""+itemName +"\" in vocabulary: \"" + vocabName +"\", Status:"+ statusCode); } return extractId(res); } // --------------------------------------------------------------- // Utility methods used by tests above // --------------------------------------------------------------- private MultipartOutput createVocabularyInstance(String displayName, String vocabType) { VocabulariesCommon vocabulary = new VocabulariesCommon(); vocabulary.setDisplayName(displayName); vocabulary.setVocabType(vocabType); MultipartOutput multipart = new MultipartOutput(); OutputPart commonPart = multipart.addPart(vocabulary, MediaType.APPLICATION_XML_TYPE); commonPart.getHeaders().add("label", client.getCommonPartName()); if(logger.isDebugEnabled()){ logger.debug("to be created, vocabulary common ", vocabulary, VocabulariesCommon.class); } return multipart; } private MultipartOutput createVocabularyItemInstance(String inVocabulary, String displayName) { VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon(); vocabularyItem.setInVocabulary(inVocabulary); vocabularyItem.setDisplayName(displayName); MultipartOutput multipart = new MultipartOutput(); OutputPart commonPart = multipart.addPart(vocabularyItem, MediaType.APPLICATION_XML_TYPE); commonPart.getHeaders().add("label", client.getItemCommonPartName()); if(logger.isDebugEnabled()){ logger.debug("to be created, vocabularyitem common ", vocabularyItem, VocabularyitemsCommon.class); } return multipart; } /** * Returns an error message indicating that the status code returned by a * specific call to a service does not fall within a set of valid status * codes for that service. * * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). * * @param statusCode The invalid status code that was returned in the response, * from submitting that type of request to the service. * * @return An error message. */ protected String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { return "Status code '" + statusCode + "' in response is NOT within the expected set: " + requestType.validStatusCodesAsString(); } protected String extractId(ClientResponse<Response> res) { MultivaluedMap<String, Object> mvm = res.getMetadata(); String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0); if(logger.isDebugEnabled()){ logger.debug("extractId:uri=" + uri); } String[] segments = uri.split("/"); String id = segments[segments.length - 1]; if(logger.isDebugEnabled()){ logger.debug("id=" + id); } return id; } public static void main(String[] args) { VocabularyBaseImport vbi = new VocabularyBaseImport(); final String acquisitionMethodsVocabName = "Acquisition Methods"; final String entryMethodsVocabName = "Entry Methods"; final String entryReasonsVocabName = "Entry Reasons"; final String responsibleDeptsVocabName = "Responsible Departments"; List<String> acquisitionMethodsEnumValues = Arrays.asList("Gift","Purchase","Exchange","Transfer","Treasure"); List<String> entryMethodsEnumValues = Arrays.asList("In person","Post","Found on doorstep"); List<String> entryReasonsEnumValues = Arrays.asList("Enquiry","Commission","Loan"); List<String> respDeptNamesEnumValues = Arrays.asList("Antiquities","Architecture and Design","Decorative Arts", "Ethnography","Herpetology","Media and Performance Art", "Paintings and Sculpture","Paleobotany","Photographs", "Prints and Drawings"); vbi.createEnumeration(acquisitionMethodsVocabName, acquisitionMethodsEnumValues); vbi.createEnumeration(entryMethodsVocabName, entryMethodsEnumValues); vbi.createEnumeration(entryReasonsVocabName, entryReasonsEnumValues); vbi.createEnumeration(responsibleDeptsVocabName, respDeptNamesEnumValues); } }
NOJIRA - Fixed logging init in main().
services/vocabulary/client/src/main/java/org/collectionspace/services/client/import/VocabularyBaseImport.java
NOJIRA - Fixed logging init in main().
<ide><path>ervices/vocabulary/client/src/main/java/org/collectionspace/services/client/import/VocabularyBaseImport.java <ide> import javax.ws.rs.core.MultivaluedMap; <ide> import javax.ws.rs.core.Response; <ide> <add>import org.apache.log4j.BasicConfigurator; <ide> import org.collectionspace.services.client.VocabularyClient; <ide> import org.collectionspace.services.client.test.ServiceRequestType; <ide> import org.collectionspace.services.vocabulary.VocabulariesCommon; <ide> * $LastChangedDate: 2009-09-23 11:03:36 -0700 (Wed, 23 Sep 2009) $ <ide> */ <ide> public class VocabularyBaseImport { <del> private final Logger logger = <add> private static final Logger logger = <ide> LoggerFactory.getLogger(VocabularyBaseImport.class); <ide> <ide> // Instance variables specific to this test. <ide> } <ide> <ide> public static void main(String[] args) { <del> VocabularyBaseImport vbi = new VocabularyBaseImport(); <del> final String acquisitionMethodsVocabName = "Acquisition Methods"; <del> final String entryMethodsVocabName = "Entry Methods"; <del> final String entryReasonsVocabName = "Entry Reasons"; <del> final String responsibleDeptsVocabName = "Responsible Departments"; <del> <del> List<String> acquisitionMethodsEnumValues = <del> Arrays.asList("Gift","Purchase","Exchange","Transfer","Treasure"); <del> List<String> entryMethodsEnumValues = <del> Arrays.asList("In person","Post","Found on doorstep"); <del> List<String> entryReasonsEnumValues = <del> Arrays.asList("Enquiry","Commission","Loan"); <del> List<String> respDeptNamesEnumValues = <del> Arrays.asList("Antiquities","Architecture and Design","Decorative Arts", <del> "Ethnography","Herpetology","Media and Performance Art", <del> "Paintings and Sculpture","Paleobotany","Photographs", <del> "Prints and Drawings"); <del> <del> vbi.createEnumeration(acquisitionMethodsVocabName, acquisitionMethodsEnumValues); <del> vbi.createEnumeration(entryMethodsVocabName, entryMethodsEnumValues); <del> vbi.createEnumeration(entryReasonsVocabName, entryReasonsEnumValues); <del> vbi.createEnumeration(responsibleDeptsVocabName, respDeptNamesEnumValues); <del> } <add> <add> BasicConfigurator.configure(); <add> logger.info("VocabularyBaseImport starting..."); <add> <add> VocabularyBaseImport vbi = new VocabularyBaseImport(); <add> final String acquisitionMethodsVocabName = "Acquisition Methods"; <add> final String entryMethodsVocabName = "Entry Methods"; <add> final String entryReasonsVocabName = "Entry Reasons"; <add> final String responsibleDeptsVocabName = "Responsible Departments"; <add> <add> List<String> acquisitionMethodsEnumValues = <add> Arrays.asList("Gift","Purchase","Exchange","Transfer","Treasure"); <add> List<String> entryMethodsEnumValues = <add> Arrays.asList("In person","Post","Found on doorstep"); <add> List<String> entryReasonsEnumValues = <add> Arrays.asList("Enquiry","Commission","Loan"); <add> List<String> respDeptNamesEnumValues = <add> Arrays.asList("Antiquities","Architecture and Design","Decorative Arts", <add> "Ethnography","Herpetology","Media and Performance Art", <add> "Paintings and Sculpture","Paleobotany","Photographs", <add> "Prints and Drawings"); <add> <add> vbi.createEnumeration(acquisitionMethodsVocabName, acquisitionMethodsEnumValues); <add> vbi.createEnumeration(entryMethodsVocabName, entryMethodsEnumValues); <add> vbi.createEnumeration(entryReasonsVocabName, entryReasonsEnumValues); <add> vbi.createEnumeration(responsibleDeptsVocabName, respDeptNamesEnumValues); <add> <add> logger.info("VocabularyBaseImport complete."); <add> } <ide> }
JavaScript
agpl-3.0
d591d2000ace1127246bee953b3604ae1d0c5b0d
0
fabian247/wifi-watcher,fabian247/wifi-watcher,fabian247/wifi-watcher
const dns = require('dns') const localIP = '192.168.178.0' // TODO: make local IP a variable or in config file function getRoutesFromPacketArray (packetArray) { var routesArray = [] for (var packet in packetArray) { try { routesArray.push(getRouteFromPacket(packet)) } catch (exception) { console.log(exception) } } } function getRouteFromPacket (packet) { switch (packet.payload.ethertype) { case 0x800: // console.log('Ipv4') return handleIPv4Packet(packet.payload.payload) case 0x86dd: // console.log('Ipv6') return handleIPv6Packet(packet.payload.payload) default: throw new Error('Don\'t know how to handle this packet of ethertype ' + packet.payload.ethertype) } } // TODO: check if packet is valid, check if IPs are valid function handleIPv4Packet (packet) { var route = { senderIP: packet.saddr.toString(), receiverIP: packet.daddr.toString() } // console.log('IPv4: ', result) return route } // TODO: same as IPv4 function handleIPv6Packet (packet) { console.log('Ipv6 in function') return 'IPv6 Packet' } // TODO: check if IP valid, return ipAddress if dns.reverse fails function reverseLookupOfIP (ipAddress) { // console.log(ipAddress) return new Promise((resolve, reject) => { dns.reverse(ipAddress, (err, domains) => { if (err) { reject(err) } // console.log('reverse for ' + ipAddress + ': ' + domains) resolve(domains) }) }) } // TODO: check if IPs valid function getLocalAddress (sender, receiver) { if (getNetworkPartOfIP(sender) === getNetworkPartOfIP(localIP)) { return {local: sender, receiver} } else { // if sender is not local, then receiver must be local return {local: receiver, receiver: sender} } } // TODO: check if IP valid function getNetworkPartOfIP (ipAddress) { return ipAddress.substring(0, ipAddress.lastIndexOf('.')) } module.exports = { reverseLookupOfIP, getRoutesFromPacketArray, getRouteFromPacket, getLocalAddress }
lib/expose_websites.js
const dns = require('dns') const localIP = '192.168.178.0' // TODO: make local IP a variable or in config file function getRoutesFromPacketArray (packetArray) { var routesArray = [] for (var packet in packetArray) { try { routesArray.push(getRouteFromPacket(packet)) } catch (exception) { console.log(exception) } } } function getRouteFromPacket (packet) { switch (packet.payload.ethertype) { case 0x800: // console.log('Ipv4') // use module.exports.function for testability return module.exports.handleIPv4Packet(packet.payload.payload) case 0x86dd: // console.log('Ipv6') return module.exports.handleIPv6Packet(packet.payload.payload) default: throw new Error('Don\'t know how to handle this packet of ethertype ' + packet.payload.ethertype) } } // TODO: check if packet is valid, check if IPs are valid function handleIPv4Packet (packet) { var route = { senderIP: packet.saddr.toString(), receiverIP: packet.daddr.toString() } // console.log('IPv4: ', result) return route } // TODO: same as IPv4 function handleIPv6Packet (packet) { console.log('Ipv6 in function') return 'IPv6 Packet' } // TODO: check if IP valid, return ipAddress if dns.reverse fails function reverseLookupOfIP (ipAddress) { // console.log(ipAddress) return new Promise((resolve, reject) => { dns.reverse(ipAddress, (err, domains) => { if (err) { reject(err) } // console.log('reverse for ' + ipAddress + ': ' + domains) resolve(domains) }) }) } // TODO: check if IPs valid function getLocalAddress (sender, receiver) { if (getNetworkPartOfIP(sender) === getNetworkPartOfIP(localIP)) { return {local: sender, receiver} } else { // if sender is not local, then receiver must be local return {local: receiver, receiver: sender} } } // TODO: check if IP valid function getNetworkPartOfIP (ipAddress) { return ipAddress.substring(0, ipAddress.lastIndexOf('.')) } module.exports = { reverseLookupOfIP, handleIPv4Packet, handleIPv6Packet, getRoutesFromPacketArray, getRouteFromPacket, getLocalAddress }
Remove surplus exports
lib/expose_websites.js
Remove surplus exports
<ide><path>ib/expose_websites.js <ide> switch (packet.payload.ethertype) { <ide> case 0x800: <ide> // console.log('Ipv4') <del> // use module.exports.function for testability <del> return module.exports.handleIPv4Packet(packet.payload.payload) <add> return handleIPv4Packet(packet.payload.payload) <ide> case 0x86dd: <ide> // console.log('Ipv6') <del> return module.exports.handleIPv6Packet(packet.payload.payload) <add> return handleIPv6Packet(packet.payload.payload) <ide> default: <ide> throw new Error('Don\'t know how to handle this packet of ethertype ' + packet.payload.ethertype) <ide> } <ide> <ide> module.exports = { <ide> reverseLookupOfIP, <del> handleIPv4Packet, <del> handleIPv6Packet, <ide> getRoutesFromPacketArray, <ide> getRouteFromPacket, <ide> getLocalAddress
JavaScript
apache-2.0
e980a45955ad8e470da422d4c71f50489a5abe41
0
Brightspace/valence-ui-typography,BrightspaceUI/typography,Brightspace/valence-ui-typography
/* eslint no-invalid-this: 0 */ 'use strict'; var browsers = { phantomjs: new LocalBrowserFactory({ browser: 'phantomjs' }), chromeWindows: new SauceBrowserFactory({ browser: 'Chrome', platform: 'WIN10' }), firefoxWindows: new SauceBrowserFactory({ browser: 'Firefox', platform: 'WIN10' }), ie11Windows: new SauceBrowserFactory({ browser: 'internet explorer', version: '11', platform: 'WIN10' }), edgeWindows: new SauceBrowserFactory({ browser: 'microsoftedge', platform: 'WIN10' }), chromeMac: new SauceBrowserFactory({ browser: 'Chrome', platform: 'EL_CAPITAN' }), safariMac: new SauceBrowserFactory({ browser: 'Safari', platform: 'EL_CAPITAN' }), firefoxMac: new SauceBrowserFactory({ browser: 'Firefox', platform: 'EL_CAPITAN' }) }; var mobileBrowsers = { chromeNexus5: new ChromeBrowserFactory({ tags: ['mobile'], desiredCapabilities: { chromeOptions: { mobileEmulation: { deviceName: 'Google Nexus 5' } } } }) }; var endpoint = 'http://localhost:8080/components/d2l-typography/test/perceptual/typography.html'; var spec = 'test/font-classes.gspec'; polymerTests(browsers, function(test) { test('typography-mobile', { endpoint: endpoint, spec: spec, size: '320x600', tags: ['mobile'] }); test('typography-desktop', { endpoint: endpoint, spec: spec, size: '1024x768', tags: ['desktop'] }); }); polymerTests(mobileBrowsers, function(test) { test('typography', { endpoint: endpoint, spec: spec }); });
typography.test.js
/* eslint no-invalid-this: 0 */ 'use strict'; var browsers = { phantomjs: new LocalBrowserFactory({ browser: 'phantomjs' }), chromeWindows: new SauceBrowserFactory({ browser: 'Chrome', platform: 'WIN10' }), firefoxWindows: new SauceBrowserFactory({ browser: 'Firefox', platform: 'WIN10' }), ie11Windows: new SauceBrowserFactory({ browser: 'internet explorer', version: '11', platform: 'WIN10' }), ie10Windows: new SauceBrowserFactory({ browser: 'internet explorer', version: '10', platform: 'WIN8' }), edgeWindows: new SauceBrowserFactory({ browser: 'microsoftedge', platform: 'WIN10' }), chromeMac: new SauceBrowserFactory({ browser: 'Chrome', platform: 'EL_CAPITAN' }), safariMac: new SauceBrowserFactory({ browser: 'Safari', platform: 'EL_CAPITAN' }), firefoxMac: new SauceBrowserFactory({ browser: 'Firefox', platform: 'EL_CAPITAN' }) }; var mobileBrowsers = { chromeNexus5: new ChromeBrowserFactory({ tags: ['mobile'], desiredCapabilities: { chromeOptions: { mobileEmulation: { deviceName: 'Google Nexus 5' } } } }) }; var endpoint = 'http://localhost:8080/components/d2l-typography/test/perceptual/typography.html'; var spec = 'test/font-classes.gspec'; polymerTests(browsers, function(test) { test('typography-mobile', { endpoint: endpoint, spec: spec, size: '320x600', tags: ['mobile'] }); test('typography-desktop', { endpoint: endpoint, spec: spec, size: '1024x768', tags: ['desktop'] }); }); polymerTests(mobileBrowsers, function(test) { test('typography', { endpoint: endpoint, spec: spec }); });
removing IE10 from Sauce tests
typography.test.js
removing IE10 from Sauce tests
<ide><path>ypography.test.js <ide> browser: 'internet explorer', <ide> version: '11', <ide> platform: 'WIN10' <del> }), <del> ie10Windows: new SauceBrowserFactory({ <del> browser: 'internet explorer', <del> version: '10', <del> platform: 'WIN8' <ide> }), <ide> edgeWindows: new SauceBrowserFactory({ <ide> browser: 'microsoftedge',
Java
bsd-2-clause
b81d127198edd1c279575731dd225c8560b61799
0
clementval/claw-compiler,clementval/claw-compiler
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.translator.transformation.claw.parallelize; import cx2x.translator.ClawTranslator; import cx2x.translator.common.Utility; import cx2x.translator.language.base.ClawLanguage; import cx2x.translator.language.helper.TransformationHelper; import cx2x.translator.language.helper.accelerator.AcceleratorDirective; import cx2x.translator.language.helper.accelerator.AcceleratorHelper; import cx2x.translator.language.helper.target.Target; import cx2x.translator.transformation.ClawTransformation; import cx2x.translator.xnode.ClawAttr; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.helper.NestedDoStatement; import cx2x.xcodeml.helper.XnodeUtil; import cx2x.xcodeml.language.DimensionDefinition; import cx2x.xcodeml.transformation.Transformation; import cx2x.xcodeml.transformation.Translator; import cx2x.xcodeml.xnode.*; import xcodeml.util.XmOption; import java.util.*; /** * The parallelize transformation transforms the code contained in a * subroutine/function by adding necessary dimensions and parallelism to the * defined data. * <p> * Transformation for the GPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Do statements over the additional dimensions is added as an outer * loop and wrap the entire body of the subroutine. * </ul> * <p> * Transformation for the CPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Propagated promotion is applied to all scalars or arrays used in an * assign statement at the lhs and where a promoted variable is used on the * rhs. * <li> Do statements over the additional dimensions are added as an inner * loop wrapping each assign statements including promoted variables. * </ul> * <p> * Generation of OpenACC directives:<ul> * <li> acc routine seq is generated for subroutine called from the parallelized * subroutine if they are located in the same translation unit. * <li> acc data region with corresponding present clause for all promoted * variables with the intent in, out or inout. * <li> acc parallel region is generated to wrap all the body of the subroutine. * <li> acc private clause is added to the parallel directive for all local * variables. * <li> acc loop is generated for the generated do statement. * <li> acc loop seq is generated for already existing do statements. * </ul> * <p> * Generation of OpenMP directives: <ul> * <li> omp parallel do is generated for each generated do statements. * </ul> * * @author clementval */ public class Parallelize extends ClawTransformation { private static final int DEFAULT_OVER = 0; private final Map<String, DimensionDefinition> _dimensions; private final Map<String, PromotionInfo> _promotions; private final List<String> _arrayFieldsInOut; private final List<String> _scalarFields; private int _overDimensions; private XfunctionDefinition _fctDef; private XfunctionType _fctType; private List<List<Xnode>> _beforeCrt, _inMiddle, _afterCrt; /** * Constructs a new Parallelize transformation triggered from a specific * pragma. * * @param directive The directive that triggered the define transformation. */ public Parallelize(ClawLanguage directive) { super(directive); _overDimensions = 0; _dimensions = new HashMap<>(); _promotions = new HashMap<>(); _arrayFieldsInOut = new ArrayList<>(); _scalarFields = new ArrayList<>(); } /** * Print information about promoted arrays, candidate for promotion arrays and * scalars. * * @param name Name of the subroutine. * @param promoted List of promoted array variables. * @param candidateArrays List of candidate array variables for promotion. * @param scalars List of candidate scalar variables for promotion. */ private void printDebugPromotionInfos(String name, List<String> promoted, List<String> candidateArrays, List<String> scalars) { if(XmOption.isDebugOutput()) { System.out.println("=========================================="); System.out.println("Parallelize promotion infos for subroutine " + name); System.out.println(" - Promoted arrays(" + promoted.size() + "):"); for(String array : promoted) { System.out.println(" " + array); } System.out.println(" - Candidate arrays(" + candidateArrays.size() + "):"); for(String array : candidateArrays) { System.out.println(" " + array); } System.out.println(" - Candidate scalars(" + scalars.size() + "):"); for(String array : scalars) { System.out.println(" " + array); } System.out.println("=========================================="); } } @Override public boolean analyze(XcodeProgram xcodeml, Translator translator) { // Check for the parent fct/subroutine definition _fctDef = XnodeUtil.findParentFunction(_claw.getPragma()); if(_fctDef == null) { xcodeml.addError("Parent function/subroutine cannot be found. " + "Parallelize directive must be defined in a function/subroutine.", _claw.getPragma().lineNo()); return false; } _fctType = (XfunctionType) xcodeml.getTypeTable(). get(_fctDef.getName().getAttribute(Xattr.TYPE)); if(_fctType == null) { xcodeml.addError("Function/subroutine signature cannot be found. ", _claw.getPragma().lineNo()); return false; } // Check if unsupported statements are located in the future parallel // region. if(_claw.getTarget() == Target.GPU && _claw.getDirectiveLanguage() == AcceleratorDirective.OPENACC) { Xnode contains = _fctDef.body().matchSeq(Xcode.FCONTAINSSTATEMENT); Xnode parallelRegionStart = AcceleratorHelper.findParallelRegionStart( _claw.getAcceleratorGenerator(), _fctDef, null); Xnode parallelRegionEnd = AcceleratorHelper.findParallelRegionEnd( _claw.getAcceleratorGenerator(), _fctDef, contains); List<Xnode> unsupportedStatements = XnodeUtil.getStatements(parallelRegionStart, parallelRegionEnd, _claw.getAcceleratorGenerator().getUnsupportedStatements()); if(unsupportedStatements.size() > 0) { for(Xnode statement : unsupportedStatements) { xcodeml.addError("Unsupported statement in parallel region", statement.lineNo()); } return false; } } return analyzeDimension(xcodeml) && analyzeData(xcodeml) && analyzeOver(xcodeml); } /** * Analyse the defined dimension. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeDimension(XcodeProgram xcodeml) { if(!_claw.hasDimensionClause()) { xcodeml.addError("No dimension defined for parallelization.", _claw.getPragma().lineNo()); return false; } for(DimensionDefinition d : _claw.getDimensionValues()) { if(_dimensions.containsKey(d.getIdentifier())) { xcodeml.addError( String.format("Dimension with identifier %s already specified.", d.getIdentifier()), _claw.getPragma().lineNo() ); return false; } _dimensions.put(d.getIdentifier(), d); } return true; } /** * Analyse the information defined in the data clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeData(XcodeProgram xcodeml) { /* If there is no data/over clause specified, an automatic deduction for * array promotion is performed. */ if(!_claw.hasOverDataClause()) { List<String> scalars = new ArrayList<>(); List<String> candidateArrays = new ArrayList<>(); List<Xdecl> declarations = _fctDef.getDeclarationTable().values(); for(Xdecl decl : declarations) { if(decl.opcode() != Xcode.VARDECL) { continue; } Xtype type = xcodeml.getTypeTable(). get(decl.matchSeq(Xcode.NAME).getAttribute(Xattr.TYPE)); if(type instanceof XbasicType) { String varName = decl.matchSeq(Xcode.NAME).value(); XbasicType bType = (XbasicType) type; if(bType.isArray()) { if(bType.hasIntent() || bType.isPointer()) { _arrayFieldsInOut.add(varName); } else { candidateArrays.add(varName); } } else { if(_claw.hasScalarClause() && _claw.getScalarClauseValues().contains(varName)) { _arrayFieldsInOut.add(varName); } if(!bType.isParameter() && bType.hasIntent()) { scalars.add(varName); } } } } _scalarFields.addAll(scalars); _scalarFields.addAll(candidateArrays); printDebugPromotionInfos(_fctDef.getName().value(), _arrayFieldsInOut, candidateArrays, scalars); return true; } /* If the data clause if defined at least once, manual promotion is the * rule. The array identifiers defined in the data clauses will be used as * the list of array to be promoted. * In the analysis, we control that all defined arrays in the data clauses * are actual declared variables. */ for(List<String> data : _claw.getOverDataClauseValues()) { for(String d : data) { if(!_fctDef.getSymbolTable().contains(d)) { xcodeml.addError( String.format("Data %s is not defined in the current block.", d), _claw.getPragma().lineNo() ); return false; } if(!_fctDef.getDeclarationTable().contains(d)) { xcodeml.addError( String.format("Data %s is not declared in the current block.", d), _claw.getPragma().lineNo() ); return false; } } _arrayFieldsInOut.addAll(data); } return true; } /** * Analyse the information defined in the over clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeOver(XcodeProgram xcodeml) { if(!_claw.hasOverClause()) { _overDimensions += _claw.getDimensionValues().size(); return true; } for(List<String> over : _claw.getOverClauseValues()) { if(!over.contains(DimensionDefinition.BASE_DIM)) { xcodeml.addError("The column dimension has not been specified in the " + "over clause. Use : to specify it.", _claw.getPragma().lineNo()); return false; } int baseDimNb = TransformationHelper.baseDimensionNb(over); if(baseDimNb > 2) { xcodeml.addError("Too many base dimensions specified in over clause. " + "Maximum two base dimensions can be specified.", _claw.getPragma().lineNo()); return false; } else if(baseDimNb == 2) { if(!over.get(0).equals(DimensionDefinition.BASE_DIM) || !over.get(over.size() - 1).equals(DimensionDefinition.BASE_DIM)) { xcodeml.addError("Base dimensions structure not supported in over" + "clause.", _claw.getPragma().lineNo()); return false; } } } // Check if over dimensions are defined dimensions _overDimensions = _claw.getDimensionValues().size(); for(List<String> overLst : _claw.getOverClauseValues()) { int usedDimension = 0; for(String o : overLst) { if(!o.equals(DimensionDefinition.BASE_DIM)) { if(!_dimensions.containsKey(o)) { xcodeml.addError( String.format( "Dimension %s is not defined. Cannot be used in over " + "clause", o), _claw.getPragma().lineNo() ); return false; } ++usedDimension; } } if(usedDimension != _overDimensions) { xcodeml.addError("Over clause doesn't use one or more defined " + "dimensions", _claw.getPragma().lineNo()); return false; } } return true; } @Override public void transform(XcodeProgram xcodeml, Translator translator, Transformation other) throws Exception { // Handle PURE function / subroutine ClawTranslator trans = (ClawTranslator) translator; boolean pureRemoved = XnodeUtil.removePure(_fctDef, _fctType); if(trans.getConfiguration().isForcePure() && pureRemoved) { throw new IllegalTransformationException( "PURE specifier cannot be removed", _fctDef.lineNo()); } else if(pureRemoved) { String fctName = _fctDef.matchDirectDescendant(Xcode.NAME).value(); System.out.println("Warning: PURE specifier removed from function " + fctName + " at line " + _fctDef.lineNo() + ". Transformation and " + "code generation applied to it."); } // Prepare the array index that will be added to the array references. prepareArrayIndexes(xcodeml); // Insert the declarations of variables to iterate over the new dimensions. insertVariableToIterateOverDimension(xcodeml); // Promote all array fields with new dimensions. promoteFields(xcodeml); // Adapt array references. if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { TransformationHelper.adaptArrayReferences( _claw.getOverDataClauseValues().get(i), i, _fctDef.body(), _promotions, _beforeCrt, _inMiddle, _afterCrt, xcodeml); } } else { TransformationHelper.adaptArrayReferences(_arrayFieldsInOut, DEFAULT_OVER, _fctDef.body(), _promotions, _beforeCrt, _inMiddle, _afterCrt, xcodeml); } // Delete the pragma _claw.getPragma().delete(); // Apply specific target transformation if(_claw.getTarget() == Target.GPU) { transformForGPU(xcodeml); } else if(_claw.getTarget() == Target.CPU) { transformForCPU(xcodeml); } if(!_fctType.getBooleanAttribute(Xattr.IS_PRIVATE)) { XmoduleDefinition modDef = _fctDef.findParentModule(); if(modDef != null) { TransformationHelper.updateModuleSignature(xcodeml, _fctDef, _fctType, modDef, _claw, translator, false); } } } /** * Apply GPU based transformation. * * @param xcodeml Current XcodeML program unit. */ private void transformForGPU(XcodeProgram xcodeml) { AcceleratorHelper.generateLoopSeq(_claw, xcodeml, _fctDef); /* Create a nested loop with the new defined dimensions and wrap it around * the whole subroutine's body. This is for the moment a really naive * transformation idea but it is our start point. * Use the first over clause to create it. */ NestedDoStatement loops = new NestedDoStatement(getOrderedDimensionsFromDefinition(0), xcodeml); /* Subroutine/function can have a contains section with inner subroutines or * functions. The newly created (nested) do statements should stop before * this contains section if it exists. */ Xnode contains = _fctDef.body().matchSeq(Xcode.FCONTAINSSTATEMENT); if(contains != null) { Xnode parallelRegionStart = AcceleratorHelper.findParallelRegionStart( _claw.getAcceleratorGenerator(), _fctDef, null); Xnode parallelRegionEnd = AcceleratorHelper.findParallelRegionEnd( _claw.getAcceleratorGenerator(), _fctDef, contains); XnodeUtil.shiftStatementsInBody(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); contains.insertBefore(loops.getOuterStatement()); } else { // No contains section, all the body is copied to the do statements. Xnode parallelRegionStart = AcceleratorHelper.findParallelRegionStart( _claw.getAcceleratorGenerator(), _fctDef, null); Xnode parallelRegionEnd = AcceleratorHelper.findParallelRegionEnd( _claw.getAcceleratorGenerator(), _fctDef, null); // Define a hook from where we can insert the new do statement Xnode hook = parallelRegionEnd.nextSibling(); XnodeUtil.shiftStatementsInBody(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); // Hook is null then we append the do statement to the current fct body if(hook == null) { _fctDef.body().append(loops.getOuterStatement(), false); } else { // Insert new do statement before the hook element hook.insertBefore(loops.getOuterStatement()); } } // Generate the data region List<String> presents = AcceleratorHelper.getPresentVariables(xcodeml, _fctDef); AcceleratorHelper.generateDataRegionClause(_claw, xcodeml, presents, loops.getOuterStatement(), loops.getOuterStatement()); // Generate the parallel region List<String> privates = AcceleratorHelper.getLocalArrays(xcodeml, _fctDef); AcceleratorHelper.generateParallelLoopClause(_claw, xcodeml, privates, loops.getOuterStatement(), loops.getOuterStatement(), loops.getGroupSize()); AcceleratorHelper.generateRoutineDirectives(_claw, xcodeml, _fctDef); } /** * Apply CPU based transformations. * * @param xcodeml Current XcodeML program unit. * @throws IllegalTransformationException If promotion of arrays fails. */ private void transformForCPU(XcodeProgram xcodeml) throws IllegalTransformationException { /* Create a group of nested loop with the newly defined dimension and wrap * every assignment statement in the column loop or including data with it. * This is for the moment a really naive transformation idea but it is our * start point. * Use the first over clause to do it. */ List<DimensionDefinition> order = getOrderedDimensionsFromDefinition(0); List<Xnode> assignStatements = _fctDef.body().matchAll(Xcode.FASSIGNSTATEMENT); for(Xnode assign : assignStatements) { Xnode lhs = assign.child(Xnode.LHS); String lhsName = (lhs.opcode() == Xcode.VAR) ? lhs.value() : lhs.matchSeq(Xcode.VARREF, Xcode.VAR).value(); NestedDoStatement loops = null; if(lhs.opcode() == Xcode.FARRAYREF && _arrayFieldsInOut.contains(lhsName)) { loops = new NestedDoStatement(order, xcodeml); assign.insertAfter(loops.getOuterStatement()); loops.getInnerStatement().body().append(assign, true); assign.delete(); } else if(lhs.opcode() == Xcode.VAR || lhs.opcode() == Xcode.FARRAYREF && _scalarFields.contains(lhsName)) { /* If the assignment is in the column loop and is composed with some * promoted variables, the field must be promoted and the var reference * switch to an array reference */ if(shouldBePromoted(assign)) { if(!_arrayFieldsInOut.contains(lhsName)) { _arrayFieldsInOut.add(lhsName); PromotionInfo promotionInfo; if(lhs.opcode() == Xcode.VAR) { // Scalar to array promotionInfo = TransformationHelper.promoteField(lhsName, false, false, DEFAULT_OVER, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); } else { // Array to array promotionInfo = TransformationHelper.promoteField(lhsName, true, true, DEFAULT_OVER, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); } _promotions.put(lhsName, promotionInfo); } if(lhs.opcode() == Xcode.VAR) { adaptScalarRefToArrayReferences(xcodeml, Collections.singletonList(lhsName), DEFAULT_OVER); } else { TransformationHelper.adaptArrayReferences( Collections.singletonList(lhsName), DEFAULT_OVER, _fctDef.body(), _promotions, _beforeCrt, _inMiddle, _afterCrt, xcodeml); } loops = new NestedDoStatement(order, xcodeml); assign.insertAfter(loops.getOuterStatement()); loops.getInnerStatement().body().append(assign, true); assign.delete(); } } if(loops != null) { // Generate the corresponding directive around the loop AcceleratorHelper.generateLoopDirectives(_claw, xcodeml, loops.getOuterStatement(), loops.getOuterStatement(), AcceleratorHelper.NO_COLLAPSE); } } // Generate the parallel region AcceleratorHelper.generateParallelClause(_claw, xcodeml, _fctDef.body().firstChild(), _fctDef.body().lastChild()); } /** * Check whether the LHS variable should be promoted. * * @param assignStmt Assign statement node. * @return True if the LHS variable should be promoted. False otherwise. */ private boolean shouldBePromoted(Xnode assignStmt) { Xnode rhs = assignStmt.child(Xnode.RHS); if(rhs == null) { return false; } List<Xnode> vars = XnodeUtil.findAllReferences(rhs); Set<String> names = XnodeUtil.getNamesFromReferences(vars); return Utility.hasIntersection(names, _arrayFieldsInOut); } /** * Prepare the arrayIndex elements that will be inserted before and after the * current indexes in the array references. * * @param xcodeml Current XcodeML program unit in which new elements are * created. */ private void prepareArrayIndexes(XcodeProgram xcodeml) { _beforeCrt = new ArrayList<>(); _afterCrt = new ArrayList<>(); _inMiddle = new ArrayList<>(); if(_claw.hasOverClause()) { /* If the over clause is specified, the indexes respect the definition of * the over clause. Indexes before the "colon" symbol will be inserted * before the current indexes and the remaining indexes will be inserted * after the current indexes. */ for(List<String> over : _claw.getOverClauseValues()) { List<Xnode> beforeCrt = new ArrayList<>(); List<Xnode> afterCrt = new ArrayList<>(); List<Xnode> inMiddle = new ArrayList<>(); List<Xnode> crt = beforeCrt; // In middle insertion if(TransformationHelper.baseDimensionNb(over) == 2) { for(String dim : over) { if(!dim.equals(DimensionDefinition.BASE_DIM)) { DimensionDefinition d = _dimensions.get(dim); inMiddle.add(d.generateArrayIndex(xcodeml)); } } } else { for(String dim : over) { if(dim.equals(DimensionDefinition.BASE_DIM)) { crt = afterCrt; } else { DimensionDefinition d = _dimensions.get(dim); crt.add(d.generateArrayIndex(xcodeml)); } } } Collections.reverse(beforeCrt); _beforeCrt.add(beforeCrt); _afterCrt.add(afterCrt); _inMiddle.add(inMiddle); } } else { /* If no over clause, the indexes are inserted in order from the first * defined dimensions from left to right. Everything is inserted on the * left of current indexes. */ List<Xnode> crt = new ArrayList<>(); List<Xnode> empty = Collections.emptyList(); for(DimensionDefinition dim : _claw.getDimensionValues()) { crt.add(dim.generateArrayIndex(xcodeml)); } Collections.reverse(crt); _beforeCrt.add(crt); _afterCrt.add(empty); _inMiddle.add(empty); } } /** * Promote all fields declared in the data clause with the additional * dimensions. * * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void promoteFields(XcodeProgram xcodeml) throws IllegalTransformationException { if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { for(String fieldId : _claw.getOverDataClauseValues().get(i)) { PromotionInfo promotionInfo = TransformationHelper.promoteField(fieldId, true, true, i, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); _promotions.put(fieldId, promotionInfo); } } } else { // Promote all arrays in a similar manner for(String fieldId : _arrayFieldsInOut) { PromotionInfo promotionInfo = TransformationHelper.promoteField(fieldId, true, true, DEFAULT_OVER, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); _promotions.put(fieldId, promotionInfo); } } } /** * Adapt all the array references of the variable in the data clause in the * current function/subroutine definition. * * @param xcodeml Current XcodeML program unit in which the element will be * created. * @param ids List of array identifiers that must be adapted. * @param index Index designing the correct over clause to be used. */ private void adaptScalarRefToArrayReferences(XcodeProgram xcodeml, List<String> ids, int index) { for(String id : ids) { List<Xnode> vars = XnodeUtil.findAllReferences(_fctDef.body(), id); Xid sId = _fctDef.getSymbolTable().get(id); XbasicType type = (XbasicType) xcodeml.getTypeTable().get(sId.getType()); for(Xnode var : vars) { Xnode ref = xcodeml.createArrayRef(type, var.cloneNode()); for(Xnode ai : _beforeCrt.get(index)) { ref.matchSeq(Xcode.VARREF).insertAfter(ai.cloneNode()); } for(Xnode ai : _afterCrt.get(index)) { ref.append(ai, true); } var.insertAfter(ref); var.delete(); } } } /** * Insert the declaration of the different variables needed to iterate over * the additional dimensions. * * @param xcodeml Current XcodeML program unit in which element are * created. */ private void insertVariableToIterateOverDimension(XcodeProgram xcodeml) { // Create type and declaration for iterations over the new dimensions XbasicType intTypeIntentIn = xcodeml.createBasicType( xcodeml.getTypeTable().generateIntegerTypeHash(), Xname.TYPE_F_INT, Xintent.IN); xcodeml.getTypeTable().add(intTypeIntentIn); // For each dimension defined in the directive for(DimensionDefinition dimension : _claw.getDimensionValues()) { // Create the parameter for the lower bound if(dimension.lowerBoundIsVar()) { xcodeml.createIdAndDecl(dimension.getLowerBoundId(), intTypeIntentIn.getType(), Xname.SCLASS_F_PARAM, _fctDef, true); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam(dimension.getLowerBoundId(), intTypeIntentIn.getType(), _fctType); param.setAttribute(ClawAttr.IS_CLAW.toString(), Xname.TRUE); } // Create parameter for the upper bound if(dimension.upperBoundIsVar()) { xcodeml.createIdAndDecl(dimension.getUpperBoundId(), intTypeIntentIn.getType(), Xname.SCLASS_F_PARAM, _fctDef, true); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam(dimension.getUpperBoundId(), intTypeIntentIn.getType(), _fctType); param.setAttribute(ClawAttr.IS_CLAW.toString(), Xname.TRUE); } // Create induction variable declaration xcodeml.createIdAndDecl(dimension.getIdentifier(), Xname.TYPE_F_INT, Xname.SCLASS_F_LOCAL, _fctDef, false); } } /** * Get the list of dimensions in order from the parallelize over definition. * * @param overIndex Which over clause to use. * @return Ordered list of dimension object. */ private List<DimensionDefinition> getOrderedDimensionsFromDefinition(int overIndex) { if(_claw.hasOverClause()) { List<DimensionDefinition> dimensions = new ArrayList<>(); for(String o : _claw.getOverClauseValues().get(overIndex)) { if(o.equals(DimensionDefinition.BASE_DIM)) { continue; } dimensions.add(_dimensions.get(o)); } return dimensions; } else { return _claw.getDimensionValuesReversed(); } } /** * @return Always false as independent transformation are applied one by one. * @see Transformation#canBeTransformedWith(XcodeProgram, Transformation) */ @Override public boolean canBeTransformedWith(XcodeProgram xcodeml, Transformation other) { return false; // This is an independent transformation } }
omni-cx2x/src/cx2x/translator/transformation/claw/parallelize/Parallelize.java
/* * This file is released under terms of BSD license * See LICENSE file for more information */ package cx2x.translator.transformation.claw.parallelize; import cx2x.translator.ClawTranslator; import cx2x.translator.common.Utility; import cx2x.translator.language.base.ClawLanguage; import cx2x.translator.language.helper.TransformationHelper; import cx2x.translator.language.helper.accelerator.AcceleratorDirective; import cx2x.translator.language.helper.accelerator.AcceleratorHelper; import cx2x.translator.language.helper.target.Target; import cx2x.translator.transformation.ClawTransformation; import cx2x.translator.xnode.ClawAttr; import cx2x.xcodeml.exception.IllegalTransformationException; import cx2x.xcodeml.helper.NestedDoStatement; import cx2x.xcodeml.helper.XnodeUtil; import cx2x.xcodeml.language.DimensionDefinition; import cx2x.xcodeml.transformation.Transformation; import cx2x.xcodeml.transformation.Translator; import cx2x.xcodeml.xnode.*; import xcodeml.util.XmOption; import java.util.*; /** * The parallelize transformation transforms the code contained in a * subroutine/function by adding necessary dimensions and parallelism to the * defined data. * <p> * Transformation for the GPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Do statements over the additional dimensions is added as an outer * loop and wrap the entire body of the subroutine. * </ul> * <p> * Transformation for the CPU target: <ul> * <li> Automatic promotion is applied to all arrays with intent in, out or * inout. * <li> Propagated promotion is applied to all scalars or arrays used in an * assign statement at the lhs and where a promoted variable is used on the * rhs. * <li> Do statements over the additional dimensions are added as an inner * loop wrapping each assign statements including promoted variables. * </ul> * <p> * Generation of OpenACC directives:<ul> * <li> acc routine seq is generated for subroutine called from the parallelized * subroutine if they are located in the same translation unit. * <li> acc data region with corresponding present clause for all promoted * variables with the intent in, out or inout. * <li> acc parallel region is generated to wrap all the body of the subroutine. * <li> acc private clause is added to the parallel directive for all local * variables. * <li> acc loop is generated for the generated do statement. * <li> acc loop seq is generated for already existing do statements. * </ul> * <p> * Generation of OpenMP directives: <ul> * <li> omp parallel do is generated for each generated do statements. * </ul> * * @author clementval */ public class Parallelize extends ClawTransformation { private static final int DEFAULT_OVER = 0; private final Map<String, DimensionDefinition> _dimensions; private final Map<String, PromotionInfo> _promotions; private final List<String> _arrayFieldsInOut; private final List<String> _scalarFields; private int _overDimensions; private XfunctionDefinition _fctDef; private XfunctionType _fctType; private List<List<Xnode>> _beforeCrt, _inMiddle, _afterCrt; /** * Constructs a new Parallelize transformation triggered from a specific * pragma. * * @param directive The directive that triggered the define transformation. */ public Parallelize(ClawLanguage directive) { super(directive); _overDimensions = 0; _dimensions = new HashMap<>(); _promotions = new HashMap<>(); _arrayFieldsInOut = new ArrayList<>(); _scalarFields = new ArrayList<>(); } /** * Print information about promoted arrays, candidate for promotion arrays and * scalars. * * @param name Name of the subroutine. * @param promoted List of promoted array variables. * @param candidateArrays List of candidate array variables for promotion. * @param scalars List of candidate scalar variables for promotion. */ private void printDebugPromotionInfos(String name, List<String> promoted, List<String> candidateArrays, List<String> scalars) { if(XmOption.isDebugOutput()) { System.out.println("=========================================="); System.out.println("Parallelize promotion infos for subroutine " + name); System.out.println(" - Promoted arrays(" + promoted.size() + "):"); for(String array : promoted) { System.out.println(" " + array); } System.out.println(" - Candidate arrays(" + candidateArrays.size() + "):"); for(String array : candidateArrays) { System.out.println(" " + array); } System.out.println(" - Candidate scalars(" + scalars.size() + "):"); for(String array : scalars) { System.out.println(" " + array); } System.out.println("=========================================="); } } @Override public boolean analyze(XcodeProgram xcodeml, Translator translator) { // Check for the parent fct/subroutine definition _fctDef = XnodeUtil.findParentFunction(_claw.getPragma()); if(_fctDef == null) { xcodeml.addError("Parent function/subroutine cannot be found. " + "Parallelize directive must be defined in a function/subroutine.", _claw.getPragma().lineNo()); return false; } _fctType = (XfunctionType) xcodeml.getTypeTable(). get(_fctDef.getName().getAttribute(Xattr.TYPE)); if(_fctType == null) { xcodeml.addError("Function/subroutine signature cannot be found. ", _claw.getPragma().lineNo()); return false; } // Check if unsupported statements are located in the future parallel // region. if(_claw.getTarget() == Target.GPU && _claw.getDirectiveLanguage() == AcceleratorDirective.OPENACC) { Xnode contains = _fctDef.body().matchSeq(Xcode.FCONTAINSSTATEMENT); Xnode parallelRegionStart = AcceleratorHelper.findParallelRegionStart( _claw.getAcceleratorGenerator(), _fctDef, null); Xnode parallelRegionEnd = AcceleratorHelper.findParallelRegionEnd( _claw.getAcceleratorGenerator(), _fctDef, contains); List<Xnode> unsupportedStatements = XnodeUtil.getStatements(parallelRegionStart, parallelRegionEnd, _claw.getAcceleratorGenerator().getUnsupportedStatements()); if(unsupportedStatements.size() > 0) { for(Xnode statement : unsupportedStatements) { xcodeml.addError("Unsupported statement in parallel region", statement.lineNo()); } return false; } } return analyzeDimension(xcodeml) && analyzeData(xcodeml) && analyzeOver(xcodeml); } /** * Analyse the defined dimension. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeDimension(XcodeProgram xcodeml) { if(!_claw.hasDimensionClause()) { xcodeml.addError("No dimension defined for parallelization.", _claw.getPragma().lineNo()); return false; } for(DimensionDefinition d : _claw.getDimensionValues()) { if(_dimensions.containsKey(d.getIdentifier())) { xcodeml.addError( String.format("Dimension with identifier %s already specified.", d.getIdentifier()), _claw.getPragma().lineNo() ); return false; } _dimensions.put(d.getIdentifier(), d); } return true; } /** * Analyse the information defined in the data clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeData(XcodeProgram xcodeml) { /* If there is no data/over clause specified, an automatic deduction for * array promotion is performed. */ if(!_claw.hasOverDataClause()) { List<String> scalars = new ArrayList<>(); List<String> candidateArrays = new ArrayList<>(); List<Xdecl> declarations = _fctDef.getDeclarationTable().values(); for(Xdecl decl : declarations) { if(decl.opcode() != Xcode.VARDECL) { continue; } Xtype type = xcodeml.getTypeTable(). get(decl.matchSeq(Xcode.NAME).getAttribute(Xattr.TYPE)); if(type instanceof XbasicType) { String varName = decl.matchSeq(Xcode.NAME).value(); XbasicType bType = (XbasicType) type; if(bType.isArray()) { if(bType.hasIntent() || bType.isPointer()) { _arrayFieldsInOut.add(varName); } else { candidateArrays.add(varName); } } else { if(_claw.hasScalarClause() && _claw.getScalarClauseValues().contains(varName)) { _arrayFieldsInOut.add(varName); } if(!bType.isParameter() && bType.hasIntent()) { scalars.add(varName); } } } } _scalarFields.addAll(scalars); _scalarFields.addAll(candidateArrays); printDebugPromotionInfos(_fctDef.getName().value(), _arrayFieldsInOut, candidateArrays, scalars); return true; } /* If the data clause if defined at least once, manual promotion is the * rule. The array identifiers defined in the data clauses will be used as * the list of array to be promoted. * In the analysis, we control that all defined arrays in the data clauses * are actual declared variables. */ for(List<String> data : _claw.getOverDataClauseValues()) { for(String d : data) { if(!_fctDef.getSymbolTable().contains(d)) { xcodeml.addError( String.format("Data %s is not defined in the current block.", d), _claw.getPragma().lineNo() ); return false; } if(!_fctDef.getDeclarationTable().contains(d)) { xcodeml.addError( String.format("Data %s is not declared in the current block.", d), _claw.getPragma().lineNo() ); return false; } } _arrayFieldsInOut.addAll(data); } return true; } /** * Analyse the information defined in the over clause. * * @param xcodeml Current XcodeML program unit to store the error message. * @return True if the analysis succeeded. False otherwise. */ private boolean analyzeOver(XcodeProgram xcodeml) { if(!_claw.hasOverClause()) { _overDimensions += _claw.getDimensionValues().size(); return true; } for(List<String> over : _claw.getOverClauseValues()) { if(!over.contains(DimensionDefinition.BASE_DIM)) { xcodeml.addError("The column dimension has not been specified in the " + "over clause. Use : to specify it.", _claw.getPragma().lineNo()); return false; } int baseDimNb = TransformationHelper.baseDimensionNb(over); if(baseDimNb > 2) { xcodeml.addError("Too many base dimensions specified in over clause. " + "Maximum two base dimensions can be specified.", _claw.getPragma().lineNo()); return false; } else if(baseDimNb == 2) { if(!over.get(0).equals(DimensionDefinition.BASE_DIM) || !over.get(over.size() - 1).equals(DimensionDefinition.BASE_DIM)) { xcodeml.addError("Base dimensions structure not supported in over" + "clause.", _claw.getPragma().lineNo()); return false; } } } // Check if over dimensions are defined dimensions _overDimensions = _claw.getDimensionValues().size(); for(List<String> overLst : _claw.getOverClauseValues()) { int usedDimension = 0; for(String o : overLst) { if(!o.equals(DimensionDefinition.BASE_DIM)) { if(!_dimensions.containsKey(o)) { xcodeml.addError( String.format( "Dimension %s is not defined. Cannot be used in over " + "clause", o), _claw.getPragma().lineNo() ); return false; } ++usedDimension; } } if(usedDimension != _overDimensions) { xcodeml.addError("Over clause doesn't use one or more defined " + "dimensions", _claw.getPragma().lineNo()); return false; } } return true; } @Override public void transform(XcodeProgram xcodeml, Translator translator, Transformation other) throws Exception { // Handle PURE function / subroutine ClawTranslator trans = (ClawTranslator) translator; boolean pureRemoved = XnodeUtil.removePure(_fctDef, _fctType); if(trans.getConfiguration().isForcePure() && pureRemoved) { throw new IllegalTransformationException( "PURE specifier cannot be removed", _fctDef.lineNo()); } else if(pureRemoved) { String fctName = _fctDef.matchDirectDescendant(Xcode.NAME).value(); System.out.println("Warning: PURE specifier removed from function " + fctName + " at line " + _fctDef.lineNo() + ". Transformation and " + "code generation applied to it."); } // Prepare the array index that will be added to the array references. prepareArrayIndexes(xcodeml); // Insert the declarations of variables to iterate over the new dimensions. insertVariableToIterateOverDimension(xcodeml); // Promote all array fields with new dimensions. promoteFields(xcodeml); // Adapt array references. if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { TransformationHelper.adaptArrayReferences( _claw.getOverDataClauseValues().get(i), i, _fctDef.body(), _promotions, _beforeCrt, _inMiddle, _afterCrt, xcodeml); } } else { TransformationHelper.adaptArrayReferences(_arrayFieldsInOut, DEFAULT_OVER, _fctDef.body(), _promotions, _beforeCrt, _inMiddle, _afterCrt, xcodeml); } // Delete the pragma _claw.getPragma().delete(); // Apply specific target transformation if(_claw.getTarget() == Target.GPU) { transformForGPU(xcodeml); } else if(_claw.getTarget() == Target.CPU) { transformForCPU(xcodeml); } if(!_fctType.getBooleanAttribute(Xattr.IS_PRIVATE)) { XmoduleDefinition modDef = _fctDef.findParentModule(); if(modDef != null) { TransformationHelper.updateModuleSignature(xcodeml, _fctDef, _fctType, modDef, _claw, translator, false); } } } /** * Apply GPU based transformation. * * @param xcodeml Current XcodeML program unit. */ private void transformForGPU(XcodeProgram xcodeml) { AcceleratorHelper.generateLoopSeq(_claw, xcodeml, _fctDef); /* Create a nested loop with the new defined dimensions and wrap it around * the whole subroutine's body. This is for the moment a really naive * transformation idea but it is our start point. * Use the first over clause to create it. */ NestedDoStatement loops = new NestedDoStatement(getOrderedDimensionsFromDefinition(0), xcodeml); /* Subroutine/function can have a contains section with inner subroutines or * functions. The newly created (nested) do statements should stop before * this contains section if it exists. */ Xnode contains = _fctDef.body().matchSeq(Xcode.FCONTAINSSTATEMENT); if(contains != null) { Xnode parallelRegionStart = AcceleratorHelper.findParallelRegionStart( _claw.getAcceleratorGenerator(), _fctDef, null); Xnode parallelRegionEnd = AcceleratorHelper.findParallelRegionEnd( _claw.getAcceleratorGenerator(), _fctDef, contains); XnodeUtil.shiftStatementsInBody(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); contains.insertBefore(loops.getOuterStatement()); } else { // No contains section, all the body is copied to the do statements. Xnode parallelRegionStart = AcceleratorHelper.findParallelRegionStart( _claw.getAcceleratorGenerator(), _fctDef, null); Xnode parallelRegionEnd = AcceleratorHelper.findParallelRegionEnd( _claw.getAcceleratorGenerator(), _fctDef, null); Xnode hook = parallelRegionEnd.nextSibling(); XnodeUtil.shiftStatementsInBody(parallelRegionStart, parallelRegionEnd, loops.getInnerStatement().body(), true); //_fctDef.body().delete(); //Xnode newBody = new Xnode(Xcode.BODY, xcodeml); if(hook == null) { _fctDef.body().append(loops.getOuterStatement(), false); } else { hook.insertBefore(loops.getOuterStatement()); } //newBody.append(loops.getOuterStatement(), false); //_fctDef.append(newBody, false); } // Generate the data region List<String> presents = AcceleratorHelper.getPresentVariables(xcodeml, _fctDef); AcceleratorHelper.generateDataRegionClause(_claw, xcodeml, presents, loops.getOuterStatement(), loops.getOuterStatement()); // Generate the parallel region List<String> privates = AcceleratorHelper.getLocalArrays(xcodeml, _fctDef); AcceleratorHelper.generateParallelLoopClause(_claw, xcodeml, privates, loops.getOuterStatement(), loops.getOuterStatement(), loops.getGroupSize()); AcceleratorHelper.generateRoutineDirectives(_claw, xcodeml, _fctDef); } /** * Apply CPU based transformations. * * @param xcodeml Current XcodeML program unit. * @throws IllegalTransformationException If promotion of arrays fails. */ private void transformForCPU(XcodeProgram xcodeml) throws IllegalTransformationException { /* Create a group of nested loop with the newly defined dimension and wrap * every assignment statement in the column loop or including data with it. * This is for the moment a really naive transformation idea but it is our * start point. * Use the first over clause to do it. */ List<DimensionDefinition> order = getOrderedDimensionsFromDefinition(0); List<Xnode> assignStatements = _fctDef.body().matchAll(Xcode.FASSIGNSTATEMENT); for(Xnode assign : assignStatements) { Xnode lhs = assign.child(Xnode.LHS); String lhsName = (lhs.opcode() == Xcode.VAR) ? lhs.value() : lhs.matchSeq(Xcode.VARREF, Xcode.VAR).value(); NestedDoStatement loops = null; if(lhs.opcode() == Xcode.FARRAYREF && _arrayFieldsInOut.contains(lhsName)) { loops = new NestedDoStatement(order, xcodeml); assign.insertAfter(loops.getOuterStatement()); loops.getInnerStatement().body().append(assign, true); assign.delete(); } else if(lhs.opcode() == Xcode.VAR || lhs.opcode() == Xcode.FARRAYREF && _scalarFields.contains(lhsName)) { /* If the assignment is in the column loop and is composed with some * promoted variables, the field must be promoted and the var reference * switch to an array reference */ if(shouldBePromoted(assign)) { if(!_arrayFieldsInOut.contains(lhsName)) { _arrayFieldsInOut.add(lhsName); PromotionInfo promotionInfo; if(lhs.opcode() == Xcode.VAR) { // Scalar to array promotionInfo = TransformationHelper.promoteField(lhsName, false, false, DEFAULT_OVER, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); } else { // Array to array promotionInfo = TransformationHelper.promoteField(lhsName, true, true, DEFAULT_OVER, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); } _promotions.put(lhsName, promotionInfo); } if(lhs.opcode() == Xcode.VAR) { adaptScalarRefToArrayReferences(xcodeml, Collections.singletonList(lhsName), DEFAULT_OVER); } else { TransformationHelper.adaptArrayReferences( Collections.singletonList(lhsName), DEFAULT_OVER, _fctDef.body(), _promotions, _beforeCrt, _inMiddle, _afterCrt, xcodeml); } loops = new NestedDoStatement(order, xcodeml); assign.insertAfter(loops.getOuterStatement()); loops.getInnerStatement().body().append(assign, true); assign.delete(); } } if(loops != null) { // Generate the corresponding directive around the loop AcceleratorHelper.generateLoopDirectives(_claw, xcodeml, loops.getOuterStatement(), loops.getOuterStatement(), AcceleratorHelper.NO_COLLAPSE); } } // Generate the parallel region AcceleratorHelper.generateParallelClause(_claw, xcodeml, _fctDef.body().firstChild(), _fctDef.body().lastChild()); } /** * Check whether the LHS variable should be promoted. * * @param assignStmt Assign statement node. * @return True if the LHS variable should be promoted. False otherwise. */ private boolean shouldBePromoted(Xnode assignStmt) { Xnode rhs = assignStmt.child(Xnode.RHS); if(rhs == null) { return false; } List<Xnode> vars = XnodeUtil.findAllReferences(rhs); Set<String> names = XnodeUtil.getNamesFromReferences(vars); return Utility.hasIntersection(names, _arrayFieldsInOut); } /** * Prepare the arrayIndex elements that will be inserted before and after the * current indexes in the array references. * * @param xcodeml Current XcodeML program unit in which new elements are * created. */ private void prepareArrayIndexes(XcodeProgram xcodeml) { _beforeCrt = new ArrayList<>(); _afterCrt = new ArrayList<>(); _inMiddle = new ArrayList<>(); if(_claw.hasOverClause()) { /* If the over clause is specified, the indexes respect the definition of * the over clause. Indexes before the "colon" symbol will be inserted * before the current indexes and the remaining indexes will be inserted * after the current indexes. */ for(List<String> over : _claw.getOverClauseValues()) { List<Xnode> beforeCrt = new ArrayList<>(); List<Xnode> afterCrt = new ArrayList<>(); List<Xnode> inMiddle = new ArrayList<>(); List<Xnode> crt = beforeCrt; // In middle insertion if(TransformationHelper.baseDimensionNb(over) == 2) { for(String dim : over) { if(!dim.equals(DimensionDefinition.BASE_DIM)) { DimensionDefinition d = _dimensions.get(dim); inMiddle.add(d.generateArrayIndex(xcodeml)); } } } else { for(String dim : over) { if(dim.equals(DimensionDefinition.BASE_DIM)) { crt = afterCrt; } else { DimensionDefinition d = _dimensions.get(dim); crt.add(d.generateArrayIndex(xcodeml)); } } } Collections.reverse(beforeCrt); _beforeCrt.add(beforeCrt); _afterCrt.add(afterCrt); _inMiddle.add(inMiddle); } } else { /* If no over clause, the indexes are inserted in order from the first * defined dimensions from left to right. Everything is inserted on the * left of current indexes. */ List<Xnode> crt = new ArrayList<>(); List<Xnode> empty = Collections.emptyList(); for(DimensionDefinition dim : _claw.getDimensionValues()) { crt.add(dim.generateArrayIndex(xcodeml)); } Collections.reverse(crt); _beforeCrt.add(crt); _afterCrt.add(empty); _inMiddle.add(empty); } } /** * Promote all fields declared in the data clause with the additional * dimensions. * * @param xcodeml Current XcodeML program unit in which the element will be * created. * @throws IllegalTransformationException if elements cannot be created or * elements cannot be found. */ private void promoteFields(XcodeProgram xcodeml) throws IllegalTransformationException { if(_claw.hasOverDataClause()) { for(int i = 0; i < _claw.getOverDataClauseValues().size(); ++i) { for(String fieldId : _claw.getOverDataClauseValues().get(i)) { PromotionInfo promotionInfo = TransformationHelper.promoteField(fieldId, true, true, i, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); _promotions.put(fieldId, promotionInfo); } } } else { // Promote all arrays in a similar manner for(String fieldId : _arrayFieldsInOut) { PromotionInfo promotionInfo = TransformationHelper.promoteField(fieldId, true, true, DEFAULT_OVER, _overDimensions, _fctDef, _fctType, _claw.getDimensionValues(), _claw, xcodeml, null); _promotions.put(fieldId, promotionInfo); } } } /** * Adapt all the array references of the variable in the data clause in the * current function/subroutine definition. * * @param xcodeml Current XcodeML program unit in which the element will be * created. * @param ids List of array identifiers that must be adapted. * @param index Index designing the correct over clause to be used. */ private void adaptScalarRefToArrayReferences(XcodeProgram xcodeml, List<String> ids, int index) { for(String id : ids) { List<Xnode> vars = XnodeUtil.findAllReferences(_fctDef.body(), id); Xid sId = _fctDef.getSymbolTable().get(id); XbasicType type = (XbasicType) xcodeml.getTypeTable().get(sId.getType()); for(Xnode var : vars) { Xnode ref = xcodeml.createArrayRef(type, var.cloneNode()); for(Xnode ai : _beforeCrt.get(index)) { ref.matchSeq(Xcode.VARREF).insertAfter(ai.cloneNode()); } for(Xnode ai : _afterCrt.get(index)) { ref.append(ai, true); } var.insertAfter(ref); var.delete(); } } } /** * Insert the declaration of the different variables needed to iterate over * the additional dimensions. * * @param xcodeml Current XcodeML program unit in which element are * created. */ private void insertVariableToIterateOverDimension(XcodeProgram xcodeml) { // Create type and declaration for iterations over the new dimensions XbasicType intTypeIntentIn = xcodeml.createBasicType( xcodeml.getTypeTable().generateIntegerTypeHash(), Xname.TYPE_F_INT, Xintent.IN); xcodeml.getTypeTable().add(intTypeIntentIn); // For each dimension defined in the directive for(DimensionDefinition dimension : _claw.getDimensionValues()) { // Create the parameter for the lower bound if(dimension.lowerBoundIsVar()) { xcodeml.createIdAndDecl(dimension.getLowerBoundId(), intTypeIntentIn.getType(), Xname.SCLASS_F_PARAM, _fctDef, true); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam(dimension.getLowerBoundId(), intTypeIntentIn.getType(), _fctType); param.setAttribute(ClawAttr.IS_CLAW.toString(), Xname.TRUE); } // Create parameter for the upper bound if(dimension.upperBoundIsVar()) { xcodeml.createIdAndDecl(dimension.getUpperBoundId(), intTypeIntentIn.getType(), Xname.SCLASS_F_PARAM, _fctDef, true); // Add parameter to the local type table Xnode param = xcodeml.createAndAddParam(dimension.getUpperBoundId(), intTypeIntentIn.getType(), _fctType); param.setAttribute(ClawAttr.IS_CLAW.toString(), Xname.TRUE); } // Create induction variable declaration xcodeml.createIdAndDecl(dimension.getIdentifier(), Xname.TYPE_F_INT, Xname.SCLASS_F_LOCAL, _fctDef, false); } } /** * Get the list of dimensions in order from the parallelize over definition. * * @param overIndex Which over clause to use. * @return Ordered list of dimension object. */ private List<DimensionDefinition> getOrderedDimensionsFromDefinition(int overIndex) { if(_claw.hasOverClause()) { List<DimensionDefinition> dimensions = new ArrayList<>(); for(String o : _claw.getOverClauseValues().get(overIndex)) { if(o.equals(DimensionDefinition.BASE_DIM)) { continue; } dimensions.add(_dimensions.get(o)); } return dimensions; } else { return _claw.getDimensionValuesReversed(); } } /** * @return Always false as independent transformation are applied one by one. * @see Transformation#canBeTransformedWith(XcodeProgram, Transformation) */ @Override public boolean canBeTransformedWith(XcodeProgram xcodeml, Transformation other) { return false; // This is an independent transformation } }
Remove dead code + add comment
omni-cx2x/src/cx2x/translator/transformation/claw/parallelize/Parallelize.java
Remove dead code + add comment
<ide><path>mni-cx2x/src/cx2x/translator/transformation/claw/parallelize/Parallelize.java <ide> Xnode parallelRegionEnd = AcceleratorHelper.findParallelRegionEnd( <ide> _claw.getAcceleratorGenerator(), _fctDef, null); <ide> <add> // Define a hook from where we can insert the new do statement <ide> Xnode hook = parallelRegionEnd.nextSibling(); <del> <del> <ide> XnodeUtil.shiftStatementsInBody(parallelRegionStart, parallelRegionEnd, <ide> loops.getInnerStatement().body(), true); <ide> <del> //_fctDef.body().delete(); <del> //Xnode newBody = new Xnode(Xcode.BODY, xcodeml); <del> <add> // Hook is null then we append the do statement to the current fct body <ide> if(hook == null) { <ide> _fctDef.body().append(loops.getOuterStatement(), false); <ide> } else { <add> // Insert new do statement before the hook element <ide> hook.insertBefore(loops.getOuterStatement()); <ide> } <del> <del> //newBody.append(loops.getOuterStatement(), false); <del> //_fctDef.append(newBody, false); <ide> } <ide> <ide> // Generate the data region
JavaScript
mit
bcf6b2cb9858c54ad95eab1aa8dd823d842dae45
0
HyphnKnight/js13k-2017,HyphnKnight/js13k-2017
export const child = `\uD83D\uDC69\uD83C\uDFFC\u200D\uD83C\uDF3E`; export const protector = `\uD83D\uDC6E\uD83C\uDFFF\u200D\u2640\uFE0F`; export const persecutor = `\uD83D\uDD75\uD83C\uDFFD`; export const avenger = `\uD83D\uDC69\uD83C\uDFFB\u200D\uD83C\uDFA4`; export const demon = `\uD83D\uDC79`; export const tree = `\uD83C\uDF32`; export const treeAlt = `\uD83C\uDF33`; export const cloud = `\u2601\uFE0F`; export const mountain = `\uD83C\uDFD4`; export const pointRight = `\uD83D\uDC49\uD83C\uDFFB`; export const ghost = `\uD83D\uDC7B`; export const pool = `\uD83C\uDF75`; export const gem = `\uD83D\uDC8E`; export const blackHeart = `\uD83D\uDDA4`; export const heart = `\u2764\uFE0F`;
src/emoji.js
export const child = `\uD83D\uDC69\uD83C\uDFFC\u200D\uD83C\uDF3E`; export const protector = `\uD83D\uDC6E\uD83C\uDFFF\u200D\u2640\uFE0F`; export const persecutor = `\uD83D\uDD75\uD83C\uDFFD`; export const avenger = `\uD83D\uDC69\uD83C\uDFFB\u200D\uD83C\uDFA4`; export const demon = `\uD83D\uDC79`; export const tree = `\uD83C\uDF32`; export const treeAlt = `\uD83C\uDF33`; export const cloud = `\u2601\uFE0F`; export const mountain = `\uD83C\uDFD4`; export const pointRight = `\uD83D\uDC49\uD83C\uDFFB`; export const ghost = `\uD83D\uDC7B`; export const pool = `\uD83C\uDF75`; export const gem = `\uD83D\uDC8E`;
add heart emoji
src/emoji.js
add heart emoji
<ide><path>rc/emoji.js <ide> export const ghost = `\uD83D\uDC7B`; <ide> export const pool = `\uD83C\uDF75`; <ide> export const gem = `\uD83D\uDC8E`; <add>export const blackHeart = `\uD83D\uDDA4`; <add>export const heart = `\u2764\uFE0F`;
Java
mit
927cb8039a5f9283a476c7f701bb4a40aaac6342
0
codeka/wwmmo,codeka/wwmmo,codeka/wwmmo,codeka/wwmmo,codeka/wwmmo,codeka/wwmmo
package au.com.codeka.warworlds.server.admin.handlers; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.Collection; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import org.joda.time.DateTime; import au.com.codeka.carrot.base.CarrotException; import au.com.codeka.carrot.resource.FileResourceLocater; import au.com.codeka.carrot.interpret.CarrotInterpreter; import au.com.codeka.carrot.interpret.InterpretException; import au.com.codeka.carrot.lib.Filter; import au.com.codeka.carrot.template.TemplateEngine; import au.com.codeka.warworlds.common.Log; import au.com.codeka.warworlds.common.proto.AdminRole; import au.com.codeka.warworlds.server.admin.RequestException; import au.com.codeka.warworlds.server.admin.RequestHandler; import au.com.codeka.warworlds.server.admin.Session; import au.com.codeka.warworlds.server.store.DataStore; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import javax.annotation.Nullable; public class AdminHandler extends RequestHandler { private final Log log = new Log("AdminHandler"); private static final TemplateEngine TEMPLATE_ENGINE; static { TEMPLATE_ENGINE = new TemplateEngine(); TEMPLATE_ENGINE.getConfiguration().setResourceLocater( new FileResourceLocater( TEMPLATE_ENGINE.getConfiguration(), new File("data/admin/tmpl").getAbsolutePath())); TEMPLATE_ENGINE.getConfiguration().setEncoding("utf-8"); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new NumberFilter()); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new AttrEscapeFilter()); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new LocalDateFilter()); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new IsInRoleFilter()); } @Override public boolean onBeforeHandle() { Collection<AdminRole> requiredRoles = getRequiredRoles(); if (requiredRoles != null) { Session session = getSessionNoError(); if (session == null) { authenticate(); return false; } else { boolean inRoles = false; for (AdminRole role : requiredRoles) { inRoles = inRoles || session.isInRole(role); } if (!inRoles) { // you're not in a required role. log.warning("User '%s' is not in any required role: %s", session.getEmail(), requiredRoles); redirect("/admin"); return false; } } } return true; } @Override protected void handleException(RequestException e) { try { render("exception.html", ImmutableMap.<String, Object>builder() .put("exception", e) .put("stack_trace", Throwables.getStackTraceAsString(e)) .build()); e.populate(getResponse()); } catch (Exception e2) { log.error("Error loading exception.html template.", e2); setResponseText(e2.toString()); } } /** * Gets a collection of roles, one of which the current user must be in to access this handler. */ protected Collection<AdminRole> getRequiredRoles() { return Lists.newArrayList(AdminRole.ADMINISTRATOR); } protected void render(String path, @Nullable Map<String, Object> data) throws RequestException { if (data == null) { data = new TreeMap<>(); } if (data instanceof ImmutableMap) { data = new TreeMap<>(data); // make it mutable again... } data.put("realm", getRealm()); Session session = getSessionNoError(); if (session != null) { data.put("session", session); } data.put("num_backend_users", DataStore.i.adminUsers().count()); getResponse().setContentType("text/html"); getResponse().setHeader("Content-Type", "text/html; charset=utf-8"); try { getResponse().getWriter().write(TEMPLATE_ENGINE.process(path, data)); } catch (CarrotException | IOException e) { log.error("Error rendering template!", e); throw new RequestException(e); } } protected void write(String text) { getResponse().setContentType("text/plain"); getResponse().setHeader("Content-Type", "text/plain; charset=utf-8"); try { getResponse().getWriter().write(text); } catch (IOException e) { log.error("Error writing output!", e); } } protected void authenticate() { URI requestUrl = null; try { requestUrl = new URI(getRequestUrl()); } catch (URISyntaxException e) { throw new RuntimeException(e); } String finalUrl = requestUrl.getPath(); String redirectUrl = requestUrl.resolve("/admin/login").toString(); try { redirectUrl += "?continue=" + URLEncoder.encode(finalUrl, "utf-8"); } catch (UnsupportedEncodingException e) { // should never happen } redirect(redirectUrl); } private static class NumberFilter implements Filter { private static final DecimalFormat FORMAT = new DecimalFormat("#,##0"); @Override public String getName() { return "number"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { if (object == null) { return null; } if (object instanceof Integer) { int n = (int) object; return FORMAT.format(n); } if (object instanceof Long) { long n = (long) object; return FORMAT.format(n); } if (object instanceof Float) { float n = (float) object; return FORMAT.format(n); } if (object instanceof Double) { double n = (double) object; return FORMAT.format(n); } throw new InterpretException("Expected a number."); } } private static class AttrEscapeFilter implements Filter { @Override public String getName() { return "attr-escape"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { return object.toString().replace("\"", "&quot;").replace("'", "&squot;"); } } private static class LocalDateFilter implements Filter { @Override public String getName() { return "local-date"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { if (object instanceof DateTime) { DateTime dt = (DateTime) object; return String.format(Locale.ENGLISH, "<script>(function() {" + " var dt = new Date(\"%s\");" + " +document.write(dt.toLocaleString());" + "})();</script>", dt); } throw new InterpretException("Expected a DateTime."); } } private static class IsInRoleFilter implements Filter { @Override public String getName() { return "isinrole"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { if (object instanceof Session) { AdminRole role = AdminRole.valueOf(args[0]); return ((Session) object).isInRole(role); } throw new InterpretException("Expected a Session, not " + object); } } }
server/src/main/java/au/com/codeka/warworlds/server/admin/handlers/AdminHandler.java
package au.com.codeka.warworlds.server.admin.handlers; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.Collection; import java.util.Locale; import java.util.Map; import java.util.TreeMap; import org.joda.time.DateTime; import au.com.codeka.carrot.base.CarrotException; import au.com.codeka.carrot.resource.FileResourceLocater; import au.com.codeka.carrot.interpret.CarrotInterpreter; import au.com.codeka.carrot.interpret.InterpretException; import au.com.codeka.carrot.lib.Filter; import au.com.codeka.carrot.template.TemplateEngine; import au.com.codeka.warworlds.common.Log; import au.com.codeka.warworlds.common.proto.AdminRole; import au.com.codeka.warworlds.server.admin.RequestException; import au.com.codeka.warworlds.server.admin.RequestHandler; import au.com.codeka.warworlds.server.admin.Session; import au.com.codeka.warworlds.server.store.DataStore; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import javax.annotation.Nullable; public class AdminHandler extends RequestHandler { private final Log log = new Log("AdminHandler"); private static final TemplateEngine TEMPLATE_ENGINE; static { TEMPLATE_ENGINE = new TemplateEngine(); TEMPLATE_ENGINE.getConfiguration().setResourceLocater( new FileResourceLocater( TEMPLATE_ENGINE.getConfiguration(), new File("data/admin/tmpl").getAbsolutePath())); TEMPLATE_ENGINE.getConfiguration().setEncoding("utf-8"); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new NumberFilter()); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new AttrEscapeFilter()); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new LocalDateFilter()); TEMPLATE_ENGINE.getConfiguration().getFilterLibrary().register(new IsInRoleFilter()); } @Override public boolean onBeforeHandle() { Collection<AdminRole> requiredRoles = getRequiredRoles(); if (requiredRoles != null) { Session session = getSessionNoError(); if (session == null) { authenticate(); return false; } else { boolean inRoles = false; for (AdminRole role : requiredRoles) { inRoles = inRoles || session.isInRole(role); } if (!inRoles) { // you're not in a required role. redirect("/admin"); return false; } } } return true; } @Override protected void handleException(RequestException e) { try { render("exception.html", ImmutableMap.<String, Object>builder() .put("exception", e) .put("stack_trace", Throwables.getStackTraceAsString(e)) .build()); e.populate(getResponse()); } catch (Exception e2) { log.error("Error loading exception.html template.", e2); setResponseText(e2.toString()); } } /** * Gets a collection of roles, one of which the current user must be in to access this handler. */ protected Collection<AdminRole> getRequiredRoles() { return Lists.newArrayList(AdminRole.ADMINISTRATOR); } protected void render(String path, @Nullable Map<String, Object> data) throws RequestException { if (data == null) { data = new TreeMap<>(); } if (data instanceof ImmutableMap) { data = new TreeMap<>(data); // make it mutable again... } data.put("realm", getRealm()); Session session = getSessionNoError(); if (session != null) { data.put("session", session); } data.put("num_backend_users", DataStore.i.adminUsers().count()); getResponse().setContentType("text/html"); getResponse().setHeader("Content-Type", "text/html; charset=utf-8"); try { getResponse().getWriter().write(TEMPLATE_ENGINE.process(path, data)); } catch (CarrotException | IOException e) { log.error("Error rendering template!", e); throw new RequestException(e); } } protected void write(String text) { getResponse().setContentType("text/plain"); getResponse().setHeader("Content-Type", "text/plain; charset=utf-8"); try { getResponse().getWriter().write(text); } catch (IOException e) { log.error("Error writing output!", e); } } protected void authenticate() { URI requestUrl = null; try { requestUrl = new URI(getRequestUrl()); } catch (URISyntaxException e) { throw new RuntimeException(e); } String finalUrl = requestUrl.getPath(); String redirectUrl = requestUrl.resolve("/admin/login").toString(); try { redirectUrl += "?continue=" + URLEncoder.encode(finalUrl, "utf-8"); } catch (UnsupportedEncodingException e) { // should never happen } redirect(redirectUrl); } private static class NumberFilter implements Filter { private static final DecimalFormat FORMAT = new DecimalFormat("#,##0"); @Override public String getName() { return "number"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { if (object == null) { return null; } if (object instanceof Integer) { int n = (int) object; return FORMAT.format(n); } if (object instanceof Long) { long n = (long) object; return FORMAT.format(n); } if (object instanceof Float) { float n = (float) object; return FORMAT.format(n); } if (object instanceof Double) { double n = (double) object; return FORMAT.format(n); } throw new InterpretException("Expected a number."); } } private static class AttrEscapeFilter implements Filter { @Override public String getName() { return "attr-escape"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { return object.toString().replace("\"", "&quot;").replace("'", "&squot;"); } } private static class LocalDateFilter implements Filter { @Override public String getName() { return "local-date"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { if (object instanceof DateTime) { DateTime dt = (DateTime) object; return String.format(Locale.ENGLISH, "<script>(function() {" + " var dt = new Date(\"%s\");" + " +document.write(dt.toLocaleString());" + "})();</script>", dt); } throw new InterpretException("Expected a DateTime."); } } private static class IsInRoleFilter implements Filter { @Override public String getName() { return "isinrole"; } @Override public Object filter(Object object, CarrotInterpreter interpreter, String... args) throws InterpretException { if (object instanceof Session) { AdminRole role = AdminRole.valueOf(args[0]); return ((Session) object).isInRole(role); } throw new InterpretException("Expected a Session, not " + object); } } }
Add a log.
server/src/main/java/au/com/codeka/warworlds/server/admin/handlers/AdminHandler.java
Add a log.
<ide><path>erver/src/main/java/au/com/codeka/warworlds/server/admin/handlers/AdminHandler.java <ide> } <ide> if (!inRoles) { <ide> // you're not in a required role. <add> log.warning("User '%s' is not in any required role: %s", <add> session.getEmail(), requiredRoles); <ide> redirect("/admin"); <ide> return false; <ide> }
Java
apache-2.0
f0a46983b512689b2c8b6aba368c52688c2f05f8
0
robovm/robovm-studio,allotria/intellij-community,allotria/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,ibinti/intellij-community,slisson/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,jagguli/intellij-community,robovm/robovm-studio,dslomov/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,petteyg/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,dslomov/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,holmes/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,ryano144/intellij-community,kool79/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,supersven/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,ol-loginov/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,vladmm/intellij-community,izonder/intellij-community,signed/intellij-community,vladmm/intellij-community,joewalnes/idea-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,signed/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,jexp/idea2,ol-loginov/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,da1z/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,da1z/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,apixandru/intellij-community,semonte/intellij-community,samthor/intellij-community,da1z/intellij-community,holmes/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,signed/intellij-community,kool79/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,apixandru/intellij-community,samthor/intellij-community,petteyg/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,robovm/robovm-studio,da1z/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,asedunov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,jexp/idea2,TangHao1987/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,consulo/consulo,SerCeMan/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,caot/intellij-community,nicolargo/intellij-community,izonder/intellij-community,amith01994/intellij-community,slisson/intellij-community,adedayo/intellij-community,consulo/consulo,salguarnieri/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,supersven/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,jexp/idea2,wreckJ/intellij-community,asedunov/intellij-community,jagguli/intellij-community,da1z/intellij-community,asedunov/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,supersven/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,caot/intellij-community,clumsy/intellij-community,kdwink/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,fnouama/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ryano144/intellij-community,retomerz/intellij-community,robovm/robovm-studio,FHannes/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,apixandru/intellij-community,ryano144/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,samthor/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,jexp/idea2,salguarnieri/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ernestp/consulo,ahb0327/intellij-community,semonte/intellij-community,apixandru/intellij-community,ernestp/consulo,lucafavatella/intellij-community,samthor/intellij-community,petteyg/intellij-community,ryano144/intellij-community,FHannes/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,allotria/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,kool79/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ibinti/intellij-community,signed/intellij-community,signed/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,allotria/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,da1z/intellij-community,semonte/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,semonte/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,semonte/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,samthor/intellij-community,amith01994/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,Lekanich/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,izonder/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,holmes/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,caot/intellij-community,slisson/intellij-community,izonder/intellij-community,ernestp/consulo,akosyakov/intellij-community,xfournet/intellij-community,joewalnes/idea-community,slisson/intellij-community,supersven/intellij-community,da1z/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,allotria/intellij-community,fnouama/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,signed/intellij-community,signed/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,da1z/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,amith01994/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,fnouama/intellij-community,hurricup/intellij-community,kdwink/intellij-community,retomerz/intellij-community,da1z/intellij-community,samthor/intellij-community,caot/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,blademainer/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,retomerz/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,da1z/intellij-community,kdwink/intellij-community,kool79/intellij-community,robovm/robovm-studio,semonte/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,supersven/intellij-community,ernestp/consulo,retomerz/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,jagguli/intellij-community,caot/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,consulo/consulo,mglukhikh/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,kool79/intellij-community,petteyg/intellij-community,izonder/intellij-community,signed/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,jexp/idea2,jagguli/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,kool79/intellij-community,semonte/intellij-community,izonder/intellij-community,fnouama/intellij-community,consulo/consulo,ibinti/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,joewalnes/idea-community,kdwink/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,da1z/intellij-community,jagguli/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,supersven/intellij-community,supersven/intellij-community,slisson/intellij-community,samthor/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,ernestp/consulo,caot/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ahb0327/intellij-community,ryano144/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,signed/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,semonte/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,blademainer/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,caot/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,fnouama/intellij-community,ibinti/intellij-community,FHannes/intellij-community,samthor/intellij-community,fnouama/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ernestp/consulo,xfournet/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,allotria/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,signed/intellij-community,suncycheng/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,jagguli/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,signed/intellij-community,kdwink/intellij-community,kool79/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,da1z/intellij-community,FHannes/intellij-community,consulo/consulo,caot/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,slisson/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,holmes/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,signed/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,holmes/intellij-community,kool79/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,vladmm/intellij-community,joewalnes/idea-community,petteyg/intellij-community,fitermay/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,fnouama/intellij-community,clumsy/intellij-community,hurricup/intellij-community,slisson/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community
/* * Copyright 2000-2006 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.intellij.util.xml; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiManager; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.SoftFactoryMap; import com.intellij.util.xml.highlighting.ResolvingElementQuickFix; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Map; /** * Converter which resolves {@link com.intellij.util.xml.DomElement}s by name in a defined scope. The scope is taken * from corresponding {@link com.intellij.util.xml.DomFileDescription#getResolveScope(GenericDomValue)}. * * @author peter */ public class DomResolveConverter<T extends DomElement> extends ResolvingConverter<T>{ private static final FactoryMap<Class<? extends DomElement>,DomResolveConverter> ourCache = new FactoryMap<Class<? extends DomElement>, DomResolveConverter>() { @NotNull protected DomResolveConverter create(final Class<? extends DomElement> key) { return new DomResolveConverter(key); } }; private final SoftFactoryMap<DomElement, CachedValue<Map<String, DomElement>>> myResolveCache = new SoftFactoryMap<DomElement, CachedValue<Map<String, DomElement>>>() { @NotNull protected CachedValue<Map<String, DomElement>> create(final DomElement scope) { final DomManager domManager = scope.getManager(); final Project project = domManager.getProject(); return PsiManager.getInstance(project).getCachedValuesManager().createCachedValue(new CachedValueProvider<Map<String, DomElement>>() { public Result<Map<String, DomElement>> compute() { final Map<String, DomElement> map = new THashMap<String, DomElement>(); scope.acceptChildren(new DomElementVisitor() { public void visitDomElement(DomElement element) { if (myClass.isInstance(element)) { final String name = ElementPresentationManager.getElementName(element); if (name != null && !map.containsKey(name)) { map.put(name, element); } } else { element.acceptChildren(this); } } }); return new Result<Map<String, DomElement>>(map, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT); } }, false); } }; private final Class<T> myClass; public DomResolveConverter(final Class<T> aClass) { myClass = aClass; } public static <T extends DomElement> DomResolveConverter<T> createConverter(Class<T> aClass) { return ourCache.get(aClass); } public final T fromString(final String s, final ConvertContext context) { if (s == null) return null; return (T) myResolveCache.get(getResolvingScope(context)).getValue().get(s); } private static DomElement getResolvingScope(final ConvertContext context) { final DomElement invocationElement = context.getInvocationElement(); return invocationElement.getManager().getResolvingScope((GenericDomValue)invocationElement); } public String getErrorMessage(final String s, final ConvertContext context) { return CodeInsightBundle.message("error.cannot.resolve.0.1", ElementPresentationManager.getTypeName(myClass), s); } public final String toString(final T t, final ConvertContext context) { if (t == null) return null; return ElementPresentationManager.getElementName(t); } @NotNull public Collection<? extends T> getVariants(final ConvertContext context) { final DomElement reference = context.getInvocationElement(); final DomElement scope = reference.getManager().getResolvingScope((GenericDomValue)reference); return (Collection<T>)myResolveCache.get(scope).getValue().values(); } public LocalQuickFix[] getQuickFixes(final ConvertContext context) { final DomElement element = context.getInvocationElement(); final GenericDomValue value = ((GenericDomValue)element).createStableCopy(); final String newName = value.getStringValue(); if (newName == null) return LocalQuickFix.EMPTY_ARRAY; final DomElement scope = value.getManager().getResolvingScope(value); return ResolvingElementQuickFix.createFixes(newName, myClass, scope); } }
dom/openapi/src/com/intellij/util/xml/DomResolveConverter.java
/* * Copyright 2000-2006 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.intellij.util.xml; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiManager; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.SoftFactoryMap; import com.intellij.util.xml.highlighting.ResolvingElementQuickFix; import gnu.trove.THashMap; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Map; /** * Converter which resolves {@link com.intellij.util.xml.DomElement}s by name in a defined scope. The scope is taken * from corresponding {@link com.intellij.util.xml.DomFileDescription#getResolveScope(GenericDomValue)}. * * @author peter */ public class DomResolveConverter<T extends DomElement> extends ResolvingConverter<T>{ private static final FactoryMap<Class<? extends DomElement>,DomResolveConverter> ourCache = new FactoryMap<Class<? extends DomElement>, DomResolveConverter>() { @NotNull protected DomResolveConverter create(final Class<? extends DomElement> key) { return new DomResolveConverter(key); } }; private final SoftFactoryMap<DomElement, CachedValue<Map<String, DomElement>>> myResolveCache = new SoftFactoryMap<DomElement, CachedValue<Map<String, DomElement>>>() { @NotNull protected CachedValue<Map<String, DomElement>> create(final DomElement scope) { final DomManager domManager = scope.getManager(); final Project project = domManager.getProject(); return PsiManager.getInstance(project).getCachedValuesManager().createCachedValue(new CachedValueProvider<Map<String, DomElement>>() { public Result<Map<String, DomElement>> compute() { final Map<String, DomElement> map = new THashMap<String, DomElement>(); scope.acceptChildren(new DomElementVisitor() { public void visitDomElement(DomElement element) { if (myClass.isInstance(element)) { final String name = ElementPresentationManager.getElementName(element); if (name != null && !map.containsKey(name)) { map.put(name, element); } } else { element.acceptChildren(this); } } }); return new Result<Map<String, DomElement>>(map, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT); } }, false); } }; private final Class<T> myClass; public DomResolveConverter(final Class<T> aClass) { myClass = aClass; } public static <T extends DomElement> DomResolveConverter<T> createConverter(Class<T> aClass) { return ourCache.get(aClass); } public final T fromString(final String s, final ConvertContext context) { if (s == null) return null; return (T) myResolveCache.get(getResolvingScope(context)).getValue().get(s); } private static DomElement getResolvingScope(final ConvertContext context) { final DomElement invocationElement = context.getInvocationElement(); return invocationElement.getManager().getResolvingScope((GenericDomValue)invocationElement); } public String getErrorMessage(final String s, final ConvertContext context) { return CodeInsightBundle.message("error.cannot.resolve.0.1", ElementPresentationManager.getTypeName(myClass), s); } public final String toString(final T t, final ConvertContext context) { if (t == null) return null; return ElementPresentationManager.getElementName(t); } @NotNull public Collection<? extends T> getVariants(final ConvertContext context) { final DomElement reference = context.getInvocationElement(); final DomElement scope = reference.getManager().getResolvingScope((GenericDomValue)reference); return (Collection<T>)myResolveCache.get(scope).getValue().values(); } public LocalQuickFix[] getQuickFixes(final ConvertContext context) { final DomElement element = context.getInvocationElement(); final GenericDomValue value = ((GenericDomValue)element).createStableCopy(); final String newName = value.getStringValue(); assert newName != null; final DomElement scope = value.getManager().getResolvingScope(value); return ResolvingElementQuickFix.createFixes(newName, myClass, scope); } }
IDEADEV-22149
dom/openapi/src/com/intellij/util/xml/DomResolveConverter.java
IDEADEV-22149
<ide><path>om/openapi/src/com/intellij/util/xml/DomResolveConverter.java <ide> final DomElement element = context.getInvocationElement(); <ide> final GenericDomValue value = ((GenericDomValue)element).createStableCopy(); <ide> final String newName = value.getStringValue(); <del> assert newName != null; <add> if (newName == null) return LocalQuickFix.EMPTY_ARRAY; <ide> final DomElement scope = value.getManager().getResolvingScope(value); <ide> return ResolvingElementQuickFix.createFixes(newName, myClass, scope); <ide> }
Java
mit
7da63e0c95322ed8a22805087e0c78e7efbe3e65
0
richard-roberts/SOMns,smarr/SOMns,MetaConc/SOMns,richard-roberts/SOMns,richard-roberts/SOMns,smarr/SOMns,VAISHALI-DHANOA/SOMns,smarr/SOMns,smarr/SOMns,richard-roberts/SOMns,VAISHALI-DHANOA/SOMns,MetaConc/SOMns,richard-roberts/SOMns,richard-roberts/SOMns,smarr/SOMns,richard-roberts/SOMns,smarr/SOMns,smarr/SOMns,VAISHALI-DHANOA/SOMns,MetaConc/SOMns
package som.interpreter.nodes; import som.interpreter.SArguments; import som.interpreter.TruffleCompiler; import som.interpreter.TypesGen; import som.interpreter.nodes.dispatch.AbstractDispatchNode; import som.interpreter.nodes.dispatch.GenericDispatchNode; import som.interpreter.nodes.dispatch.SuperDispatchNode; import som.interpreter.nodes.dispatch.UninitializedDispatchNode; import som.interpreter.nodes.literals.BlockNode; import som.interpreter.nodes.nary.EagerBinaryPrimitiveNode; import som.interpreter.nodes.specialized.IfFalseMessageNodeFactory; import som.interpreter.nodes.specialized.IfTrueIfFalseMessageNodeFactory; import som.interpreter.nodes.specialized.IfTrueMessageNodeFactory; import som.interpreter.nodes.specialized.IntToByDoMessageNodeFactory; import som.interpreter.nodes.specialized.IntToDoMessageNodeFactory; import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileFalseStaticBlocksNode; import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileTrueStaticBlocksNode; import som.primitives.BlockPrimsFactory.ValueOnePrimFactory; import som.primitives.EqualsEqualsPrimFactory; import som.primitives.EqualsPrimFactory; import som.primitives.arithmetic.AdditionPrimFactory; import som.primitives.arithmetic.LessThanOrEqualPrimFactory; import som.primitives.arithmetic.LessThanPrimFactory; import som.primitives.arithmetic.SubtractionPrimFactory; import som.vm.Universe; import som.vmobjects.SBlock; import som.vmobjects.SSymbol; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.NodeInfo; public final class MessageSendNode { public static AbstractMessageSendNode create(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments) { return new UninitializedMessageSendNode(selector, receiver, arguments); } @NodeInfo(shortName = "send") public abstract static class AbstractMessageSendNode extends ExpressionNode implements PreevaluatedExpression { @Child protected ExpressionNode receiverNode; @Children protected final ExpressionNode[] argumentNodes; protected AbstractMessageSendNode(final ExpressionNode receiver, final ExpressionNode[] arguments) { this.receiverNode = adoptChild(receiver); this.argumentNodes = adoptChildren(arguments); } @Override public final Object executeGeneric(final VirtualFrame frame) { Object rcvr = receiverNode.executeGeneric(frame); Object[] arguments = evaluateArguments(frame); return executePreEvaluated(frame, rcvr, arguments); } @ExplodeLoop private Object[] evaluateArguments(final VirtualFrame frame) { Object[] arguments = new Object[argumentNodes.length]; for (int i = 0; i < argumentNodes.length; i++) { arguments[i] = argumentNodes[i].executeGeneric(frame); } return arguments; } } private static final class UninitializedMessageSendNode extends AbstractMessageSendNode { private final SSymbol selector; protected UninitializedMessageSendNode(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments) { super(receiver, arguments); this.selector = selector; } @Override public Object executePreEvaluated(final VirtualFrame frame, final Object receiver, final Object[] arguments) { return specialize(receiver, arguments).executePreEvaluated(frame, receiver, arguments); } private PreevaluatedExpression specialize(final Object receiver, final Object[] arguments) { TruffleCompiler.transferToInterpreterAndInvalidate("Specialize Message Node"); // first option is a super send, super sends are treated specially because // the receiver class is lexically determined if (receiverNode instanceof ISuperReadNode) { GenericMessageSendNode node = new GenericMessageSendNode(selector, receiverNode, argumentNodes, SuperDispatchNode.create(selector, (ISuperReadNode) receiverNode)); return replace(node); } // We treat super sends separately for simplicity, might not be the // optimal solution, especially in cases were the knowledge of the // receiver class also allows us to do more specific things, but for the // moment we will leave it at this. // TODO: revisit, and also do more specific optimizations for super sends. // let's organize the specializations by number of arguments // perhaps not the best, but one simple way to just get some order into // the chaos. switch (argumentNodes.length) { // case 0: return specializeUnary( receiver, arguments); // don't have any at the moment case 1: return specializeBinary(receiver, arguments); case 2: return specializeTernary(receiver, arguments); case 3: return specializeQuaternary(receiver, arguments); } return makeGenericSend(); } private GenericMessageSendNode makeGenericSend() { GenericMessageSendNode send = new GenericMessageSendNode(selector, receiverNode, argumentNodes, new UninitializedDispatchNode(selector, Universe.current())); return replace(send); } private PreevaluatedExpression specializeBinary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "whileTrue:": { if (argumentNodes[0] instanceof BlockNode && receiverNode instanceof BlockNode) { BlockNode argBlockNode = (BlockNode) argumentNodes[0]; SBlock argBlock = (SBlock) arguments[0]; return replace(new WhileTrueStaticBlocksNode( (BlockNode) receiverNode, argBlockNode, (SBlock) receiver, argBlock, Universe.current())); } break; // use normal send } case "whileFalse:": if (argumentNodes[0] instanceof BlockNode && receiverNode instanceof BlockNode) { BlockNode argBlockNode = (BlockNode) argumentNodes[0]; SBlock argBlock = (SBlock) arguments[0]; return replace(new WhileFalseStaticBlocksNode( (BlockNode) receiverNode, argBlockNode, (SBlock) receiver, argBlock, Universe.current())); } break; // use normal send case "ifTrue:": return replace(IfTrueMessageNodeFactory.create(receiver, arguments[0], Universe.current(), receiverNode, argumentNodes[0])); case "ifFalse:": return replace(IfFalseMessageNodeFactory.create(receiver, arguments[0], Universe.current(), receiverNode, argumentNodes[0])); // TODO: find a better way for primitives, use annotation or something case "<": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], LessThanPrimFactory.create(receiverNode, argumentNodes[0]))); case "<=": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], LessThanOrEqualPrimFactory.create(receiverNode, argumentNodes[0]))); case "+": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], AdditionPrimFactory.create(receiverNode, argumentNodes[0]))); case "value:": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], ValueOnePrimFactory.create(receiverNode, argumentNodes[0]))); case "-": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], SubtractionPrimFactory.create(receiverNode, argumentNodes[0]))); case "=": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], EqualsPrimFactory.create(receiverNode, argumentNodes[0]))); case "==": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], EqualsEqualsPrimFactory.create(receiverNode, argumentNodes[0]))); } return makeGenericSend(); } private PreevaluatedExpression specializeTernary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "ifTrue:ifFalse:": return replace(IfTrueIfFalseMessageNodeFactory.create(receiver, arguments[0], arguments[1], Universe.current(), receiverNode, argumentNodes[0], argumentNodes[1])); case "to:do:": if (TypesGen.TYPES.isImplicitInteger(receiver) && TypesGen.TYPES.isImplicitInteger(arguments[0]) && TypesGen.TYPES.isSBlock(arguments[1])) { return replace(IntToDoMessageNodeFactory.create(this, (SBlock) arguments[1], receiverNode, argumentNodes[0], argumentNodes[1])); } break; } return makeGenericSend(); } private PreevaluatedExpression specializeQuaternary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "to:by:do:": return replace(IntToByDoMessageNodeFactory.create(this, (SBlock) arguments[2], receiverNode, argumentNodes[0], argumentNodes[1], argumentNodes[2])); } return makeGenericSend(); } } public static final class GenericMessageSendNode extends AbstractMessageSendNode { private final SSymbol selector; public static GenericMessageSendNode create(final SSymbol selector, final ExpressionNode receiverNode, final ExpressionNode[] argumentNodes) { return new GenericMessageSendNode(selector, receiverNode, argumentNodes, new UninitializedDispatchNode(selector, Universe.current())); } @Child private AbstractDispatchNode dispatchNode; private GenericMessageSendNode(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments, final AbstractDispatchNode dispatchNode) { super(receiver, arguments); this.selector = selector; this.dispatchNode = adoptChild(dispatchNode); } @Override public Object executePreEvaluated(final VirtualFrame frame, final Object receiver, final Object[] arguments) { SArguments args = new SArguments(receiver, arguments); return dispatchNode.executeDispatch(frame, args); } public void replaceDispatchNodeBecauseCallSiteIsMegaMorphic( final GenericDispatchNode replacement) { dispatchNode.replace(replacement); } @Override public String toString() { return "GMsgSend(" + selector.getString() + ")"; } } }
src/som/interpreter/nodes/MessageSendNode.java
package som.interpreter.nodes; import som.interpreter.SArguments; import som.interpreter.TruffleCompiler; import som.interpreter.TypesGen; import som.interpreter.nodes.dispatch.AbstractDispatchNode; import som.interpreter.nodes.dispatch.GenericDispatchNode; import som.interpreter.nodes.dispatch.SuperDispatchNode; import som.interpreter.nodes.dispatch.UninitializedDispatchNode; import som.interpreter.nodes.literals.BlockNode; import som.interpreter.nodes.nary.EagerBinaryPrimitiveNode; import som.interpreter.nodes.specialized.IfFalseMessageNodeFactory; import som.interpreter.nodes.specialized.IfTrueIfFalseMessageNodeFactory; import som.interpreter.nodes.specialized.IfTrueMessageNodeFactory; import som.interpreter.nodes.specialized.IntToByDoMessageNodeFactory; import som.interpreter.nodes.specialized.IntToDoMessageNodeFactory; import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileFalseStaticBlocksNode; import som.interpreter.nodes.specialized.WhileWithStaticBlocksNode.WhileTrueStaticBlocksNode; import som.primitives.BlockPrimsFactory.ValueOnePrimFactory; import som.primitives.EqualsEqualsPrimFactory; import som.primitives.EqualsPrimFactory; import som.primitives.arithmetic.AdditionPrimFactory; import som.primitives.arithmetic.LessThanOrEqualPrimFactory; import som.primitives.arithmetic.LessThanPrimFactory; import som.primitives.arithmetic.SubtractionPrimFactory; import som.vm.Universe; import som.vmobjects.SBlock; import som.vmobjects.SSymbol; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.ExplodeLoop; import com.oracle.truffle.api.nodes.NodeInfo; public final class MessageSendNode { public static AbstractMessageSendNode create(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments) { return new UninitializedMessageSendNode(selector, receiver, arguments); } @NodeInfo(shortName = "send") public abstract static class AbstractMessageSendNode extends ExpressionNode implements PreevaluatedExpression { @Child protected ExpressionNode receiverNode; @Children protected final ExpressionNode[] argumentNodes; protected AbstractMessageSendNode(final ExpressionNode receiver, final ExpressionNode[] arguments) { this.receiverNode = adoptChild(receiver); this.argumentNodes = adoptChildren(arguments); } @Override public final Object executeGeneric(final VirtualFrame frame) { Object rcvr = receiverNode.executeGeneric(frame); Object[] arguments = evaluateArguments(frame); return executePreEvaluated(frame, rcvr, arguments); } @ExplodeLoop private Object[] evaluateArguments(final VirtualFrame frame) { Object[] arguments = new Object[argumentNodes.length]; for (int i = 0; i < argumentNodes.length; i++) { arguments[i] = argumentNodes[i].executeGeneric(frame); } return arguments; } } private static final class UninitializedMessageSendNode extends AbstractMessageSendNode { private final SSymbol selector; protected UninitializedMessageSendNode(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments) { super(receiver, arguments); this.selector = selector; } @Override public Object executePreEvaluated(final VirtualFrame frame, final Object receiver, final Object[] arguments) { return specialize(receiver, arguments).executePreEvaluated(frame, receiver, arguments); } private PreevaluatedExpression specialize(final Object receiver, final Object[] arguments) { TruffleCompiler.transferToInterpreterAndInvalidate("Specialize Message Node"); // first option is a super send, super sends are treated specially because // the receiver class is lexically determined if (receiverNode instanceof ISuperReadNode) { GenericMessageSendNode node = new GenericMessageSendNode(selector, receiverNode, argumentNodes, SuperDispatchNode.create(selector, (ISuperReadNode) receiverNode)); return replace(node); } // We treat super sends separately for simplicity, might not be the // optimal solution, especially in cases were the knowledge of the // receiver class also allows us to do more specific things, but for the // moment we will leave it at this. // TODO: revisit, and also do more specific optimizations for super sends. // let's organize the specializations by number of arguments // perhaps not the best, but one simple way to just get some order into // the chaos. switch (argumentNodes.length) { // case 0: return specializeUnary( receiver, arguments); // don't have any at the moment case 1: return specializeBinary(receiver, arguments); case 2: return specializeTernary(receiver, arguments); case 3: return specializeQuaternary(receiver, arguments); } return makeGenericSend(); } private GenericMessageSendNode makeGenericSend() { GenericMessageSendNode send = new GenericMessageSendNode(selector, receiverNode, argumentNodes, new UninitializedDispatchNode(selector, Universe.current())); return replace(send); } private PreevaluatedExpression specializeBinary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "whileTrue:": { if (argumentNodes[0] instanceof BlockNode && receiverNode instanceof BlockNode) { BlockNode argBlockNode = (BlockNode) argumentNodes[0]; SBlock argBlock = (SBlock) arguments[0]; return replace(new WhileTrueStaticBlocksNode( (BlockNode) receiverNode, argBlockNode, (SBlock) receiver, argBlock, Universe.current())); } break; // use normal send } case "whileFalse:": if (argumentNodes[0] instanceof BlockNode && receiverNode instanceof BlockNode) { BlockNode argBlockNode = (BlockNode) argumentNodes[0]; SBlock argBlock = (SBlock) arguments[0]; return replace(new WhileFalseStaticBlocksNode( (BlockNode) receiverNode, argBlockNode, (SBlock) receiver, argBlock, Universe.current())); } break; // use normal send case "ifTrue:": return replace(IfTrueMessageNodeFactory.create(receiver, arguments[0], Universe.current(), receiverNode, argumentNodes[0])); case "ifFalse:": return replace(IfFalseMessageNodeFactory.create(receiver, arguments[0], Universe.current(), receiverNode, argumentNodes[0])); // TODO: find a better way for primitives, use annotation or something case "<": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], LessThanPrimFactory.create(receiverNode, argumentNodes[0]))); case "<=": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], LessThanOrEqualPrimFactory.create(receiverNode, argumentNodes[0]))); case "+": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], AdditionPrimFactory.create(receiverNode, argumentNodes[0]))); case "value:": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], ValueOnePrimFactory.create(receiverNode, argumentNodes[0]))); case "-": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], SubtractionPrimFactory.create(receiverNode, argumentNodes[0]))); case "=": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], EqualsPrimFactory.create(receiverNode, argumentNodes[0]))); case "==": return replace(new EagerBinaryPrimitiveNode(selector, receiverNode, argumentNodes[0], EqualsEqualsPrimFactory.create(receiverNode, argumentNodes[0]))); } return makeGenericSend(); } private PreevaluatedExpression specializeTernary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "ifTrue:ifFalse:": return replace(IfTrueIfFalseMessageNodeFactory.create(receiver, arguments[0], arguments[1], Universe.current(), receiverNode, argumentNodes[0], argumentNodes[1])); case "to:do:": if (TypesGen.TYPES.isImplicitInteger(receiver) && TypesGen.TYPES.isImplicitInteger(arguments[0]) && TypesGen.TYPES.isSBlock(arguments[1])) { return replace(IntToDoMessageNodeFactory.create(this, (SBlock) arguments[1], receiverNode, argumentNodes[0], argumentNodes[1])); } break; } return makeGenericSend(); } } public static final class GenericMessageSendNode extends AbstractMessageSendNode { private final SSymbol selector; public static GenericMessageSendNode create(final SSymbol selector, final ExpressionNode receiverNode, final ExpressionNode[] argumentNodes) { return new GenericMessageSendNode(selector, receiverNode, argumentNodes, new UninitializedDispatchNode(selector, Universe.current())); } @Child private AbstractDispatchNode dispatchNode; private GenericMessageSendNode(final SSymbol selector, final ExpressionNode receiver, final ExpressionNode[] arguments, final AbstractDispatchNode dispatchNode) { super(receiver, arguments); this.selector = selector; this.dispatchNode = adoptChild(dispatchNode); } @Override public Object executePreEvaluated(final VirtualFrame frame, final Object receiver, final Object[] arguments) { SArguments args = new SArguments(receiver, arguments); return dispatchNode.executeDispatch(frame, args); } public void replaceDispatchNodeBecauseCallSiteIsMegaMorphic( final GenericDispatchNode replacement) { dispatchNode.replace(replacement); } @Override public String toString() { return "GMsgSend(" + selector.getString() + ")"; } private PreevaluatedExpression specializeQuaternary(final Object receiver, final Object[] arguments) { switch (selector.getString()) { case "to:by:do:": return replace(IntToByDoMessageNodeFactory.create(this, (SBlock) arguments[2], receiverNode, argumentNodes[0], argumentNodes[1], argumentNodes[2])); } return makeGenericSend(); } } }
Something is really broken in Tower :( Signed-off-by: Stefan Marr <[email protected]>
src/som/interpreter/nodes/MessageSendNode.java
Something is really broken in Tower :(
<ide><path>rc/som/interpreter/nodes/MessageSendNode.java <ide> } <ide> return makeGenericSend(); <ide> } <add> <add> private PreevaluatedExpression specializeQuaternary(final Object receiver, <add> final Object[] arguments) { <add> switch (selector.getString()) { <add> case "to:by:do:": <add> return replace(IntToByDoMessageNodeFactory.create(this, <add> (SBlock) arguments[2], receiverNode, argumentNodes[0], <add> argumentNodes[1], argumentNodes[2])); <add> } <add> return makeGenericSend(); <add> } <ide> } <ide> <ide> public static final class GenericMessageSendNode <ide> public String toString() { <ide> return "GMsgSend(" + selector.getString() + ")"; <ide> } <del> <del> private PreevaluatedExpression specializeQuaternary(final Object receiver, <del> final Object[] arguments) { <del> switch (selector.getString()) { <del> case "to:by:do:": <del> return replace(IntToByDoMessageNodeFactory.create(this, <del> (SBlock) arguments[2], receiverNode, argumentNodes[0], <del> argumentNodes[1], argumentNodes[2])); <del> } <del> return makeGenericSend(); <del> } <ide> } <ide> }
JavaScript
mit
11309201d219465e41b741bd507736343bdf6587
0
elvinyung/epsilon-delta
var utils = require('./utils'); var epsilonDelta = function (configs) { configs = configs || {}; configs.db = configs.db || require('./memoryDB')(); configs.userKey = configs.userKey || 'connection.remoteAddress'; configs.capacity = configs.capacity || 200; configs.expire = configs.expire || 360000; configs.limitResponse = configs.limitResponse || 'Your rate limit has been reached.'; var db = configs.db; // manually set user's data. var manualSet = function (userKey, capacity, expire) { var data = {}; ((typeof capacity == 'object') ? function () { capacity.capacity = capacity.capacity || configs.capacity; capacity.capacity = capacity || configs.expire; data.capacity = capacity.capacity; data.expire = capacity.expire; } : function () { capacity = capacity; data.capacity = capacity; data.expire = expire; })(); db.hmset(userKey, data); }; // check if user still has requests left. var rate = function (userKey, cb) { db.hgetall(userKey, function(err, data) { var now = Date.now(); data = (data ? { capacity: parseInt(data.capacity), expire: parseInt(data.expire) } : { capacity: configs.capacity, expire: now + configs.expire }); // refill bucket if should be refilled before now (data.expire <= now) && function(){ data.capacity = configs.capacity; data.expire = now + configs.expire; }(); // take one from bucket if user still has tokens (data.capacity > 0) && function(){ data.capacity -= 1; }(); // write code here db.hmset(userKey, data); cb(null, data); return data; }); }; // the main limiter middllware. var limiter = function (req, res, next) { var userKey = utils.nestedGet(req, configs.userKey); rate(userKey, function(err, data){ res.set({ 'X-Rate-Limit-Limit': configs.capacity, 'X-Rate-Limit-Remaining': data.capacity, 'X-Rate-Limit-Reset': data.expire - Date.now() }); ((parseInt(data.capacity) > 0) ? next : function () { // if callback exists, call it configs.limitCallback && configs.limitCallback(req, res); (typeof configs.limitResponse == 'object') && res.set('Content-Type', 'application/json'); res.status(429); res.end(JSON.stringify(configs.limitResponse)); })(); }); }; limiter.rate = rate; limiter.manualSet = manualSet; return limiter; } module.exports = epsilonDelta;
lib/limiter.js
var utils = require('./utils'); var epsilonDelta = function (configs) { configs = configs || {}; configs.db = configs.db || require('./memoryDB')(); configs.userKey = configs.userKey || 'connection.remoteAddress'; configs.capacity = configs.capacity || 200; configs.expire = configs.expire || 360000; configs.limitResponse = configs.limitResponse || 'Your rate limit has been reached.'; var db = configs.db; // manually set user's data. var manualSet = function (userKey, capacity, expire) { var data = {}; ((typeof capacity == 'object') ? function () { capacity.capacity = capacity.capacity || configs.capacity; capacity.capacity = capacity || configs.expire; data.capacity = capacity.capacity; data.expire = capacity.expire; } : function () { capacity = capacity; data.capacity = capacity; data.expire = expire; })(); db.hmset(userKey, data); }; // check if user still has requests left. var rate = function (userKey, cb) { db.hgetall(userKey, function(err, data) { var now = Date.now(); data = data || { capacity: configs.capacity, expire: now + configs.expire }; // refill bucket if should be refilled before now (data.expire < now) && function(){ data.capacity = configs.capacity; data.expire = now + configs.expire; }(); // take one from bucket if user still has tokens (data.capacity > 0) && function(){ data.capacity -= 1; }(); // write code here db.hmset(userKey, data); cb(null, data); return data; }); }; // the main limiter middllware. var limiter = function (req, res, next) { var userKey = utils.nestedGet(req, configs.userKey); rate(userKey, function(err, data){ res.set({ 'X-Rate-Limit-Limit': configs.capacity, 'X-Rate-Limit-Remaining': data.capacity, 'X-Rate-Limit-Reset': data.expire - Date.now() }); ((parseInt(data.capacity) > 0) ? next : function () { // if callback exists, call it configs.limitCallback && configs.limitCallback(req, res); (typeof configs.limitResponse == 'object') && res.set('Content-Type', 'application/json'); res.status(429); res.end(JSON.stringify(configs.limitResponse)); })(); }); }; limiter.rate = rate; limiter.manualSet = manualSet; return limiter; } module.exports = epsilonDelta;
redis type casting fix
lib/limiter.js
redis type casting fix
<ide><path>ib/limiter.js <ide> var rate = function (userKey, cb) { <ide> db.hgetall(userKey, function(err, data) { <ide> var now = Date.now(); <del> data = data || { <del> capacity: configs.capacity, <del> expire: now + configs.expire <del> }; <add> data = (data ? <add> { <add> capacity: parseInt(data.capacity), <add> expire: parseInt(data.expire) <add> } : <add> { <add> capacity: configs.capacity, <add> expire: now + configs.expire <add> }); <ide> <ide> // refill bucket if should be refilled before now <del> (data.expire < now) && function(){ <add> (data.expire <= now) && function(){ <ide> data.capacity = configs.capacity; <ide> data.expire = now + configs.expire; <ide> }();
Java
apache-2.0
887616a9e2f071b35ebc975d21e5461ae9b604f2
0
esaunders/autopsy,rcordovano/autopsy,APriestman/autopsy,esaunders/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,APriestman/autopsy,millmanorama/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,millmanorama/autopsy,millmanorama/autopsy,wschaeferB/autopsy,APriestman/autopsy,rcordovano/autopsy,dgrove727/autopsy,APriestman/autopsy,rcordovano/autopsy,dgrove727/autopsy,rcordovano/autopsy,dgrove727/autopsy,millmanorama/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,wschaeferB/autopsy,APriestman/autopsy
/* * Autopsy Forensic Browser * * Copyright 2011-2017 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.datamodel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; import org.openide.nodes.ChildFactory; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.Sheet; import org.openide.util.NbBundle; import org.openide.util.lookup.Lookups; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.core.UserPreferences; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.ingest.IngestManager; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.SleuthkitCase; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskData; /** * Filters database results by file extension. */ public final class FileTypesByExtension implements AutopsyVisitableItem { private final static Logger logger = Logger.getLogger(FileTypesByExtension.class.getName()); private final SleuthkitCase skCase; private final FileTypes typesRoot; public FileTypesByExtension(FileTypes typesRoot) { this.skCase = typesRoot.getSleuthkitCase(); this.typesRoot = typesRoot; } public SleuthkitCase getSleuthkitCase() { return this.skCase; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } /** * Listens for case and ingest invest. Updates observers when events are * fired. FileType and FileTypes nodes are all listening to this. */ private class FileTypesByExtObservable extends Observable { private final PropertyChangeListener pcl; private FileTypesByExtObservable() { super(); this.pcl = (PropertyChangeEvent evt) -> { String eventType = evt.getPropertyName(); if (eventType.equals(IngestManager.IngestModuleEvent.CONTENT_CHANGED.toString()) || eventType.equals(IngestManager.IngestJobEvent.COMPLETED.toString()) || eventType.equals(IngestManager.IngestJobEvent.CANCELLED.toString()) || eventType.equals(Case.Events.DATA_SOURCE_ADDED.toString())) { /** * Checking for a current case is a stop gap measure until a * different way of handling the closing of cases is worked * out. Currently, remote events may be received for a case * that is already closed. */ try { Case.getCurrentCase(); typesRoot.shouldShowCounts(); update(); } catch (IllegalStateException notUsed) { /** * Case is closed, do nothing. */ } } else if (eventType.equals(Case.Events.CURRENT_CASE.toString())) { // case was closed. Remove listeners so that we don't get called with a stale case handle if (evt.getNewValue() == null) { removeListeners(); } } }; IngestManager.getInstance().addIngestJobEventListener(pcl); IngestManager.getInstance().addIngestModuleEventListener(pcl); Case.addPropertyChangeListener(pcl); } private void removeListeners() { deleteObservers(); IngestManager.getInstance().removeIngestJobEventListener(pcl); IngestManager.getInstance().removeIngestModuleEventListener(pcl); Case.removePropertyChangeListener(pcl); } private void update() { setChanged(); notifyObservers(); } } private static final String FNAME = NbBundle.getMessage(FileTypesByExtNode.class, "FileTypesByExtNode.fname.text"); /** * Node for root of file types view. Children are nodes for specific types. */ class FileTypesByExtNode extends DisplayableItemNode { private final FileTypesByExtension.RootFilter filter; /** * * @param skCase * @param filter null to display root node of file type tree, pass in * something to provide a sub-node. */ FileTypesByExtNode(SleuthkitCase skCase, FileTypesByExtension.RootFilter filter) { this(skCase, filter, null); } /** * * @param skCase * @param filter * @param o Observable that was created by a higher-level node that * provides updates on events */ private FileTypesByExtNode(SleuthkitCase skCase, FileTypesByExtension.RootFilter filter, FileTypesByExtObservable o) { super(Children.create(new FileTypesByExtNodeChildren(skCase, filter, o), true), Lookups.singleton(filter == null ? FNAME : filter.getDisplayName())); this.filter = filter; // root node of tree if (filter == null) { super.setName(FNAME); super.setDisplayName(FNAME); } // sub-node in file tree (i.e. documents, exec, etc.) else { super.setName(filter.getDisplayName()); super.setDisplayName(filter.getDisplayName()); } this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file_types.png"); //NON-NLS } @Override public boolean isLeafTypeNode() { return false; } @Override public <T> T accept(DisplayableItemNodeVisitor<T> v) { return v.visit(this); } @Override protected Sheet createSheet() { Sheet s = super.createSheet(); Sheet.Set ss = s.get(Sheet.PROPERTIES); if (ss == null) { ss = Sheet.createPropertiesSet(); s.put(ss); } if (filter != null && (filter.equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER) || filter.equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER))) { String extensions = ""; for (String ext : filter.getFilter()) { extensions += "'" + ext + "', "; } extensions = extensions.substring(0, extensions.lastIndexOf(',')); ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.desc"), extensions)); } else { ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.name.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.name.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.name.desc"), getDisplayName())); } return s; } @Override public String getItemType() { /** * Because Documents and Executable are further expandable, their * column order settings should be stored separately. */ if (filter == null) { return getClass().getName(); } if (filter.equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER) || filter.equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER)) { return getClass().getName() + filter.getName(); } return getClass().getName(); } } private class FileTypesByExtNodeChildren extends ChildFactory<FileTypesByExtension.SearchFilterInterface> { private final SleuthkitCase skCase; private final FileTypesByExtension.RootFilter filter; private final FileTypesByExtObservable notifier; /** * * @param skCase * @param filter Is null for root node * @param o Observable that provides updates based on events being * fired (or null if one needs to be created) */ private FileTypesByExtNodeChildren(SleuthkitCase skCase, FileTypesByExtension.RootFilter filter, FileTypesByExtObservable o) { super(); this.skCase = skCase; this.filter = filter; if (o == null) { this.notifier = new FileTypesByExtObservable(); } else { this.notifier = o; } } @Override protected boolean createKeys(List<FileTypesByExtension.SearchFilterInterface> list) { // root node if (filter == null) { list.addAll(Arrays.asList(FileTypesByExtension.RootFilter.values())); } // document and executable has another level of nodes else if (filter.equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER)) { list.addAll(Arrays.asList(FileTypesByExtension.DocumentFilter.values())); } else if (filter.equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER)) { list.addAll(Arrays.asList(FileTypesByExtension.ExecutableFilter.values())); } return true; } @Override protected Node createNodeForKey(FileTypesByExtension.SearchFilterInterface key) { // make new nodes for the sub-nodes if (key.getName().equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER.getName())) { return new FileTypesByExtNode(skCase, FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER, notifier); } else if (key.getName().equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER.getName())) { return new FileTypesByExtNode(skCase, FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER, notifier); } else { return new FileExtensionNode(key, skCase, notifier); } } } /** * Node for a specific file type / extension. Children of it will be the * files of that type. */ class FileExtensionNode extends FileTypes.BGCountUpdatingNode { private final FileTypesByExtension.SearchFilterInterface filter; /** * * @param filter Extensions that will be shown for this node * @param skCase * @param o Observable that sends updates when the child factories * should refresh */ FileExtensionNode(FileTypesByExtension.SearchFilterInterface filter, SleuthkitCase skCase, FileTypesByExtObservable o) { super(typesRoot, Children.create(new FileExtensionNodeChildren(filter, skCase, o), true), Lookups.singleton(filter.getDisplayName())); this.filter = filter; super.setName(filter.getDisplayName()); updateDisplayName(); this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file-filter-icon.png"); //NON-NLS o.addObserver(this); } @Override public <T> T accept(DisplayableItemNodeVisitor<T> v) { return v.visit(this); } @Override protected Sheet createSheet() { Sheet s = super.createSheet(); Sheet.Set ss = s.get(Sheet.PROPERTIES); if (ss == null) { ss = Sheet.createPropertiesSet(); s.put(ss); } ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.filterType.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.filterType.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.filterType.desc"), filter.getDisplayName())); ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.desc"), String.join(", ", filter.getFilter()))); return s; } @Override public boolean isLeafTypeNode() { return true; } /** * Consider allowing different configurations for Images, Videos, etc * (in which case we'd return getClass().getName() + filter.getName() * for all filters). */ @Override public String getItemType() { return DisplayableItemNode.FILE_PARENT_NODE_KEY; } @Override String getDisplayNameBase() { return filter.getDisplayName(); } @Override long calculateChildCount() throws TskCoreException { return skCase.countFilesWhere(createQuery(filter)); } } private String createQuery(FileTypesByExtension.SearchFilterInterface filter) { if (filter.getFilter().isEmpty()) { // We should never be given a search filter without extensions // but if we are it is clearly a programming error so we throw // an IllegalArgumentException. throw new IllegalArgumentException("Empty filter list passed to createQuery()"); // NON-NLS } String query = "(dir_type = " + TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue() + ")" + (UserPreferences.hideKnownFilesInViewsTree() ? " AND (known IS NULL OR known != " + TskData.FileKnown.KNOWN.getFileKnownValue() + ")" : " ") + " AND (NULL "; //NON-NLS if (skCase.getDatabaseType().equals(TskData.DbType.POSTGRESQL)) { // For PostgreSQL we get a more efficient query by using builtin // regular expression support and or'ing all extensions. We also // escape the dot at the beginning of the extension. // We will end up with a query that looks something like this: // OR LOWER(name) ~ '(\.zip|\.rar|\.7zip|\.cab|\.jar|\.cpio|\.ar|\.gz|\.tgz|\.bz2)$') query += "OR LOWER(name) ~ '(\\"; query += StringUtils.join(filter.getFilter().stream() .map(String::toLowerCase).collect(Collectors.toList()), "|\\"); query += ")$'"; } else { for (String s : filter.getFilter()) { query += "OR LOWER(name) LIKE '%" + s.toLowerCase() + "'"; // NON-NLS } } query += ')'; return query; } /** * Child node factory for a specific file type - does the database query. */ private class FileExtensionNodeChildren extends ChildFactory.Detachable<Content> implements Observer { private final SleuthkitCase skCase; private final FileTypesByExtension.SearchFilterInterface filter; private final Observable notifier; /** * * @param filter Extensions to display * @param skCase * @param o Observable that will notify when there could be new * data to display */ private FileExtensionNodeChildren(FileTypesByExtension.SearchFilterInterface filter, SleuthkitCase skCase, Observable o) { super(); this.filter = filter; this.skCase = skCase; notifier = o; } @Override protected void addNotify() { if (notifier != null) { notifier.addObserver(this); } } @Override protected void removeNotify() { if (notifier != null) { notifier.deleteObserver(this); } } @Override public void update(Observable o, Object arg) { refresh(true); } @Override protected boolean createKeys(List<Content> list) { try { list.addAll(skCase.findAllFilesWhere(createQuery(filter))); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Couldn't get search results", ex); //NON-NLS } return true; } @Override protected Node createNodeForKey(Content key) { return key.accept(new FileTypes.FileNodeCreationVisitor()); } } // root node filters public static enum RootFilter implements AutopsyVisitableItem, SearchFilterInterface { TSK_IMAGE_FILTER(0, "TSK_IMAGE_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskImgFilter.text"), FileTypeExtensions.getImageExtensions()), TSK_VIDEO_FILTER(1, "TSK_VIDEO_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskVideoFilter.text"), FileTypeExtensions.getVideoExtensions()), TSK_AUDIO_FILTER(2, "TSK_AUDIO_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskAudioFilter.text"), FileTypeExtensions.getAudioExtensions()), TSK_ARCHIVE_FILTER(3, "TSK_ARCHIVE_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskArchiveFilter.text"), FileTypeExtensions.getArchiveExtensions()), TSK_DOCUMENT_FILTER(3, "TSK_DOCUMENT_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskDocumentFilter.text"), Arrays.asList(".htm", ".html", ".doc", ".docx", ".odt", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".rtf")), //NON-NLS TSK_EXECUTABLE_FILTER(3, "TSK_EXECUTABLE_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskExecFilter.text"), FileTypeExtensions.getExecutableExtensions()); //NON-NLS private final int id; private final String name; private final String displayName; private final List<String> filter; private RootFilter(int id, String name, String displayName, List<String> filter) { this.id = id; this.name = name; this.displayName = displayName; this.filter = filter; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } @Override public String getName() { return this.name; } @Override public int getId() { return this.id; } @Override public String getDisplayName() { return this.displayName; } @Override public List<String> getFilter() { return this.filter; } } // document sub-node filters public static enum DocumentFilter implements AutopsyVisitableItem, SearchFilterInterface { AUT_DOC_HTML(0, "AUT_DOC_HTML", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocHtmlFilter.text"), Arrays.asList(".htm", ".html")), //NON-NLS AUT_DOC_OFFICE(1, "AUT_DOC_OFFICE", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocOfficeFilter.text"), Arrays.asList(".doc", ".docx", ".odt", ".xls", ".xlsx", ".ppt", ".pptx")), //NON-NLS AUT_DOC_PDF(2, "AUT_DOC_PDF", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autoDocPdfFilter.text"), Arrays.asList(".pdf")), //NON-NLS AUT_DOC_TXT(3, "AUT_DOC_TXT", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocTxtFilter.text"), Arrays.asList(".txt")), //NON-NLS AUT_DOC_RTF(4, "AUT_DOC_RTF", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocRtfFilter.text"), Arrays.asList(".rtf")); //NON-NLS private final int id; private final String name; private final String displayName; private final List<String> filter; private DocumentFilter(int id, String name, String displayName, List<String> filter) { this.id = id; this.name = name; this.displayName = displayName; this.filter = filter; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } @Override public String getName() { return this.name; } @Override public int getId() { return this.id; } @Override public String getDisplayName() { return this.displayName; } @Override public List<String> getFilter() { return this.filter; } } // executable sub-node filters public static enum ExecutableFilter implements AutopsyVisitableItem, SearchFilterInterface { ExecutableFilter_EXE(0, "ExecutableFilter_EXE", ".exe", Arrays.asList(".exe")), //NON-NLS ExecutableFilter_DLL(1, "ExecutableFilter_DLL", ".dll", Arrays.asList(".dll")), //NON-NLS ExecutableFilter_BAT(2, "ExecutableFilter_BAT", ".bat", Arrays.asList(".bat")), //NON-NLS ExecutableFilter_CMD(3, "ExecutableFilter_CMD", ".cmd", Arrays.asList(".cmd")), //NON-NLS ExecutableFilter_COM(4, "ExecutableFilter_COM", ".com", Arrays.asList(".com")); //NON-NLS private final int id; private final String name; private final String displayName; private final List<String> filter; private ExecutableFilter(int id, String name, String displayName, List<String> filter) { this.id = id; this.name = name; this.displayName = displayName; this.filter = filter; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } @Override public String getName() { return this.name; } @Override public int getId() { return this.id; } @Override public String getDisplayName() { return this.displayName; } @Override public List<String> getFilter() { return this.filter; } } interface SearchFilterInterface { public String getName(); public int getId(); public String getDisplayName(); public List<String> getFilter(); } }
Core/src/org/sleuthkit/autopsy/datamodel/FileTypesByExtension.java
/* * Autopsy Forensic Browser * * Copyright 2011-2017 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.datamodel; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.logging.Level; import org.apache.commons.lang.StringUtils; import org.openide.nodes.ChildFactory; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.nodes.Sheet; import org.openide.util.NbBundle; import org.openide.util.lookup.Lookups; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.core.UserPreferences; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.ingest.IngestManager; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.SleuthkitCase; import org.sleuthkit.datamodel.TskCoreException; import org.sleuthkit.datamodel.TskData; /** * Filters database results by file extension. */ public final class FileTypesByExtension implements AutopsyVisitableItem { private final static Logger logger = Logger.getLogger(FileTypesByExtension.class.getName()); private final SleuthkitCase skCase; private final FileTypes typesRoot; public FileTypesByExtension(FileTypes typesRoot) { this.skCase = typesRoot.getSleuthkitCase(); this.typesRoot = typesRoot; } public SleuthkitCase getSleuthkitCase() { return this.skCase; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } /** * Listens for case and ingest invest. Updates observers when events are * fired. FileType and FileTypes nodes are all listening to this. */ private class FileTypesByExtObservable extends Observable { private final PropertyChangeListener pcl; private FileTypesByExtObservable() { super(); this.pcl = (PropertyChangeEvent evt) -> { String eventType = evt.getPropertyName(); if (eventType.equals(IngestManager.IngestModuleEvent.CONTENT_CHANGED.toString()) || eventType.equals(IngestManager.IngestJobEvent.COMPLETED.toString()) || eventType.equals(IngestManager.IngestJobEvent.CANCELLED.toString()) || eventType.equals(Case.Events.DATA_SOURCE_ADDED.toString())) { /** * Checking for a current case is a stop gap measure until a * different way of handling the closing of cases is worked * out. Currently, remote events may be received for a case * that is already closed. */ try { Case.getCurrentCase(); typesRoot.shouldShowCounts(); update(); } catch (IllegalStateException notUsed) { /** * Case is closed, do nothing. */ } } else if (eventType.equals(Case.Events.CURRENT_CASE.toString())) { // case was closed. Remove listeners so that we don't get called with a stale case handle if (evt.getNewValue() == null) { removeListeners(); } } }; IngestManager.getInstance().addIngestJobEventListener(pcl); IngestManager.getInstance().addIngestModuleEventListener(pcl); Case.addPropertyChangeListener(pcl); } private void removeListeners() { deleteObservers(); IngestManager.getInstance().removeIngestJobEventListener(pcl); IngestManager.getInstance().removeIngestModuleEventListener(pcl); Case.removePropertyChangeListener(pcl); } private void update() { setChanged(); notifyObservers(); } } private static final String FNAME = NbBundle.getMessage(FileTypesByExtNode.class, "FileTypesByExtNode.fname.text"); /** * Node for root of file types view. Children are nodes for specific types. */ class FileTypesByExtNode extends DisplayableItemNode { private final FileTypesByExtension.RootFilter filter; /** * * @param skCase * @param filter null to display root node of file type tree, pass in * something to provide a sub-node. */ FileTypesByExtNode(SleuthkitCase skCase, FileTypesByExtension.RootFilter filter) { this(skCase, filter, null); } /** * * @param skCase * @param filter * @param o Observable that was created by a higher-level node that * provides updates on events */ private FileTypesByExtNode(SleuthkitCase skCase, FileTypesByExtension.RootFilter filter, FileTypesByExtObservable o) { super(Children.create(new FileTypesByExtNodeChildren(skCase, filter, o), true), Lookups.singleton(filter == null ? FNAME : filter.getDisplayName())); this.filter = filter; // root node of tree if (filter == null) { super.setName(FNAME); super.setDisplayName(FNAME); } // sub-node in file tree (i.e. documents, exec, etc.) else { super.setName(filter.getDisplayName()); super.setDisplayName(filter.getDisplayName()); } this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file_types.png"); //NON-NLS } @Override public boolean isLeafTypeNode() { return false; } @Override public <T> T accept(DisplayableItemNodeVisitor<T> v) { return v.visit(this); } @Override protected Sheet createSheet() { Sheet s = super.createSheet(); Sheet.Set ss = s.get(Sheet.PROPERTIES); if (ss == null) { ss = Sheet.createPropertiesSet(); s.put(ss); } if (filter != null && (filter.equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER) || filter.equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER))) { String extensions = ""; for (String ext : filter.getFilter()) { extensions += "'" + ext + "', "; } extensions = extensions.substring(0, extensions.lastIndexOf(',')); ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.desc"), extensions)); } else { ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.name.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.name.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.name.desc"), getDisplayName())); } return s; } @Override public String getItemType() { /** * Because Documents and Executable are further expandable, their * column order settings should be stored separately. */ if (filter == null) { return getClass().getName(); } if (filter.equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER) || filter.equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER)) { return getClass().getName() + filter.getName(); } return getClass().getName(); } } private class FileTypesByExtNodeChildren extends ChildFactory<FileTypesByExtension.SearchFilterInterface> { private final SleuthkitCase skCase; private final FileTypesByExtension.RootFilter filter; private final FileTypesByExtObservable notifier; /** * * @param skCase * @param filter Is null for root node * @param o Observable that provides updates based on events being * fired (or null if one needs to be created) */ private FileTypesByExtNodeChildren(SleuthkitCase skCase, FileTypesByExtension.RootFilter filter, FileTypesByExtObservable o) { super(); this.skCase = skCase; this.filter = filter; if (o == null) { this.notifier = new FileTypesByExtObservable(); } else { this.notifier = o; } } @Override protected boolean createKeys(List<FileTypesByExtension.SearchFilterInterface> list) { // root node if (filter == null) { list.addAll(Arrays.asList(FileTypesByExtension.RootFilter.values())); } // document and executable has another level of nodes else if (filter.equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER)) { list.addAll(Arrays.asList(FileTypesByExtension.DocumentFilter.values())); } else if (filter.equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER)) { list.addAll(Arrays.asList(FileTypesByExtension.ExecutableFilter.values())); } return true; } @Override protected Node createNodeForKey(FileTypesByExtension.SearchFilterInterface key) { // make new nodes for the sub-nodes if (key.getName().equals(FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER.getName())) { return new FileTypesByExtNode(skCase, FileTypesByExtension.RootFilter.TSK_DOCUMENT_FILTER, notifier); } else if (key.getName().equals(FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER.getName())) { return new FileTypesByExtNode(skCase, FileTypesByExtension.RootFilter.TSK_EXECUTABLE_FILTER, notifier); } else { return new FileExtensionNode(key, skCase, notifier); } } } /** * Node for a specific file type / extension. Children of it will be the * files of that type. */ class FileExtensionNode extends FileTypes.BGCountUpdatingNode { private final FileTypesByExtension.SearchFilterInterface filter; /** * * @param filter Extensions that will be shown for this node * @param skCase * @param o Observable that sends updates when the child factories * should refresh */ FileExtensionNode(FileTypesByExtension.SearchFilterInterface filter, SleuthkitCase skCase, FileTypesByExtObservable o) { super(typesRoot, Children.create(new FileExtensionNodeChildren(filter, skCase, o), true), Lookups.singleton(filter.getDisplayName())); this.filter = filter; super.setName(filter.getDisplayName()); updateDisplayName(); this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file-filter-icon.png"); //NON-NLS o.addObserver(this); } @Override public <T> T accept(DisplayableItemNodeVisitor<T> v) { return v.visit(this); } @Override protected Sheet createSheet() { Sheet s = super.createSheet(); Sheet.Set ss = s.get(Sheet.PROPERTIES); if (ss == null) { ss = Sheet.createPropertiesSet(); s.put(ss); } ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.filterType.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.filterType.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.filterType.desc"), filter.getDisplayName())); ss.put(new NodeProperty<>(NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.name"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.displayName"), NbBundle.getMessage(this.getClass(), "FileTypesByExtNode.createSheet.fileExt.desc"), String.join(", ", filter.getFilter()))); return s; } @Override public boolean isLeafTypeNode() { return true; } /** * Consider allowing different configurations for Images, Videos, etc * (in which case we'd return getClass().getName() + filter.getName() * for all filters). */ @Override public String getItemType() { return DisplayableItemNode.FILE_PARENT_NODE_KEY; } @Override String getDisplayNameBase() { return filter.getDisplayName(); } @Override long calculateChildCount() throws TskCoreException { return skCase.countFilesWhere(createQuery(filter)); } } private String createQuery(FileTypesByExtension.SearchFilterInterface filter) { if (filter.getFilter().isEmpty()) { return ""; } String query = "(dir_type = " + TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue() + ")" + (UserPreferences.hideKnownFilesInViewsTree() ? " AND (known IS NULL OR known != " + TskData.FileKnown.KNOWN.getFileKnownValue() + ")" : " ") + " AND (NULL "; //NON-NLS if (skCase.getDatabaseType().equals(TskData.DbType.POSTGRESQL)) { // For PostgreSQL we get a more efficient query by using builtin // regular expression support and or'ing all extensions. We also // escape the dot at the beginning of the extension. // We will end up with a query that looks something like this: // OR LOWER(name) ~ '(\.zip|\.rar|\.7zip|\.cab|\.jar|\.cpio|\.ar|\.gz|\.tgz|\.bz2)$') query += "OR LOWER(name) ~ '(\\"; query += StringUtils.join(filter.getFilter(), "|\\"); query += ")$'"; } else { for (String s : filter.getFilter()) { query += "OR LOWER(name) LIKE '%" + s.toLowerCase() + "'"; // NON-NLS } } query += ')'; return query; } /** * Child node factory for a specific file type - does the database query. */ private class FileExtensionNodeChildren extends ChildFactory.Detachable<Content> implements Observer { private final SleuthkitCase skCase; private final FileTypesByExtension.SearchFilterInterface filter; private final Observable notifier; /** * * @param filter Extensions to display * @param skCase * @param o Observable that will notify when there could be new * data to display */ private FileExtensionNodeChildren(FileTypesByExtension.SearchFilterInterface filter, SleuthkitCase skCase, Observable o) { super(); this.filter = filter; this.skCase = skCase; notifier = o; } @Override protected void addNotify() { if (notifier != null) { notifier.addObserver(this); } } @Override protected void removeNotify() { if (notifier != null) { notifier.deleteObserver(this); } } @Override public void update(Observable o, Object arg) { refresh(true); } @Override protected boolean createKeys(List<Content> list) { try { list.addAll(skCase.findAllFilesWhere(createQuery(filter))); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Couldn't get search results", ex); //NON-NLS } return true; } @Override protected Node createNodeForKey(Content key) { return key.accept(new FileTypes.FileNodeCreationVisitor()); } } // root node filters public static enum RootFilter implements AutopsyVisitableItem, SearchFilterInterface { TSK_IMAGE_FILTER(0, "TSK_IMAGE_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskImgFilter.text"), FileTypeExtensions.getImageExtensions()), TSK_VIDEO_FILTER(1, "TSK_VIDEO_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskVideoFilter.text"), FileTypeExtensions.getVideoExtensions()), TSK_AUDIO_FILTER(2, "TSK_AUDIO_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskAudioFilter.text"), FileTypeExtensions.getAudioExtensions()), TSK_ARCHIVE_FILTER(3, "TSK_ARCHIVE_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskArchiveFilter.text"), FileTypeExtensions.getArchiveExtensions()), TSK_DOCUMENT_FILTER(3, "TSK_DOCUMENT_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskDocumentFilter.text"), Arrays.asList(".htm", ".html", ".doc", ".docx", ".odt", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".rtf")), //NON-NLS TSK_EXECUTABLE_FILTER(3, "TSK_EXECUTABLE_FILTER", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.tskExecFilter.text"), FileTypeExtensions.getExecutableExtensions()); //NON-NLS private final int id; private final String name; private final String displayName; private final List<String> filter; private RootFilter(int id, String name, String displayName, List<String> filter) { this.id = id; this.name = name; this.displayName = displayName; this.filter = filter; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } @Override public String getName() { return this.name; } @Override public int getId() { return this.id; } @Override public String getDisplayName() { return this.displayName; } @Override public List<String> getFilter() { return this.filter; } } // document sub-node filters public static enum DocumentFilter implements AutopsyVisitableItem, SearchFilterInterface { AUT_DOC_HTML(0, "AUT_DOC_HTML", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocHtmlFilter.text"), Arrays.asList(".htm", ".html")), //NON-NLS AUT_DOC_OFFICE(1, "AUT_DOC_OFFICE", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocOfficeFilter.text"), Arrays.asList(".doc", ".docx", ".odt", ".xls", ".xlsx", ".ppt", ".pptx")), //NON-NLS AUT_DOC_PDF(2, "AUT_DOC_PDF", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autoDocPdfFilter.text"), Arrays.asList(".pdf")), //NON-NLS AUT_DOC_TXT(3, "AUT_DOC_TXT", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocTxtFilter.text"), Arrays.asList(".txt")), //NON-NLS AUT_DOC_RTF(4, "AUT_DOC_RTF", //NON-NLS NbBundle.getMessage(FileTypesByExtension.class, "FileTypeExtensionFilters.autDocRtfFilter.text"), Arrays.asList(".rtf")); //NON-NLS private final int id; private final String name; private final String displayName; private final List<String> filter; private DocumentFilter(int id, String name, String displayName, List<String> filter) { this.id = id; this.name = name; this.displayName = displayName; this.filter = filter; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } @Override public String getName() { return this.name; } @Override public int getId() { return this.id; } @Override public String getDisplayName() { return this.displayName; } @Override public List<String> getFilter() { return this.filter; } } // executable sub-node filters public static enum ExecutableFilter implements AutopsyVisitableItem, SearchFilterInterface { ExecutableFilter_EXE(0, "ExecutableFilter_EXE", ".exe", Arrays.asList(".exe")), //NON-NLS ExecutableFilter_DLL(1, "ExecutableFilter_DLL", ".dll", Arrays.asList(".dll")), //NON-NLS ExecutableFilter_BAT(2, "ExecutableFilter_BAT", ".bat", Arrays.asList(".bat")), //NON-NLS ExecutableFilter_CMD(3, "ExecutableFilter_CMD", ".cmd", Arrays.asList(".cmd")), //NON-NLS ExecutableFilter_COM(4, "ExecutableFilter_COM", ".com", Arrays.asList(".com")); //NON-NLS private final int id; private final String name; private final String displayName; private final List<String> filter; private ExecutableFilter(int id, String name, String displayName, List<String> filter) { this.id = id; this.name = name; this.displayName = displayName; this.filter = filter; } @Override public <T> T accept(AutopsyItemVisitor<T> v) { return v.visit(this); } @Override public String getName() { return this.name; } @Override public int getId() { return this.id; } @Override public String getDisplayName() { return this.displayName; } @Override public List<String> getFilter() { return this.filter; } } interface SearchFilterInterface { public String getName(); public int getId(); public String getDisplayName(); public List<String> getFilter(); } }
Addressed review comments.
Core/src/org/sleuthkit/autopsy/datamodel/FileTypesByExtension.java
Addressed review comments.
<ide><path>ore/src/org/sleuthkit/autopsy/datamodel/FileTypesByExtension.java <ide> import java.util.Observable; <ide> import java.util.Observer; <ide> import java.util.logging.Level; <add>import java.util.stream.Collectors; <ide> import org.apache.commons.lang.StringUtils; <ide> import org.openide.nodes.ChildFactory; <ide> import org.openide.nodes.Children; <ide> <ide> private String createQuery(FileTypesByExtension.SearchFilterInterface filter) { <ide> if (filter.getFilter().isEmpty()) { <del> return ""; <add> // We should never be given a search filter without extensions <add> // but if we are it is clearly a programming error so we throw <add> // an IllegalArgumentException. <add> throw new IllegalArgumentException("Empty filter list passed to createQuery()"); // NON-NLS <ide> } <ide> <ide> String query = "(dir_type = " + TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue() + ")" <ide> // We will end up with a query that looks something like this: <ide> // OR LOWER(name) ~ '(\.zip|\.rar|\.7zip|\.cab|\.jar|\.cpio|\.ar|\.gz|\.tgz|\.bz2)$') <ide> query += "OR LOWER(name) ~ '(\\"; <del> query += StringUtils.join(filter.getFilter(), "|\\"); <add> query += StringUtils.join(filter.getFilter().stream() <add> .map(String::toLowerCase).collect(Collectors.toList()), "|\\"); <ide> query += ")$'"; <ide> } else { <ide> for (String s : filter.getFilter()) {
Java
apache-2.0
95568bd4275e10b49a30064d013865ead1ab5135
0
manovotn/core,antoinesd/weld-core,manovotn/core,antoinesd/weld-core,antoinesd/weld-core,weld/core,weld/core,manovotn/core
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.ejb; import java.io.ObjectStreamException; import java.io.Serializable; import javax.interceptor.InvocationContext; import org.jboss.weld.Container; import org.jboss.weld.bootstrap.api.helpers.RegistrySingletonProvider; import org.jboss.weld.context.ejb.EjbRequestContext; import org.jboss.weld.manager.BeanManagerImpl; /** * Interceptor for ensuring the request context is active during requests to EJBs. * <p/> * Normally, a servlet will start the request context, however in non-servlet * requests (e.g. MDB, async, timeout) the contexts may need starting. * <p/> * The Application context is active for duration of the deployment * * @author Pete Muir */ public class SessionBeanInterceptor extends AbstractEJBRequestScopeActivationInterceptor implements Serializable { private static final long serialVersionUID = 2658712435730329384L; private volatile BeanManagerImpl beanManager; private volatile transient EjbRequestContext ejbRequestContext; @Override public Object aroundInvoke(InvocationContext invocation) throws Exception { if (beanManager == null) { this.beanManager = obtainBeanManager(invocation); this.ejbRequestContext = getEjbRequestContext(); } return super.aroundInvoke(invocation); } private BeanManagerImpl obtainBeanManager(InvocationContext invocation) { Object value = invocation.getContextData().get(Container.CONTEXT_ID_KEY); String contextId = RegistrySingletonProvider.STATIC_INSTANCE; if (value instanceof String) { contextId = (String) value; } return Container.instance(contextId).deploymentManager(); } @Override protected EjbRequestContext getEjbRequestContext() { return ejbRequestContext; } @Override protected BeanManagerImpl getBeanManager() { return beanManager; } private Object readResolve() throws ObjectStreamException { return new SessionBeanInterceptor(); } }
impl/src/main/java/org/jboss/weld/ejb/SessionBeanInterceptor.java
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.ejb; import java.io.ObjectStreamException; import java.io.Serializable; import org.jboss.weld.Container; import org.jboss.weld.context.ejb.EjbRequestContext; import org.jboss.weld.manager.BeanManagerImpl; /** * Interceptor for ensuring the request context is active during requests to EJBs. * <p/> * Normally, a servlet will start the request context, however in non-servlet * requests (e.g. MDB, async, timeout) the contexts may need starting. * <p/> * The Application context is active for duration of the deployment * * @author Pete Muir */ public class SessionBeanInterceptor extends AbstractEJBRequestScopeActivationInterceptor implements Serializable { private static final long serialVersionUID = 2658712435730329384L; private final BeanManagerImpl beanManager; private final transient EjbRequestContext ejbRequestContext; public SessionBeanInterceptor() { this.beanManager = Container.instance().deploymentManager(); this.ejbRequestContext = super.getEjbRequestContext(); } @Override protected EjbRequestContext getEjbRequestContext() { return ejbRequestContext; } @Override protected BeanManagerImpl getBeanManager() { return beanManager; } private Object readResolve() throws ObjectStreamException { return new SessionBeanInterceptor(); } }
WELD-1476 Eliminate Container.instance() usage
impl/src/main/java/org/jboss/weld/ejb/SessionBeanInterceptor.java
WELD-1476 Eliminate Container.instance() usage
<ide><path>mpl/src/main/java/org/jboss/weld/ejb/SessionBeanInterceptor.java <ide> import java.io.ObjectStreamException; <ide> import java.io.Serializable; <ide> <add>import javax.interceptor.InvocationContext; <add> <ide> import org.jboss.weld.Container; <add>import org.jboss.weld.bootstrap.api.helpers.RegistrySingletonProvider; <ide> import org.jboss.weld.context.ejb.EjbRequestContext; <ide> import org.jboss.weld.manager.BeanManagerImpl; <ide> <ide> <ide> private static final long serialVersionUID = 2658712435730329384L; <ide> <del> private final BeanManagerImpl beanManager; <del> private final transient EjbRequestContext ejbRequestContext; <add> private volatile BeanManagerImpl beanManager; <add> private volatile transient EjbRequestContext ejbRequestContext; <ide> <del> public SessionBeanInterceptor() { <del> this.beanManager = Container.instance().deploymentManager(); <del> this.ejbRequestContext = super.getEjbRequestContext(); <add> @Override <add> public Object aroundInvoke(InvocationContext invocation) throws Exception { <add> if (beanManager == null) { <add> this.beanManager = obtainBeanManager(invocation); <add> this.ejbRequestContext = getEjbRequestContext(); <add> } <add> return super.aroundInvoke(invocation); <add> } <add> <add> private BeanManagerImpl obtainBeanManager(InvocationContext invocation) { <add> Object value = invocation.getContextData().get(Container.CONTEXT_ID_KEY); <add> String contextId = RegistrySingletonProvider.STATIC_INSTANCE; <add> if (value instanceof String) { <add> contextId = (String) value; <add> } <add> return Container.instance(contextId).deploymentManager(); <ide> } <ide> <ide> @Override
Java
apache-2.0
8ce2ebbb0437fbd1b502ff0d44528ac4b902cc4e
0
escowles/fcrepo4,lsitu/fcrepo4,peichman-umd/fcrepo4,lsitu/fcrepo4,sprater/fcrepo4,whikloj/fcrepo4,mohideen/fcrepo4,nianma/fcrepo4,ychouloute/fcrepo4,whikloj/fcrepo4,dbernstein/fcrepo4,whikloj/fcrepo4,medusa-project/fcrepo4,medusa-project/fcrepo4,bseeger/fcrepo4,emetsger/fcrepo4,ruebot/fcrepo4,bbranan/fcrepo4,peichman-umd/fcrepo4,ajs6f/fcrepo4,bbranan/fcrepo4,yinlinchen/fcrepo4,ruebot/fcrepo4,whikloj/fcrepo4,mikedurbin/fcrepo4,bseeger/fcrepo4,mikedurbin/fcrepo4,peichman-umd/fcrepo4,robyj/fcrepo4,barmintor/fcrepo4,sprater/fcrepo4,bbranan/fcrepo4,lsitu/fcrepo4,mohideen/fcrepo4,nianma/fcrepo4,yinlinchen/fcrepo4,ruebot/fcrepo4,awoods/fcrepo4,escowles/fcrepo4,robyj/fcrepo4,emetsger/fcrepo4,barmintor/fcrepo4,yinlinchen/fcrepo4,dbernstein/fcrepo4,nianma/fcrepo4,mohideen/fcrepo4,ychouloute/fcrepo4,fcrepo4/fcrepo4,fcrepo4/fcrepo4,medusa-project/fcrepo4,dbernstein/fcrepo4,emetsger/fcrepo4,bseeger/fcrepo4,robyj/fcrepo4,escowles/fcrepo4,robyj/fcrepo4,fcrepo4/fcrepo4,ychouloute/fcrepo4,ajs6f/fcrepo4,awoods/fcrepo4,awoods/fcrepo4,sprater/fcrepo4
package org.fcrepo.utils; import static com.google.common.base.Preconditions.checkArgument; import static org.fcrepo.utils.FedoraJcrTypes.FCR_CONTENT; import static org.slf4j.LoggerFactory.getLogger; import java.util.Set; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.version.Version; import javax.jcr.version.VersionHistory; import javax.jcr.version.VersionIterator; import org.fcrepo.rdf.GraphSubjects; import org.fcrepo.services.LowLevelStorageService; import org.modeshape.jcr.api.JcrConstants; import org.modeshape.jcr.api.NamespaceRegistry; import org.slf4j.Logger; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.hp.hpl.jena.datatypes.RDFDatatype; import com.hp.hpl.jena.datatypes.xsd.XSDDateTime; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; public abstract class JcrRdfTools { private static final Logger logger = getLogger(JcrRdfTools.class); public static BiMap<String, String> jcrNamespacesToRDFNamespaces = ImmutableBiMap.of( "http://www.jcp.org/jcr/1.0", "info:fedora/fedora-system:def/internal#" ); public static BiMap<String, String> rdfNamespacesToJcrNamespaces = jcrNamespacesToRDFNamespaces.inverse(); /** * Convert a Fedora RDF Namespace into its JCR equivalent * @param rdfNamespaceUri a namespace from an RDF document * @return the JCR namespace, or the RDF namespace if no matching JCR namespace is found */ public static String getJcrNamespaceForRDFNamespace(final String rdfNamespaceUri) { if (rdfNamespacesToJcrNamespaces.containsKey(rdfNamespaceUri)) { return rdfNamespacesToJcrNamespaces.get(rdfNamespaceUri); } else { return rdfNamespaceUri; } } /** * Convert a JCR namespace into an RDF namespace fit for downstream consumption * @param jcrNamespaceUri a namespace from the JCR NamespaceRegistry * @return an RDF namespace for downstream consumption. */ public static String getRDFNamespaceForJcrNamespace(final String jcrNamespaceUri) { if (jcrNamespacesToRDFNamespaces.containsKey(jcrNamespaceUri)) { return jcrNamespacesToRDFNamespaces.get(jcrNamespaceUri); } else { return jcrNamespaceUri; } } /** * Translate a JCR node into an RDF Resource * @param node * @return an RDF URI resource * @throws RepositoryException */ public static Resource getGraphSubject(final GraphSubjects factory, final Node node) throws RepositoryException { return factory.getGraphSubject(node); } /** * Translate an RDF resource into a JCR node * @param session * @param subject an RDF URI resource * @return a JCR node, or null if one couldn't be found * @throws RepositoryException */ public static Node getNodeFromGraphSubject(final GraphSubjects factory, final Session session, final Resource subject) throws RepositoryException { return factory.getNodeFromGraphSubject(session, subject); } /** * Predicate for determining whether this {@link Node} is a Fedora object. */ public static boolean isFedoraGraphSubject(final GraphSubjects factory, final Resource subject) { return factory.isFedoraGraphSubject(subject); } private static Model createDefaultJcrModel(final Session session) throws RepositoryException { final Model model = ModelFactory.createDefaultModel(); final javax.jcr.NamespaceRegistry namespaceRegistry = NamespaceTools.getNamespaceRegistry(session); assert(namespaceRegistry != null); for (final String prefix : namespaceRegistry.getPrefixes()) { final String nsURI = namespaceRegistry.getURI(prefix); if (nsURI != null && !nsURI.equals("") && !prefix.equals("xmlns")) { if (prefix.equals("jcr")) { model.setNsPrefix("fedora-internal", getRDFNamespaceForJcrNamespace(nsURI)); } else { model.setNsPrefix(prefix, getRDFNamespaceForJcrNamespace(nsURI)); } } } return model; } /** * Get an RDF Model for a node that includes all its own JCR properties, as well as the properties of its * immediate children. * * @param node * @return * @throws RepositoryException */ public static Model getJcrPropertiesModel( final GraphSubjects factory, final Node node) throws RepositoryException { final Model model = createDefaultJcrModel(node.getSession()); addJcrPropertiesToModel(factory, node, model); addJcrTreePropertiesToModel(factory, node, model); if (node.hasNode(JcrConstants.JCR_CONTENT)) { addJcrContentLocationInformationToModel(factory, node, model); } return model; } private static void addJcrContentLocationInformationToModel( final GraphSubjects factory, final Node node, final Model model) throws RepositoryException { final Node contentNode = node.getNode(JcrConstants.JCR_CONTENT); final Resource contentNodeSubject = factory.getGraphSubject(contentNode); // TODO: get this from somewhere else. LowLevelStorageService llstore = new LowLevelStorageService(); llstore.setRepository(node.getSession().getRepository()); final Set<LowLevelCacheEntry> cacheEntries = llstore.getLowLevelCacheEntries(node); for (LowLevelCacheEntry e : cacheEntries) { model.add(contentNodeSubject, model.createProperty("info:fedora/fedora-system:def/internal#hasLocation"), e.getExternalIdentifier()); } } /** * Add the properties of a Node's parent and immediate children (as well as the jcr:content of children) to the given * RDF model * * @param node * @param model * @throws RepositoryException */ private static void addJcrTreePropertiesToModel( final GraphSubjects factory, final Node node, final Model model) throws RepositoryException { final Resource subject = getGraphSubject(factory, node); // don't do this if the node is the root node. if (node.getDepth() != 0) { final Node parentNode = node.getParent(); model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasParent"), getGraphSubject(factory, parentNode)); addJcrPropertiesToModel(factory, parentNode, model); } final javax.jcr.NodeIterator nodeIterator = node.getNodes(); long excludedNodes = 0L; while (nodeIterator.hasNext()) { final Node childNode = nodeIterator.nextNode(); if (FedoraTypesUtils.isInternalNode.apply(childNode)) { excludedNodes += 1; continue; } final Resource childNodeSubject = getGraphSubject(factory, childNode); addJcrPropertiesToModel(factory, childNode, model); if (childNode.getName().equals(JcrConstants.JCR_CONTENT)) { model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasContent"), childNodeSubject); model.add(childNodeSubject, model.createProperty("info:fedora/fedora-system:def/internal#isContentOf"), subject); excludedNodes += 1; } else { model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasChild"), childNodeSubject); model.add(childNodeSubject, model.createProperty("info:fedora/fedora-system:def/internal#hasParent"), subject); } // always include the jcr:content node information if (childNode.hasNode(JcrConstants.JCR_CONTENT)) { addJcrPropertiesToModel(factory, childNode.getNode(JcrConstants.JCR_CONTENT), model); } } model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#numberOfChildren"), ResourceFactory.createTypedLiteral(nodeIterator.getSize() - excludedNodes)); } /** * Add all of a node's properties to the given model * * @param node * @param model * @throws RepositoryException */ private static void addJcrPropertiesToModel( final GraphSubjects factory, final Node node, Model model) throws RepositoryException { final Resource subject = getGraphSubject(factory, node); final javax.jcr.PropertyIterator properties = node.getProperties(); while (properties.hasNext()) { final Property property = properties.nextProperty(); addPropertyToModel(subject, model, property); } } /** * Create a JCR value from an RDFNode, either by using the given JCR PropertyType or * by looking at the RDFNode Datatype * * @param data an RDF Node (possibly with a DataType) * @param type a JCR PropertyType value * * @return a JCR Value * * @throws javax.jcr.RepositoryException */ public static Value createValue(final Node node, final RDFNode data, final int type) throws RepositoryException { final ValueFactory valueFactory = FedoraTypesUtils.getValueFactory.apply(node); assert(valueFactory != null); if(data.isURIResource() && (type == PropertyType.REFERENCE || type == PropertyType.WEAKREFERENCE)) { // reference to another node (by path) return valueFactory.createValue(getNodeFromObjectPath(node, data.toString())); } else if (data.isURIResource() || type == PropertyType.URI) { // some random opaque URI return valueFactory.createValue(data.toString(), PropertyType.URI); } else if (data.isResource()) { // a non-URI resource (e.g. a blank node) return valueFactory.createValue(data.toString(), PropertyType.UNDEFINED); } else if (data.isLiteral() && type == PropertyType.UNDEFINED) { // the JCR schema doesn't know what this should be; so introspect the RDF and try to figure it out final Object rdfValue = data.asLiteral().getValue(); if (rdfValue instanceof Boolean) { return valueFactory.createValue((Boolean) rdfValue); } else if (rdfValue instanceof Byte) { return valueFactory.createValue((Byte) rdfValue); } else if (rdfValue instanceof Double) { return valueFactory.createValue((Double) rdfValue); } else if (rdfValue instanceof Float) { return valueFactory.createValue((Float) rdfValue); } else if (rdfValue instanceof Integer) { return valueFactory.createValue((Integer) rdfValue); } else if (rdfValue instanceof Long) { return valueFactory.createValue((Long) rdfValue); } else if (rdfValue instanceof Short) { return valueFactory.createValue((Short) rdfValue); } else if (rdfValue instanceof XSDDateTime) { return valueFactory.createValue(((XSDDateTime)rdfValue).asCalendar()); } else { return valueFactory.createValue(data.asLiteral().getString(), PropertyType.STRING); } } else { return valueFactory.createValue(data.asLiteral().getString(), type); } } /** * Add a JCR property to the given RDF Model (with the given subject) * @param subject the RDF subject to use in the assertions * @param model the RDF graph to insert the triple into * @param property the JCR property (multivalued or not) to convert to triples * * @throws RepositoryException */ public static void addPropertyToModel(final Resource subject, final Model model, final Property property) throws RepositoryException { if (property.isMultiple()) { final Value[] values = property.getValues(); for(Value v : values) { addPropertyToModel(subject, model, property, v); } } else { addPropertyToModel(subject, model, property, property.getValue()); } } /** * Add a JCR property to the given RDF Model (with the given subject) * * @param subject the RDF subject to use in the assertions * @param model the RDF graph to insert the triple into * @param property the JCR property (multivalued or not) to convert to triples * @param v the actual JCR Value to insert into the graph * @throws RepositoryException */ public static void addPropertyToModel(final Resource subject, final Model model, final Property property, Value v) throws RepositoryException { if (v.getType() == PropertyType.BINARY) { // exclude binary types from property serialization return; } final com.hp.hpl.jena.rdf.model.Property predicate = FedoraTypesUtils.getPredicateForProperty.apply(property); final String stringValue = v.getString(); RDFDatatype datatype = null; switch (v.getType()) { case PropertyType.BOOLEAN: datatype = model.createTypedLiteral(v.getBoolean()).getDatatype(); break; case PropertyType.DATE: datatype = model.createTypedLiteral(v.getDate()).getDatatype(); break; case PropertyType.DECIMAL: datatype = model.createTypedLiteral(v.getDecimal()).getDatatype(); break; case PropertyType.DOUBLE: datatype = model.createTypedLiteral(v.getDouble()).getDatatype(); break; case PropertyType.LONG: datatype = model.createTypedLiteral(v.getLong()).getDatatype(); break; case PropertyType.URI: model.add(subject, predicate, model.createResource(stringValue)); return; case PropertyType.REFERENCE: case PropertyType.WEAKREFERENCE: model.add(subject, predicate, model.createResource("info:fedora" + property.getSession().getNodeByIdentifier(stringValue).getPath())); return; case PropertyType.PATH: model.add(subject, predicate, model.createResource("info:fedora" + stringValue)); return; } if ( datatype == null) { model.add(subject, predicate, stringValue); } else { model.add(subject, predicate, stringValue, datatype); } } /** * Given an RDF predicate value (namespace URI + local name), figure out what JCR property to use * @param node the JCR node we want a property for * @param predicate the predicate to map to a property name * * @return the JCR property name * @throws RepositoryException */ public static String getPropertyNameFromPredicate(final Node node, final com.hp.hpl.jena.rdf.model.Property predicate) throws RepositoryException { final String prefix; final String namespace = getJcrNamespaceForRDFNamespace(predicate.getNameSpace()); final NamespaceRegistry namespaceRegistry = NamespaceTools.getNamespaceRegistry(node); assert(namespaceRegistry != null); if (namespaceRegistry.isRegisteredUri(namespace)) { prefix = namespaceRegistry.getPrefix(namespace); } else { prefix = namespaceRegistry.registerNamespace(namespace); } final String localName = predicate.getLocalName(); final String propertyName = prefix + ":" + localName; logger.trace("Took RDF predicate {} and translated it to JCR property {}", predicate, propertyName); return propertyName; } /** * Strip our silly "namespace" stuff from the object * @param node an existing JCR node * @param path the RDF URI to look up * @return the JCR node at the given RDF path * @throws RepositoryException */ private static Node getNodeFromObjectPath(final Node node, final String path) throws RepositoryException { return node.getSession().getNode(path.substring("info:fedora".length())); } public static Model getJcrVersionsModel( final GraphSubjects factory, final Node node) throws RepositoryException { final Resource subject = getGraphSubject(factory, node); final Model model = createDefaultJcrModel(node.getSession()); final VersionHistory versionHistory = FedoraTypesUtils.getVersionHistory(node); final VersionIterator versionIterator = versionHistory.getAllVersions(); while (versionIterator.hasNext()) { final Version version = versionIterator.nextVersion(); final Node frozenNode = version.getFrozenNode(); final Resource versionSubject = getGraphSubject(factory,frozenNode); model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasVersion"), versionSubject); final String[] versionLabels = versionHistory.getVersionLabels(version); for (String label : versionLabels ) { model.add(versionSubject, model.createProperty("info:fedora/fedora-system:def/internal#hasVersionLabel"), label); } final javax.jcr.PropertyIterator properties = frozenNode.getProperties(); while (properties.hasNext()) { final Property property = properties.nextProperty(); addPropertyToModel(versionSubject, model, property); } } return model; } }
fcrepo-kernel/src/main/java/org/fcrepo/utils/JcrRdfTools.java
package org.fcrepo.utils; import static com.google.common.base.Preconditions.checkArgument; import static org.fcrepo.utils.FedoraJcrTypes.FCR_CONTENT; import static org.slf4j.LoggerFactory.getLogger; import java.util.Set; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.version.Version; import javax.jcr.version.VersionHistory; import javax.jcr.version.VersionIterator; import org.fcrepo.rdf.GraphSubjects; import org.fcrepo.services.LowLevelStorageService; import org.modeshape.jcr.api.JcrConstants; import org.modeshape.jcr.api.NamespaceRegistry; import org.slf4j.Logger; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.hp.hpl.jena.datatypes.RDFDatatype; import com.hp.hpl.jena.datatypes.xsd.XSDDateTime; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; public abstract class JcrRdfTools { private static final Logger logger = getLogger(JcrRdfTools.class); public static BiMap<String, String> jcrNamespacesToRDFNamespaces = ImmutableBiMap.of( "http://www.jcp.org/jcr/1.0", "info:fedora/fedora-system:def/internal#" ); public static BiMap<String, String> rdfNamespacesToJcrNamespaces = jcrNamespacesToRDFNamespaces.inverse(); /** * Convert a Fedora RDF Namespace into its JCR equivalent * @param rdfNamespaceUri a namespace from an RDF document * @return the JCR namespace, or the RDF namespace if no matching JCR namespace is found */ public static String getJcrNamespaceForRDFNamespace(final String rdfNamespaceUri) { if (rdfNamespacesToJcrNamespaces.containsKey(rdfNamespaceUri)) { return rdfNamespacesToJcrNamespaces.get(rdfNamespaceUri); } else { return rdfNamespaceUri; } } /** * Convert a JCR namespace into an RDF namespace fit for downstream consumption * @param jcrNamespaceUri a namespace from the JCR NamespaceRegistry * @return an RDF namespace for downstream consumption. */ public static String getRDFNamespaceForJcrNamespace(final String jcrNamespaceUri) { if (jcrNamespacesToRDFNamespaces.containsKey(jcrNamespaceUri)) { return jcrNamespacesToRDFNamespaces.get(jcrNamespaceUri); } else { return jcrNamespaceUri; } } /** * Translate a JCR node into an RDF Resource * @param node * @return an RDF URI resource * @throws RepositoryException */ public static Resource getGraphSubject(final GraphSubjects factory, final Node node) throws RepositoryException { return factory.getGraphSubject(node); } /** * Translate an RDF resource into a JCR node * @param session * @param subject an RDF URI resource * @return a JCR node, or null if one couldn't be found * @throws RepositoryException */ public static Node getNodeFromGraphSubject(final GraphSubjects factory, final Session session, final Resource subject) throws RepositoryException { return factory.getNodeFromGraphSubject(session, subject); } /** * Predicate for determining whether this {@link Node} is a Fedora object. */ public static boolean isFedoraGraphSubject(final GraphSubjects factory, final Resource subject) { return factory.isFedoraGraphSubject(subject); } private static Model createDefaultJcrModel(final Session session) throws RepositoryException { final Model model = ModelFactory.createDefaultModel(); final javax.jcr.NamespaceRegistry namespaceRegistry = NamespaceTools.getNamespaceRegistry(session); assert(namespaceRegistry != null); for (final String prefix : namespaceRegistry.getPrefixes()) { final String nsURI = namespaceRegistry.getURI(prefix); if (nsURI != null && !nsURI.equals("") && !prefix.equals("xmlns")) { if (prefix.equals("jcr")) { model.setNsPrefix("fedora-internal", getRDFNamespaceForJcrNamespace(nsURI)); } else { model.setNsPrefix(prefix, getRDFNamespaceForJcrNamespace(nsURI)); } } } return model; } /** * Get an RDF Model for a node that includes all its own JCR properties, as well as the properties of its * immediate children. * * @param node * @return * @throws RepositoryException */ public static Model getJcrPropertiesModel( final GraphSubjects factory, final Node node) throws RepositoryException { final Model model = createDefaultJcrModel(node.getSession()); addJcrPropertiesToModel(factory, node, model); addJcrTreePropertiesToModel(factory, node, model); if (node.hasNode(JcrConstants.JCR_CONTENT)) { addJcrContentLocationInformationToModel(factory, node, model); } return model; } private static void addJcrContentLocationInformationToModel( final GraphSubjects factory, final Node node, final Model model) throws RepositoryException { final Node contentNode = node.getNode(JcrConstants.JCR_CONTENT); final Resource contentNodeSubject = factory.getGraphSubject(contentNode); // TODO: get this from somewhere else. LowLevelStorageService llstore = new LowLevelStorageService(); llstore.setRepository(node.getSession().getRepository()); final Set<LowLevelCacheEntry> cacheEntries = llstore.getLowLevelCacheEntries(node); for (LowLevelCacheEntry e : cacheEntries) { model.add(contentNodeSubject, model.createProperty("info:fedora/fedora-system:def/internal#hasLocation"), e.getExternalIdentifier()); } } /** * Add the properties of a Node's parent and immediate children (as well as the jcr:content of children) to the given * RDF model * * @param node * @param model * @throws RepositoryException */ private static void addJcrTreePropertiesToModel( final GraphSubjects factory, final Node node, final Model model) throws RepositoryException { final Resource subject = getGraphSubject(factory, node); // don't do this if the node is the root node. if (node.getDepth() != 0) { final Node parentNode = node.getParent(); model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasParent"), getGraphSubject(factory, parentNode)); addJcrPropertiesToModel(factory, parentNode, model); } final javax.jcr.NodeIterator nodeIterator = node.getNodes(); long excludedNodes = 0L; while (nodeIterator.hasNext()) { final Node childNode = nodeIterator.nextNode(); if (FedoraTypesUtils.isInternalNode.apply(childNode)) { continue; } final Resource childNodeSubject = getGraphSubject(factory, childNode); addJcrPropertiesToModel(factory, childNode, model); if (childNode.getName().equals(JcrConstants.JCR_CONTENT)) { model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasContent"), childNodeSubject); model.add(childNodeSubject, model.createProperty("info:fedora/fedora-system:def/internal#isContentOf"), subject); excludedNodes += 1; } else { model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasChild"), childNodeSubject); model.add(childNodeSubject, model.createProperty("info:fedora/fedora-system:def/internal#hasParent"), subject); } // always include the jcr:content node information if (childNode.hasNode(JcrConstants.JCR_CONTENT)) { addJcrPropertiesToModel(factory, childNode.getNode(JcrConstants.JCR_CONTENT), model); } } model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#numberOfChildren"), ResourceFactory.createTypedLiteral(nodeIterator.getSize() - excludedNodes)); } /** * Add all of a node's properties to the given model * * @param node * @param model * @throws RepositoryException */ private static void addJcrPropertiesToModel( final GraphSubjects factory, final Node node, Model model) throws RepositoryException { final Resource subject = getGraphSubject(factory, node); final javax.jcr.PropertyIterator properties = node.getProperties(); while (properties.hasNext()) { final Property property = properties.nextProperty(); addPropertyToModel(subject, model, property); } } /** * Create a JCR value from an RDFNode, either by using the given JCR PropertyType or * by looking at the RDFNode Datatype * * @param data an RDF Node (possibly with a DataType) * @param type a JCR PropertyType value * * @return a JCR Value * * @throws javax.jcr.RepositoryException */ public static Value createValue(final Node node, final RDFNode data, final int type) throws RepositoryException { final ValueFactory valueFactory = FedoraTypesUtils.getValueFactory.apply(node); assert(valueFactory != null); if(data.isURIResource() && (type == PropertyType.REFERENCE || type == PropertyType.WEAKREFERENCE)) { // reference to another node (by path) return valueFactory.createValue(getNodeFromObjectPath(node, data.toString())); } else if (data.isURIResource() || type == PropertyType.URI) { // some random opaque URI return valueFactory.createValue(data.toString(), PropertyType.URI); } else if (data.isResource()) { // a non-URI resource (e.g. a blank node) return valueFactory.createValue(data.toString(), PropertyType.UNDEFINED); } else if (data.isLiteral() && type == PropertyType.UNDEFINED) { // the JCR schema doesn't know what this should be; so introspect the RDF and try to figure it out final Object rdfValue = data.asLiteral().getValue(); if (rdfValue instanceof Boolean) { return valueFactory.createValue((Boolean) rdfValue); } else if (rdfValue instanceof Byte) { return valueFactory.createValue((Byte) rdfValue); } else if (rdfValue instanceof Double) { return valueFactory.createValue((Double) rdfValue); } else if (rdfValue instanceof Float) { return valueFactory.createValue((Float) rdfValue); } else if (rdfValue instanceof Integer) { return valueFactory.createValue((Integer) rdfValue); } else if (rdfValue instanceof Long) { return valueFactory.createValue((Long) rdfValue); } else if (rdfValue instanceof Short) { return valueFactory.createValue((Short) rdfValue); } else if (rdfValue instanceof XSDDateTime) { return valueFactory.createValue(((XSDDateTime)rdfValue).asCalendar()); } else { return valueFactory.createValue(data.asLiteral().getString(), PropertyType.STRING); } } else { return valueFactory.createValue(data.asLiteral().getString(), type); } } /** * Add a JCR property to the given RDF Model (with the given subject) * @param subject the RDF subject to use in the assertions * @param model the RDF graph to insert the triple into * @param property the JCR property (multivalued or not) to convert to triples * * @throws RepositoryException */ public static void addPropertyToModel(final Resource subject, final Model model, final Property property) throws RepositoryException { if (property.isMultiple()) { final Value[] values = property.getValues(); for(Value v : values) { addPropertyToModel(subject, model, property, v); } } else { addPropertyToModel(subject, model, property, property.getValue()); } } /** * Add a JCR property to the given RDF Model (with the given subject) * * @param subject the RDF subject to use in the assertions * @param model the RDF graph to insert the triple into * @param property the JCR property (multivalued or not) to convert to triples * @param v the actual JCR Value to insert into the graph * @throws RepositoryException */ public static void addPropertyToModel(final Resource subject, final Model model, final Property property, Value v) throws RepositoryException { if (v.getType() == PropertyType.BINARY) { // exclude binary types from property serialization return; } final com.hp.hpl.jena.rdf.model.Property predicate = FedoraTypesUtils.getPredicateForProperty.apply(property); final String stringValue = v.getString(); RDFDatatype datatype = null; switch (v.getType()) { case PropertyType.BOOLEAN: datatype = model.createTypedLiteral(v.getBoolean()).getDatatype(); break; case PropertyType.DATE: datatype = model.createTypedLiteral(v.getDate()).getDatatype(); break; case PropertyType.DECIMAL: datatype = model.createTypedLiteral(v.getDecimal()).getDatatype(); break; case PropertyType.DOUBLE: datatype = model.createTypedLiteral(v.getDouble()).getDatatype(); break; case PropertyType.LONG: datatype = model.createTypedLiteral(v.getLong()).getDatatype(); break; case PropertyType.URI: model.add(subject, predicate, model.createResource(stringValue)); return; case PropertyType.REFERENCE: case PropertyType.WEAKREFERENCE: model.add(subject, predicate, model.createResource("info:fedora" + property.getSession().getNodeByIdentifier(stringValue).getPath())); return; case PropertyType.PATH: model.add(subject, predicate, model.createResource("info:fedora" + stringValue)); return; } if ( datatype == null) { model.add(subject, predicate, stringValue); } else { model.add(subject, predicate, stringValue, datatype); } } /** * Given an RDF predicate value (namespace URI + local name), figure out what JCR property to use * @param node the JCR node we want a property for * @param predicate the predicate to map to a property name * * @return the JCR property name * @throws RepositoryException */ public static String getPropertyNameFromPredicate(final Node node, final com.hp.hpl.jena.rdf.model.Property predicate) throws RepositoryException { final String prefix; final String namespace = getJcrNamespaceForRDFNamespace(predicate.getNameSpace()); final NamespaceRegistry namespaceRegistry = NamespaceTools.getNamespaceRegistry(node); assert(namespaceRegistry != null); if (namespaceRegistry.isRegisteredUri(namespace)) { prefix = namespaceRegistry.getPrefix(namespace); } else { prefix = namespaceRegistry.registerNamespace(namespace); } final String localName = predicate.getLocalName(); final String propertyName = prefix + ":" + localName; logger.trace("Took RDF predicate {} and translated it to JCR property {}", predicate, propertyName); return propertyName; } /** * Strip our silly "namespace" stuff from the object * @param node an existing JCR node * @param path the RDF URI to look up * @return the JCR node at the given RDF path * @throws RepositoryException */ private static Node getNodeFromObjectPath(final Node node, final String path) throws RepositoryException { return node.getSession().getNode(path.substring("info:fedora".length())); } public static Model getJcrVersionsModel( final GraphSubjects factory, final Node node) throws RepositoryException { final Resource subject = getGraphSubject(factory, node); final Model model = createDefaultJcrModel(node.getSession()); final VersionHistory versionHistory = FedoraTypesUtils.getVersionHistory(node); final VersionIterator versionIterator = versionHistory.getAllVersions(); while (versionIterator.hasNext()) { final Version version = versionIterator.nextVersion(); final Node frozenNode = version.getFrozenNode(); final Resource versionSubject = getGraphSubject(factory,frozenNode); model.add(subject, model.createProperty("info:fedora/fedora-system:def/internal#hasVersion"), versionSubject); final String[] versionLabels = versionHistory.getVersionLabels(version); for (String label : versionLabels ) { model.add(versionSubject, model.createProperty("info:fedora/fedora-system:def/internal#hasVersionLabel"), label); } final javax.jcr.PropertyIterator properties = frozenNode.getProperties(); while (properties.hasNext()) { final Property property = properties.nextProperty(); addPropertyToModel(versionSubject, model, property); } } return model; } }
exclude internal nodes from the numberOfChildren count
fcrepo-kernel/src/main/java/org/fcrepo/utils/JcrRdfTools.java
exclude internal nodes from the numberOfChildren count
<ide><path>crepo-kernel/src/main/java/org/fcrepo/utils/JcrRdfTools.java <ide> final Node childNode = nodeIterator.nextNode(); <ide> <ide> if (FedoraTypesUtils.isInternalNode.apply(childNode)) { <add> excludedNodes += 1; <ide> continue; <ide> } <ide>
Java
apache-2.0
2843df57a6658a65d3197a93d7fbac5c67cf46de
0
ksw2599/torquebox,torquebox/torquebox-release,mje113/torquebox,vaskoz/torquebox,torquebox/torquebox,torquebox/torquebox,torquebox/torquebox-release,ksw2599/torquebox,torquebox/torquebox,samwgoldman/torquebox,mje113/torquebox,mje113/torquebox,vaskoz/torquebox,torquebox/torquebox,torquebox/torquebox-release,ksw2599/torquebox,samwgoldman/torquebox,torquebox/torquebox-release,mje113/torquebox,ksw2599/torquebox,samwgoldman/torquebox,vaskoz/torquebox,samwgoldman/torquebox,vaskoz/torquebox
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.torquebox.rails.deployers; import java.io.IOException; import java.io.File; import java.io.Closeable; import org.jboss.deployers.spi.DeploymentException; import org.jboss.deployers.spi.deployer.DeploymentStages; import org.jboss.deployers.spi.deployer.helpers.AbstractDeployer; import org.jboss.deployers.structure.spi.DeploymentUnit; import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VFS; /** * Ensure that log files generated by rails packaged deployments end * up somewhere reasonable, * e.g. JBOSS_HOME/server/default/log/app.rails, because they can't be * written to the deployed archive. */ public class RailsLogFileDeployer extends AbstractDeployer { static final String ATTACHMENT_NAME = "open log dir handle"; public RailsLogFileDeployer() { setStage(DeploymentStages.PARSE ); } public void deploy(DeploymentUnit unit) throws DeploymentException { if ( unit instanceof VFSDeploymentUnit && unit.getName().endsWith( ".rails" )) { deploy( (VFSDeploymentUnit) unit ); } } public void deploy(VFSDeploymentUnit unit) throws DeploymentException { VirtualFile logDir = unit.getRoot().getChild( "log" ); try { File writeableLogDir = new File( System.getProperty( "jboss.server.log.dir" ) + "/" + unit.getSimpleName() ); writeableLogDir.mkdirs(); Closeable mount = VFS.mountReal(writeableLogDir, logDir); log.warn("Set Rails log directory to "+writeableLogDir.getCanonicalPath()); unit.addAttachment( ATTACHMENT_NAME, mount, Closeable.class ); } catch (Exception e) { throw new DeploymentException( e ); } } public void undeploy(DeploymentUnit unit) { if ( unit.getName().endsWith( ".rails" )) { Closeable mount = unit.getAttachment(ATTACHMENT_NAME, Closeable.class); if (mount != null) { log.info("Closing virtual log directory for "+unit.getSimpleName() ); try { mount.close(); } catch (IOException ignored) {} } } } }
components/rails/rails-int/src/main/java/org/torquebox/rails/deployers/RailsLogFileDeployer.java
/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.torquebox.rails.deployers; import java.io.IOException; import java.io.File; import java.io.Closeable; import org.jboss.deployers.spi.DeploymentException; import org.jboss.deployers.spi.deployer.DeploymentStages; import org.jboss.deployers.spi.deployer.helpers.AbstractDeployer; import org.jboss.deployers.structure.spi.DeploymentUnit; import org.jboss.deployers.vfs.spi.structure.VFSDeploymentUnit; import org.jboss.vfs.VirtualFile; import org.jboss.vfs.VFS; /** * Ensure that log files generated by rails packaged deployments end * up somewhere reasonable, * e.g. JBOSS_HOME/server/default/log/app.rails, because they can't be * written to the deployed archive. */ public class RailsLogFileDeployer extends AbstractDeployer { static final String ATTACHMENT_NAME = "open log dir handle"; public RailsLogFileDeployer() { setStage(DeploymentStages.PARSE ); } public void deploy(DeploymentUnit unit) throws DeploymentException { if ( unit instanceof VFSDeploymentUnit && unit.getName().endsWith( ".rails" )) { deploy( (VFSDeploymentUnit) unit ); } } public void deploy(VFSDeploymentUnit unit) throws DeploymentException { VirtualFile logDir = unit.getRoot().getChild( "log" ); try { if ( ! ( logDir.exists() && logDir.getPhysicalFile().canWrite() ) ) { File writeableLogDir = new File( System.getProperty( "jboss.server.log.dir" ) + "/" + unit.getSimpleName() ); writeableLogDir.mkdirs(); Closeable mount = VFS.mountReal(writeableLogDir, logDir); log.warn("Set Rails log directory to "+writeableLogDir.getCanonicalPath()); unit.addAttachment( ATTACHMENT_NAME, mount, Closeable.class ); } } catch (Exception e) { throw new DeploymentException( e ); } } public void undeploy(DeploymentUnit unit) { if ( unit.getName().endsWith( ".rails" )) { Closeable mount = unit.getAttachment(ATTACHMENT_NAME, Closeable.class); if (mount != null) { log.info("Closing virtual log directory for "+unit.getSimpleName() ); try { mount.close(); } catch (IOException ignored) {} } } } }
Refs TORQUE-137. We now ignore any log dir in an archive and mount the jboss log dir instead.
components/rails/rails-int/src/main/java/org/torquebox/rails/deployers/RailsLogFileDeployer.java
Refs TORQUE-137. We now ignore any log dir in an archive and mount the jboss log dir instead.
<ide><path>omponents/rails/rails-int/src/main/java/org/torquebox/rails/deployers/RailsLogFileDeployer.java <ide> public void deploy(VFSDeploymentUnit unit) throws DeploymentException { <ide> VirtualFile logDir = unit.getRoot().getChild( "log" ); <ide> try { <del> if ( ! ( logDir.exists() && logDir.getPhysicalFile().canWrite() ) ) { <del> File writeableLogDir = new File( System.getProperty( "jboss.server.log.dir" ) + "/" + unit.getSimpleName() ); <del> writeableLogDir.mkdirs(); <del> Closeable mount = VFS.mountReal(writeableLogDir, logDir); <del> log.warn("Set Rails log directory to "+writeableLogDir.getCanonicalPath()); <del> unit.addAttachment( ATTACHMENT_NAME, mount, Closeable.class ); <del> } <add> File writeableLogDir = new File( System.getProperty( "jboss.server.log.dir" ) + "/" + unit.getSimpleName() ); <add> writeableLogDir.mkdirs(); <add> Closeable mount = VFS.mountReal(writeableLogDir, logDir); <add> log.warn("Set Rails log directory to "+writeableLogDir.getCanonicalPath()); <add> unit.addAttachment( ATTACHMENT_NAME, mount, Closeable.class ); <ide> } catch (Exception e) { <ide> throw new DeploymentException( e ); <ide> }
JavaScript
mit
2ffac3a53ba5ded238cd85141cd688c19142eaf7
0
anutron/behavior
/* --- name: Delegator description: Allows for the registration of delegated events on a container. requires: [Core/Element.Delegation, Core/Options, Core/Events, /Event.Mock, /Behavior] provides: [Delegator] ... */ (function(){ var spaceOrCommaRegex = /\s*,\s*|\s+/g; var checkEvent = function(trigger, element, event){ if (!event) return true; return trigger.types.some(function(type){ var elementEvent = Element.Events[type]; if (elementEvent && elementEvent.condition){ return elementEvent.condition.call(element, event, type); } else { var eventType = elementEvent && elementEvent.base ? elementEvent.base : event.type; return eventType == type; } }); }; window.Delegator = new Class({ Implements: [Options, Events, Behavior.PassMethods], options: { // breakOnErrors: false, // onTrigger: function(trigger, element, event, result){}, getBehavior: function(){}, onError: Behavior.getLog('error'), onWarn: Behavior.getLog('warn') }, initialize: function(options){ this.setOptions(options); this._bound = { eventHandler: this._eventHandler.bind(this) }; Delegator._instances.push(this); Object.each(Delegator._triggers, function(trigger){ this._eventTypes.combine(trigger.types); }, this); this.API = new Class({ Extends: BehaviorAPI }); this.passMethods({ addEvent: this.addEvent.bind(this), removeEvent: this.removeEvent.bind(this), addEvents: this.addEvents.bind(this), removeEvents: this.removeEvents.bind(this), fireEvent: this.fireEvent.bind(this), attach: this.attach.bind(this), trigger: this.trigger.bind(this), error: function(){ this.fireEvent('error', arguments); }.bind(this), fail: function(){ var msg = Array.join(arguments, ' '); throw new Error(msg); }, warn: function(){ this.fireEvent('warn', arguments); }.bind(this), getBehavior: function(){ return this.options.getBehavior(); }.bind(this) }); this.bindToBehavior(this.options.getBehavior()); }, bindToBehavior: function(behavior){ if (!behavior) return; this.unbindFromBehavior(); this._behavior = behavior; if (!this._behaviorEvents){ var self = this; this._behaviorEvents = { destroyDom: function(elements){ Array.from(elements).each(function(element){ self._behavior.cleanup(element); self._behavior.fireEvent('destroyDom', element); }); }, ammendDom: function(container){ self._behavior.apply(container); self._behavior.fireEvent('ammendDom', container); } }; } this.addEvents(this._behaviorEvents); }, getBehavior: function(){ return this._behavior; }, unbindFromBehavior: function(){ if (this._behaviorEvents && this._behavior){ this._behavior.removeEvents(this._behaviorEvents); delete this._behavior; } }, attach: function(target, _method){ _method = _method || 'addEvent'; target = document.id(target); if ((_method == 'addEvent' && this._attachedTo.contains(target)) || (_method == 'removeEvent') && !this._attachedTo.contains(target)) return this; this._eventTypes.each(function(event){ target[_method](event + ':relay([data-trigger])', this._bound.eventHandler); }, this); this._attachedTo.push(target); return this; }, detach: function(target){ if (target){ this.attach(target, 'removeEvent'); } else { this._attachedTo.each(this.detach, this); } return this; }, trigger: function(name, element, event){ var e = event; if (!e || typeOf(e) == "string") e = new Event.Mock(element, e); var result, trigger = this.getTrigger(name); if (!trigger){ this.fireEvent('warn', 'Could not find a trigger by the name of ' + name); } else if (checkEvent(trigger, element, e)) { if (this.options.breakOnErrors){ result = this._trigger(trigger, element, e); } else { try { result = this._trigger(trigger, element, e); } catch(error) { this.fireEvent('error', ['Could not apply the trigger', name, error.message]); } } } return result; }, getTrigger: function(name){ return this._triggers[name] || Delegator._triggers[name]; }, addEventTypes: function(triggerName, types){ this.getTrigger(triggerName).types.combine(Array.from(types)); return this; }, /****************** * PRIVATE METHODS ******************/ _trigger: function(trigger, element, event){ var api = new this.API(element, trigger.name); if (trigger.requireAs){ api.requireAs(trigger.requireAs); } else if (trigger.require){ api.require.apply(api, Array.from(trigger.require)); } if (trigger.defaults){ api.setDefault(trigger.defaults); } var result = trigger.handler.apply(this, [event, element, api]); this.fireEvent('trigger', [trigger, element, event, result]); return result; }, _eventHandler: function(event, target){ var triggers = target.getTriggers(); if (triggers.contains('Stop')) event.stop(); if (triggers.contains('PreventDefault')) event.preventDefault(); triggers.each(function(trigger){ if (trigger != "Stop" && trigger != "PreventDefault") this.trigger(trigger, target, event); }, this); }, _onRegister: function(eventTypes){ eventTypes.each(function(eventType){ if (!this._eventTypes.contains(eventType)){ this._attachedTo.each(function(element){ element.addEvent(eventType + ':relay([data-trigger])', this._bound.eventHandler); }, this); } this._eventTypes.include(eventType); }, this); }, _attachedTo: [], _eventTypes: [], _triggers: {} }); Delegator._triggers = {}; Delegator._instances = []; Delegator._onRegister = function(eventType){ this._instances.each(function(instance){ instance._onRegister(eventType); }); }; Delegator.register = function(eventTypes, name, handler, overwrite /** or eventType, obj, overwrite */){ eventTypes = Array.from(eventTypes); if (typeOf(name) == "object"){ var obj = name; for (name in obj){ this.register.apply(this, [eventTypes, name, obj[name], handler]); } return this; } if (!this._triggers[name] || overwrite){ if (typeOf(handler) == "function"){ handler = { handler: handler }; } handler.types = eventTypes; handler.name = name; this._triggers[name] = handler; this._onRegister(eventTypes); } else { throw new Error('Could add the trigger "' + name +'" as a previous trigger by that same name exists.'); } return this; }; Delegator.getTrigger = function(name){ return this._triggers[name]; }; Delegator.addEventTypes = function(triggerName, types){ this.getTrigger(triggerName).types.combine(Array.from(types)); return this; }; Delegator.implement('register', Delegator.register); Element.implement({ addTrigger: function(name){ return this.setData('trigger', this.getTriggers().include(name).join(' ')); }, removeTrigger: function(name){ return this.setData('trigger', this.getTriggers().erase(name).join(' ')); }, getTriggers: function(){ var triggers = this.getData('trigger'); if (!triggers) return []; return triggers.trim().split(spaceOrCommaRegex); }, hasTrigger: function(name){ return this.getTriggers().contains(name); } }); })();
Source/Delegator.js
/* --- name: Delegator description: Allows for the registration of delegated events on a container. requires: [Core/Element.Delegation, Core/Options, Core/Events, /Event.Mock, /Behavior] provides: [Delegator] ... */ (function(){ var spaceOrCommaRegex = /\s*,\s*|\s+/g; var checkEvent = function(trigger, element, event){ if (!event) return true; return trigger.types.some(function(type){ var elementEvent = Element.Events[type]; if (elementEvent && elementEvent.condition){ return elementEvent.condition.call(element, event, type); } else { var eventType = elementEvent && elementEvent.base ? elementEvent.base : event.type; return eventType == type; } }); }; window.Delegator = new Class({ Implements: [Options, Events, Behavior.PassMethods], options: { // breakOnErrors: false, // onTrigger: function(trigger, element, event, result){}, getBehavior: function(){}, onError: Behavior.getLog('error'), onWarn: Behavior.getLog('warn') }, initialize: function(options){ this.setOptions(options); this._bound = { eventHandler: this._eventHandler.bind(this) }; Delegator._instances.push(this); Object.each(Delegator._triggers, function(trigger){ this._eventTypes.combine(trigger.types); }, this); this.API = new Class({ Extends: BehaviorAPI }); this.passMethods({ addEvent: this.addEvent.bind(this), removeEvent: this.removeEvent.bind(this), addEvents: this.addEvents.bind(this), removeEvents: this.removeEvents.bind(this), fireEvent: this.fireEvent.bind(this), attach: this.attach.bind(this), trigger: this.trigger.bind(this), error: function(){ this.fireEvent('error', arguments); }.bind(this), fail: function(){ var msg = Array.join(arguments, ' '); throw new Error(msg); }, warn: function(){ this.fireEvent('warn', arguments); }.bind(this), getBehavior: function(){ return this.options.getBehavior(); }.bind(this) }); this.bindToBehavior(this.options.getBehavior()); }, bindToBehavior: function(behavior){ if (!behavior) return; this.unbindFromBehavior(); this._behavior = behavior; if (!this._behaviorEvents){ var self = this; this._behaviorEvents = { destroyDom: function(elements){ Array.from(elements).each(function(element){ self._behavior.cleanup(element); self._behavior.fireEvent('destroyDom', element); }); }, ammendDom: function(container){ self._behavior.apply(container); self._behavior.fireEvent('ammendDom', container); } }; } this.addEvents(this._behaviorEvents); }, getBehavior: function(){ return this._behavior; }, unbindFromBehavior: function(){ if (this._behaviorEvents && this._behavior){ this._behavior.removeEvents(this._behaviorEvents); delete this._behavior; } }, attach: function(target, _method){ _method = _method || 'addEvent'; target = document.id(target); if ((_method == 'addEvent' && this._attachedTo.contains(target)) || (_method == 'removeEvent') && !this._attachedTo.contains(target)) return this; this._eventTypes.each(function(event){ target[_method](event + ':relay([data-trigger])', this._bound.eventHandler); }, this); this._attachedTo.push(target); return this; }, detach: function(target){ if (target){ this.attach(target, 'removeEvent'); } else { this._attachedTo.each(this.detach, this); } return this; }, trigger: function(name, element, event){ var e = event; if (!e || typeOf(e) == "string") e = new Event.Mock(element, e); var result, trigger = this.getTrigger(name); if (!trigger){ this.fireEvent('warn', 'Could not find a trigger by the name of ' + name); } else if (checkEvent(trigger, element, e)) { if (this.options.breakOnErrors){ result = this._trigger(trigger, element, e); } else { try { result = this._trigger(trigger, element, e); } catch(error) { this.fireEvent('error', ['Could not apply the trigger', name, error]); } } } return result; }, getTrigger: function(name){ return this._triggers[name] || Delegator._triggers[name]; }, addEventTypes: function(triggerName, types){ this.getTrigger(triggerName).types.combine(Array.from(types)); return this; }, /****************** * PRIVATE METHODS ******************/ _trigger: function(trigger, element, event){ var api = new this.API(element, trigger.name); if (trigger.requireAs){ api.requireAs(trigger.requireAs); } else if (trigger.require){ api.require.apply(api, Array.from(trigger.require)); } if (trigger.defaults){ api.setDefault(trigger.defaults); } var result = trigger.handler.apply(this, [event, element, api]); this.fireEvent('trigger', [trigger, element, event, result]); return result; }, _eventHandler: function(event, target){ var triggers = target.getTriggers(); if (triggers.contains('Stop')) event.stop(); if (triggers.contains('PreventDefault')) event.preventDefault(); triggers.each(function(trigger){ if (trigger != "Stop" && trigger != "PreventDefault") this.trigger(trigger, target, event); }, this); }, _onRegister: function(eventTypes){ eventTypes.each(function(eventType){ if (!this._eventTypes.contains(eventType)){ this._attachedTo.each(function(element){ element.addEvent(eventType + ':relay([data-trigger])', this._bound.eventHandler); }, this); } this._eventTypes.include(eventType); }, this); }, _attachedTo: [], _eventTypes: [], _triggers: {} }); Delegator._triggers = {}; Delegator._instances = []; Delegator._onRegister = function(eventType){ this._instances.each(function(instance){ instance._onRegister(eventType); }); }; Delegator.register = function(eventTypes, name, handler, overwrite /** or eventType, obj, overwrite */){ eventTypes = Array.from(eventTypes); if (typeOf(name) == "object"){ var obj = name; for (name in obj){ this.register.apply(this, [eventTypes, name, obj[name], handler]); } return this; } if (!this._triggers[name] || overwrite){ if (typeOf(handler) == "function"){ handler = { handler: handler }; } handler.types = eventTypes; handler.name = name; this._triggers[name] = handler; this._onRegister(eventTypes); } else { throw new Error('Could add the trigger "' + name +'" as a previous trigger by that same name exists.'); } return this; }; Delegator.getTrigger = function(name){ return this._triggers[name]; }; Delegator.addEventTypes = function(triggerName, types){ this.getTrigger(triggerName).types.combine(Array.from(types)); return this; }; Delegator.implement('register', Delegator.register); Element.implement({ addTrigger: function(name){ return this.setData('trigger', this.getTriggers().include(name).join(' ')); }, removeTrigger: function(name){ return this.setData('trigger', this.getTriggers().erase(name).join(' ')); }, getTriggers: function(){ var triggers = this.getData('trigger'); if (!triggers) return []; return triggers.trim().split(spaceOrCommaRegex); }, hasTrigger: function(name){ return this.getTriggers().contains(name); } }); })();
fixing logging in Delegator, too
Source/Delegator.js
fixing logging in Delegator, too
<ide><path>ource/Delegator.js <ide> try { <ide> result = this._trigger(trigger, element, e); <ide> } catch(error) { <del> this.fireEvent('error', ['Could not apply the trigger', name, error]); <add> this.fireEvent('error', ['Could not apply the trigger', name, error.message]); <ide> } <ide> } <ide> }
Java
apache-2.0
b9e4d8c47368faafe788fa319d67fcdf1c8e6702
0
PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr
package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.store.Directory; import org.apache.lucene.util.ThreadInterruptedException; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Comparator; import java.util.Collections; /** A {@link MergeScheduler} that runs each merge using a * separate thread. * * <p>Specify the max number of threads that may run at * once with {@link #setMaxThreadCount}.</p> * * <p>Separately specify the maximum number of simultaneous * merges with {@link #setMaxMergeCount}. If the number of * merges exceeds the max number of threads then the * largest merges are paused until one of the smaller * merges completes.</p> * * <p>If more than {@link #getMaxMergeCount} merges are * requested then this class will forcefully throttle the * incoming threads by pausing until one more more merges * complete.</p> */ public class ConcurrentMergeScheduler extends MergeScheduler { private int mergeThreadPriority = -1; protected List<MergeThread> mergeThreads = new ArrayList<MergeThread>(); // Max number of merge threads allowed to be running at // once. When there are more merges then this, we // forcefully pause the larger ones, letting the smaller // ones run, up until maxMergeCount merges at which point // we forcefully pause incoming threads (that presumably // are the ones causing so much merging). We dynamically // default this from 1 to 3, depending on how many cores // you have: private int maxThreadCount = Math.max(1, Math.min(3, Runtime.getRuntime().availableProcessors()/2)); // Max number of merges we accept before forcefully // throttling the incoming threads private int maxMergeCount = maxThreadCount+2; protected Directory dir; private boolean closed; protected IndexWriter writer; protected int mergeThreadCount; public ConcurrentMergeScheduler() { if (allInstances != null) { // Only for testing addMyself(); } } /** Sets the max # simultaneous merge threads that should * be running at once. This must be <= {@link * #setMaxMergeCount}. */ public void setMaxThreadCount(int count) { if (count < 1) { throw new IllegalArgumentException("count should be at least 1"); } if (count > maxMergeCount) { throw new IllegalArgumentException("count should be <= maxMergeCount (= " + maxMergeCount + ")"); } maxThreadCount = count; } /** @see #setMaxThreadCount(int) */ public int getMaxThreadCount() { return maxThreadCount; } /** Sets the max # simultaneous merges that are allowed. * If a merge is necessary yet we already have this many * threads running, the incoming thread (that is calling * add/updateDocument) will block until a merge thread * has completed. Note that we will only run the * smallest {@link #setMaxThreadCount} merges at a time. */ public void setMaxMergeCount(int count) { if (count < 1) { throw new IllegalArgumentException("count should be at least 1"); } if (count < maxThreadCount) { throw new IllegalArgumentException("count should be >= maxThreadCount (= " + maxThreadCount + ")"); } maxMergeCount = count; } /** See {@link #setMaxMergeCount}. */ public int getMaxMergeCount() { return maxMergeCount; } /** Return the priority that merge threads run at. By * default the priority is 1 plus the priority of (ie, * slightly higher priority than) the first thread that * calls merge. */ public synchronized int getMergeThreadPriority() { initMergeThreadPriority(); return mergeThreadPriority; } /** Set the base priority that merge threads run at. * Note that CMS may increase priority of some merge * threads beyond this base priority. It's best not to * set this any higher than * Thread.MAX_PRIORITY-maxThreadCount, so that CMS has * room to set relative priority among threads. */ public synchronized void setMergeThreadPriority(int pri) { if (pri > Thread.MAX_PRIORITY || pri < Thread.MIN_PRIORITY) throw new IllegalArgumentException("priority must be in range " + Thread.MIN_PRIORITY + " .. " + Thread.MAX_PRIORITY + " inclusive"); mergeThreadPriority = pri; updateMergeThreads(); } // Larger merges come first protected static class CompareByMergeDocCount implements Comparator<MergeThread> { public int compare(MergeThread t1, MergeThread t2) { final MergePolicy.OneMerge m1 = t1.getCurrentMerge(); final MergePolicy.OneMerge m2 = t2.getCurrentMerge(); final int c1 = m1 == null ? Integer.MAX_VALUE : m1.segments.totalDocCount(); final int c2 = m2 == null ? Integer.MAX_VALUE : m2.segments.totalDocCount(); return c2 - c1; } } /** Called whenever the running merges have changed, to * pause & unpause threads. */ protected synchronized void updateMergeThreads() { Collections.sort(mergeThreads, new CompareByMergeDocCount()); final int count = mergeThreads.size(); int pri = mergeThreadPriority; for(int i=0;i<count;i++) { final MergeThread mergeThread = mergeThreads.get(i); final MergePolicy.OneMerge merge = mergeThread.getCurrentMerge(); if (merge == null) { continue; } final boolean doPause; if (i < count-maxThreadCount) { doPause = true; } else { doPause = false; } if (verbose()) { if (doPause != merge.getPause()) { if (doPause) { message("pause thread " + mergeThread.getName()); } else { message("unpause thread " + mergeThread.getName()); } } } if (doPause != merge.getPause()) { merge.setPause(doPause); } if (!doPause) { if (verbose()) { message("set priority of merge thread " + mergeThread.getName() + " to " + pri); } mergeThread.setThreadPriority(pri); pri = Math.min(Thread.MAX_PRIORITY, 1+pri); } } } private boolean verbose() { return writer != null && writer.verbose(); } private void message(String message) { if (verbose()) writer.message("CMS: " + message); } private synchronized void initMergeThreadPriority() { if (mergeThreadPriority == -1) { // Default to slightly higher priority than our // calling thread mergeThreadPriority = 1+Thread.currentThread().getPriority(); if (mergeThreadPriority > Thread.MAX_PRIORITY) mergeThreadPriority = Thread.MAX_PRIORITY; } } @Override public void close() { closed = true; } public synchronized void sync() { while(mergeThreadCount() > 0) { if (verbose()) message("now wait for threads; currently " + mergeThreads.size() + " still running"); final int count = mergeThreads.size(); if (verbose()) { for(int i=0;i<count;i++) message(" " + i + ": " + mergeThreads.get(i)); } try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } } private synchronized int mergeThreadCount() { int count = 0; final int numThreads = mergeThreads.size(); for(int i=0;i<numThreads;i++) if (mergeThreads.get(i).isAlive()) count++; return count; } @Override public void merge(IndexWriter writer) throws CorruptIndexException, IOException { assert !Thread.holdsLock(writer); this.writer = writer; initMergeThreadPriority(); dir = writer.getDirectory(); // First, quickly run through the newly proposed merges // and add any orthogonal merges (ie a merge not // involving segments already pending to be merged) to // the queue. If we are way behind on merging, many of // these newly proposed merges will likely already be // registered. if (verbose()) { message("now merge"); message(" index: " + writer.segString()); } // Iterate, pulling from the IndexWriter's queue of // pending merges, until it's empty: while(true) { // TODO: we could be careful about which merges to do in // the BG (eg maybe the "biggest" ones) vs FG, which // merges to do first (the easiest ones?), etc. MergePolicy.OneMerge merge = writer.getNextMerge(); if (merge == null) { if (verbose()) message(" no more merges pending; now return"); return; } // We do this w/ the primary thread to keep // deterministic assignment of segment names writer.mergeInit(merge); boolean success = false; try { synchronized(this) { final MergeThread merger; long startStallTime = 0; while (mergeThreadCount() >= maxMergeCount) { startStallTime = System.currentTimeMillis(); if (verbose()) { message(" too many merges; stalling..."); } try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } if (verbose()) { if (startStallTime != 0) { message(" stalled for " + (System.currentTimeMillis()-startStallTime) + " msec"); } message(" consider merge " + merge.segString(dir)); } assert mergeThreadCount() < maxMergeCount; // OK to spawn a new merge thread to handle this // merge: merger = getMergeThread(writer, merge); mergeThreads.add(merger); updateMergeThreads(); if (verbose()) message(" launch new thread [" + merger.getName() + "]"); merger.start(); success = true; } } finally { if (!success) { writer.mergeFinish(merge); } } } } /** Does the actual merge, by calling {@link IndexWriter#merge} */ protected void doMerge(MergePolicy.OneMerge merge) throws IOException { writer.merge(merge); } /** Create and return a new MergeThread */ protected synchronized MergeThread getMergeThread(IndexWriter writer, MergePolicy.OneMerge merge) throws IOException { final MergeThread thread = new MergeThread(writer, merge); thread.setThreadPriority(mergeThreadPriority); thread.setDaemon(true); thread.setName("Lucene Merge Thread #" + mergeThreadCount++); return thread; } protected class MergeThread extends Thread { IndexWriter tWriter; MergePolicy.OneMerge startMerge; MergePolicy.OneMerge runningMerge; private volatile boolean done; public MergeThread(IndexWriter writer, MergePolicy.OneMerge startMerge) throws IOException { this.tWriter = writer; this.startMerge = startMerge; } public synchronized void setRunningMerge(MergePolicy.OneMerge merge) { runningMerge = merge; } public synchronized MergePolicy.OneMerge getRunningMerge() { return runningMerge; } public synchronized MergePolicy.OneMerge getCurrentMerge() { if (done) { return null; } else if (runningMerge != null) { return runningMerge; } else { return startMerge; } } public void setThreadPriority(int pri) { try { setPriority(pri); } catch (NullPointerException npe) { // Strangely, Sun's JDK 1.5 on Linux sometimes // throws NPE out of here... } catch (SecurityException se) { // Ignore this because we will still run fine with // normal thread priority } } @Override public void run() { // First time through the while loop we do the merge // that we were started with: MergePolicy.OneMerge merge = this.startMerge; try { if (verbose()) message(" merge thread: start"); while(true) { setRunningMerge(merge); doMerge(merge); // Subsequent times through the loop we do any new // merge that writer says is necessary: merge = tWriter.getNextMerge(); if (merge != null) { tWriter.mergeInit(merge); updateMergeThreads(); if (verbose()) message(" merge thread: do another merge " + merge.segString(dir)); } else { done = true; updateMergeThreads(); break; } } if (verbose()) message(" merge thread: done"); } catch (Throwable exc) { // Ignore the exception if it was due to abort: if (!(exc instanceof MergePolicy.MergeAbortedException)) { if (!suppressExceptions) { // suppressExceptions is normally only set during // testing. anyExceptions = true; handleMergeException(exc); } } } finally { synchronized(ConcurrentMergeScheduler.this) { ConcurrentMergeScheduler.this.notifyAll(); boolean removed = mergeThreads.remove(this); assert removed; updateMergeThreads(); } } } @Override public String toString() { MergePolicy.OneMerge merge = getRunningMerge(); if (merge == null) merge = startMerge; return "merge thread: " + merge.segString(dir); } } /** Called when an exception is hit in a background merge * thread */ protected void handleMergeException(Throwable exc) { try { // When an exception is hit during merge, IndexWriter // removes any partial files and then allows another // merge to run. If whatever caused the error is not // transient then the exception will keep happening, // so, we sleep here to avoid saturating CPU in such // cases: Thread.sleep(250); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } throw new MergePolicy.MergeException(exc, dir); } static boolean anyExceptions = false; /** Used for testing */ public static boolean anyUnhandledExceptions() { if (allInstances == null) { throw new RuntimeException("setTestMode() was not called; often this is because your test case's setUp method fails to call super.setUp in LuceneTestCase"); } synchronized(allInstances) { final int count = allInstances.size(); // Make sure all outstanding threads are done so we see // any exceptions they may produce: for(int i=0;i<count;i++) allInstances.get(i).sync(); boolean v = anyExceptions; anyExceptions = false; return v; } } public static void clearUnhandledExceptions() { synchronized(allInstances) { anyExceptions = false; } } /** Used for testing */ private void addMyself() { synchronized(allInstances) { final int size = allInstances.size(); int upto = 0; for(int i=0;i<size;i++) { final ConcurrentMergeScheduler other = allInstances.get(i); if (!(other.closed && 0 == other.mergeThreadCount())) // Keep this one for now: it still has threads or // may spawn new threads allInstances.set(upto++, other); } allInstances.subList(upto, allInstances.size()).clear(); allInstances.add(this); } } private boolean suppressExceptions; /** Used for testing */ void setSuppressExceptions() { suppressExceptions = true; } /** Used for testing */ void clearSuppressExceptions() { suppressExceptions = false; } /** Used for testing */ private static List<ConcurrentMergeScheduler> allInstances; public static void setTestMode() { allInstances = new ArrayList<ConcurrentMergeScheduler>(); } }
lucene/src/java/org/apache/lucene/index/ConcurrentMergeScheduler.java
package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.store.Directory; import org.apache.lucene.util.ThreadInterruptedException; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Comparator; import java.util.Collections; /** A {@link MergeScheduler} that runs each merge using a * separate thread. * * <p>Specify the max number of threads that may run at * once with {@link #setMaxThreadCount}.</p> * * <p>Separately specify the maximum number of simultaneous * merges with {@link #setMaxMergeCount}. If the number of * merges exceeds the max number of threads then the * largest merges are paused until one of the smaller * merges completes.</p> * * <p>If more than {@link #getMaxMergeCount} merges are * requested then this class will forcefully throttle the * incoming threads by pausing until one more more merges * complete.</p> */ public class ConcurrentMergeScheduler extends MergeScheduler { private int mergeThreadPriority = -1; protected List<MergeThread> mergeThreads = new ArrayList<MergeThread>(); // Max number of merge threads allowed to be running at // once. When there are more merges then this, we // forcefully pause the larger ones, letting the smaller // ones run, up until maxMergeCount merges at which point // we forcefully pause incoming threads (that presumably // are the ones causing so much merging). We dynamically // default this from 1 to 3, depending on how many cores // you have: private int maxThreadCount = Math.max(1, Math.min(3, Runtime.getRuntime().availableProcessors()/2)); // Max number of merges we accept before forcefully // throttling the incoming threads private int maxMergeCount = maxThreadCount+2; protected Directory dir; private boolean closed; protected IndexWriter writer; protected int mergeThreadCount; public ConcurrentMergeScheduler() { if (allInstances != null) { // Only for testing addMyself(); } } /** Sets the max # simultaneous merge threads that should * be running at once. This must be <= {@link * #setMaxMergeCount}. */ public void setMaxThreadCount(int count) { if (count < 1) { throw new IllegalArgumentException("count should be at least 1"); } if (count > maxMergeCount) { throw new IllegalArgumentException("count should be <= maxMergeCount (= " + maxMergeCount + ")"); } maxThreadCount = count; } /** @see #setMaxThreadCount(int) */ public int getMaxThreadCount() { return maxThreadCount; } /** Sets the max # simultaneous merges that are allowed. * If a merge is necessary yet we already have this many * threads running, the incoming thread (that is calling * add/updateDocument) will block until a merge thread * has completed. Note that we will only run the * smallest {@link #setMaxThreadCount} merges at a time. */ public void setMaxMergeCount(int count) { if (count < 1) { throw new IllegalArgumentException("count should be at least 1"); } if (count < maxThreadCount) { throw new IllegalArgumentException("count should be >= maxThreadCount (= " + maxThreadCount + ")"); } maxMergeCount = count; } /** See {@link #setMaxMergeCount}. */ public int getMaxMergeCount() { return maxMergeCount; } /** Return the priority that merge threads run at. By * default the priority is 1 plus the priority of (ie, * slightly higher priority than) the first thread that * calls merge. */ public synchronized int getMergeThreadPriority() { initMergeThreadPriority(); return mergeThreadPriority; } /** Set the base priority that merge threads run at. * Note that CMS may increase priority of some merge * threads beyond this base priority. It's best not to * set this any higher than * Thread.MAX_PRIORITY-maxThreadCount, so that CMS has * room to set relative priority among threads. */ public synchronized void setMergeThreadPriority(int pri) { if (pri > Thread.MAX_PRIORITY || pri < Thread.MIN_PRIORITY) throw new IllegalArgumentException("priority must be in range " + Thread.MIN_PRIORITY + " .. " + Thread.MAX_PRIORITY + " inclusive"); mergeThreadPriority = pri; updateMergeThreads(); } // Larger merges come first protected static class CompareByMergeDocCount implements Comparator<MergeThread> { public int compare(MergeThread t1, MergeThread t2) { final MergePolicy.OneMerge m1 = t1.getCurrentMerge(); final MergePolicy.OneMerge m2 = t2.getCurrentMerge(); final int c1 = m1 == null ? Integer.MAX_VALUE : m1.segments.totalDocCount(); final int c2 = m2 == null ? Integer.MAX_VALUE : m2.segments.totalDocCount(); return c2 - c1; } } /** Called whenever the running merges have changed, to * pause & unpause threads. */ protected synchronized void updateMergeThreads() { Collections.sort(mergeThreads, new CompareByMergeDocCount()); final int count = mergeThreads.size(); int pri = mergeThreadPriority; for(int i=0;i<count;i++) { final MergeThread mergeThread = mergeThreads.get(i); final MergePolicy.OneMerge merge = mergeThread.getCurrentMerge(); if (merge == null) { continue; } final boolean doPause; if (i < count-maxThreadCount) { doPause = true; } else { doPause = false; } if (verbose()) { if (doPause != merge.getPause()) { if (doPause) { message("pause thread " + mergeThread.getName()); } else { message("unpause thread " + mergeThread.getName()); } } } if (doPause != merge.getPause()) { merge.setPause(doPause); } if (!doPause) { if (verbose()) { message("set priority of merge thread " + mergeThread.getName() + " to " + pri); } mergeThread.setThreadPriority(pri); pri = Math.min(Thread.MAX_PRIORITY, 1+pri); } } } private boolean verbose() { return writer != null && writer.verbose(); } private void message(String message) { if (verbose()) writer.message("CMS: " + message); } private synchronized void initMergeThreadPriority() { if (mergeThreadPriority == -1) { // Default to slightly higher priority than our // calling thread mergeThreadPriority = 1+Thread.currentThread().getPriority(); if (mergeThreadPriority > Thread.MAX_PRIORITY) mergeThreadPriority = Thread.MAX_PRIORITY; } } @Override public void close() { closed = true; } public synchronized void sync() { while(mergeThreadCount() > 0) { if (verbose()) message("now wait for threads; currently " + mergeThreads.size() + " still running"); final int count = mergeThreads.size(); if (verbose()) { for(int i=0;i<count;i++) message(" " + i + ": " + mergeThreads.get(i)); } try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } } private synchronized int mergeThreadCount() { int count = 0; final int numThreads = mergeThreads.size(); for(int i=0;i<numThreads;i++) if (mergeThreads.get(i).isAlive()) count++; return count; } @Override public void merge(IndexWriter writer) throws CorruptIndexException, IOException { assert !Thread.holdsLock(writer); this.writer = writer; initMergeThreadPriority(); dir = writer.getDirectory(); // First, quickly run through the newly proposed merges // and add any orthogonal merges (ie a merge not // involving segments already pending to be merged) to // the queue. If we are way behind on merging, many of // these newly proposed merges will likely already be // registered. if (verbose()) { message("now merge"); message(" index: " + writer.segString()); } // Iterate, pulling from the IndexWriter's queue of // pending merges, until it's empty: while(true) { // TODO: we could be careful about which merges to do in // the BG (eg maybe the "biggest" ones) vs FG, which // merges to do first (the easiest ones?), etc. MergePolicy.OneMerge merge = writer.getNextMerge(); if (merge == null) { if (verbose()) message(" no more merges pending; now return"); return; } // We do this w/ the primary thread to keep // deterministic assignment of segment names writer.mergeInit(merge); boolean success = false; try { synchronized(this) { final MergeThread merger; long startStallTime = 0; while (mergeThreadCount() >= maxMergeCount) { startStallTime = System.currentTimeMillis(); if (verbose()) { message(" too many merges; stalling..."); } try { wait(); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } } if (verbose()) { if (startStallTime != 0) { message(" stalled for " + (System.currentTimeMillis()-startStallTime) + " msec"); } message(" consider merge " + merge.segString(dir)); } assert mergeThreadCount() < maxMergeCount; // OK to spawn a new merge thread to handle this // merge: merger = getMergeThread(writer, merge); mergeThreads.add(merger); updateMergeThreads(); if (verbose()) message(" launch new thread [" + merger.getName() + "]"); merger.start(); success = true; } } finally { if (!success) { writer.mergeFinish(merge); } } } } /** Does the actual merge, by calling {@link IndexWriter#merge} */ protected void doMerge(MergePolicy.OneMerge merge) throws IOException { writer.merge(merge); } /** Create and return a new MergeThread */ protected synchronized MergeThread getMergeThread(IndexWriter writer, MergePolicy.OneMerge merge) throws IOException { final MergeThread thread = new MergeThread(writer, merge); thread.setThreadPriority(mergeThreadPriority); thread.setDaemon(true); thread.setName("Lucene Merge Thread #" + mergeThreadCount++); return thread; } protected class MergeThread extends Thread { IndexWriter tWriter; MergePolicy.OneMerge startMerge; MergePolicy.OneMerge runningMerge; private volatile boolean done; public MergeThread(IndexWriter writer, MergePolicy.OneMerge startMerge) throws IOException { this.tWriter = writer; this.startMerge = startMerge; } public synchronized void setRunningMerge(MergePolicy.OneMerge merge) { runningMerge = merge; } public synchronized MergePolicy.OneMerge getRunningMerge() { return runningMerge; } public synchronized MergePolicy.OneMerge getCurrentMerge() { if (done) { return null; } else if (runningMerge != null) { return runningMerge; } else { return startMerge; } } public void setThreadPriority(int pri) { try { setPriority(pri); } catch (NullPointerException npe) { // Strangely, Sun's JDK 1.5 on Linux sometimes // throws NPE out of here... } catch (SecurityException se) { // Ignore this because we will still run fine with // normal thread priority } } @Override public void run() { // First time through the while loop we do the merge // that we were started with: MergePolicy.OneMerge merge = this.startMerge; try { if (verbose()) message(" merge thread: start"); while(true) { setRunningMerge(merge); doMerge(merge); // Subsequent times through the loop we do any new // merge that writer says is necessary: merge = tWriter.getNextMerge(); if (merge != null) { tWriter.mergeInit(merge); updateMergeThreads(); if (verbose()) message(" merge thread: do another merge " + merge.segString(dir)); } else { done = true; updateMergeThreads(); break; } } if (verbose()) message(" merge thread: done"); } catch (Throwable exc) { // Ignore the exception if it was due to abort: if (!(exc instanceof MergePolicy.MergeAbortedException)) { if (!suppressExceptions) { // suppressExceptions is normally only set during // testing. anyExceptions = true; handleMergeException(exc); } } } finally { synchronized(ConcurrentMergeScheduler.this) { ConcurrentMergeScheduler.this.notifyAll(); boolean removed = mergeThreads.remove(this); assert removed; updateMergeThreads(); } } } @Override public String toString() { MergePolicy.OneMerge merge = getRunningMerge(); if (merge == null) merge = startMerge; return "merge thread: " + merge.segString(dir); } } /** Called when an exception is hit in a background merge * thread */ protected void handleMergeException(Throwable exc) { System.out.println("HANDLE " + exc); try { // When an exception is hit during merge, IndexWriter // removes any partial files and then allows another // merge to run. If whatever caused the error is not // transient then the exception will keep happening, // so, we sleep here to avoid saturating CPU in such // cases: Thread.sleep(250); } catch (InterruptedException ie) { throw new ThreadInterruptedException(ie); } throw new MergePolicy.MergeException(exc, dir); } static boolean anyExceptions = false; /** Used for testing */ public static boolean anyUnhandledExceptions() { if (allInstances == null) { throw new RuntimeException("setTestMode() was not called; often this is because your test case's setUp method fails to call super.setUp in LuceneTestCase"); } synchronized(allInstances) { final int count = allInstances.size(); // Make sure all outstanding threads are done so we see // any exceptions they may produce: for(int i=0;i<count;i++) allInstances.get(i).sync(); boolean v = anyExceptions; anyExceptions = false; return v; } } public static void clearUnhandledExceptions() { synchronized(allInstances) { anyExceptions = false; } } /** Used for testing */ private void addMyself() { synchronized(allInstances) { final int size = allInstances.size(); int upto = 0; for(int i=0;i<size;i++) { final ConcurrentMergeScheduler other = allInstances.get(i); if (!(other.closed && 0 == other.mergeThreadCount())) // Keep this one for now: it still has threads or // may spawn new threads allInstances.set(upto++, other); } allInstances.subList(upto, allInstances.size()).clear(); allInstances.add(this); } } private boolean suppressExceptions; /** Used for testing */ void setSuppressExceptions() { suppressExceptions = true; } /** Used for testing */ void clearSuppressExceptions() { suppressExceptions = false; } /** Used for testing */ private static List<ConcurrentMergeScheduler> allInstances; public static void setTestMode() { allInstances = new ArrayList<ConcurrentMergeScheduler>(); } }
remove accidental System.out.println git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@953634 13f79535-47bb-0310-9956-ffa450edef68
lucene/src/java/org/apache/lucene/index/ConcurrentMergeScheduler.java
remove accidental System.out.println
<ide><path>ucene/src/java/org/apache/lucene/index/ConcurrentMergeScheduler.java <ide> /** Called when an exception is hit in a background merge <ide> * thread */ <ide> protected void handleMergeException(Throwable exc) { <del> System.out.println("HANDLE " + exc); <ide> try { <ide> // When an exception is hit during merge, IndexWriter <ide> // removes any partial files and then allows another
Java
bsd-3-clause
b145fe20143e7884714df04fce94ba5340ecc0e3
0
Ryan1729/metazelda,tcoxon/metazelda
package net.bytten.metazelda; /** * Links two {@link Room}s. * <p> * The attached {@link Symbol} is a condition that must be satisfied for the * player to pass from one of the linked Rooms to the other via this Edge. It is * implemented as a {@link Symbol} rather than a {@link Condition} to simplify * the interface to clients of the library so that they don't have to handle the * case where multiple Symbols are required to pass through an Edge. * <p> * An unconditional Edge is one that may always be used to go from one of the * linked Rooms to the other. */ public class Edge { protected Symbol symbol; /** * Creates an unconditional Edge. */ public Edge() { symbol = null; } /** * Creates an Edge that requires a particular Symbol to be collected before * it may be used by the player to travel between the Rooms. * * @param symbol the symbol that must be obtained */ public Edge(Symbol symbol) { this.symbol = symbol; } /** * @return whether the Edge is conditional */ public boolean hasSymbol() { return symbol != null; } /** * @return the symbol that must be obtained to pass along this edge or null * if there are no required symbols */ public Symbol getSymbol() { return symbol; } public void setSymbol(Symbol symbol) { this.symbol = symbol; } @Override public boolean equals(Object other) { if (other instanceof Edge) { Edge o = (Edge)other; return symbol == o.symbol || symbol.equals(o.symbol); } else { return super.equals(other); } } }
src/net/bytten/metazelda/Edge.java
package net.bytten.metazelda; /** * Links two {@link Room}s. * <p> * The attached {@link Symbol} is a condition that must be satisfied for the * player to pass from one of the linked Rooms to the other via this Edge. It is * implemented as a {@link Symbol} rather than a {@link Condition} to simplify * the interface to clients of the library so that they don't have to handle the * case where multiple Symbols are required to pass through an Edge. * <p> * An unconditional Edge is one that may always be used to go from one of the * linked Rooms to the other. */ public class Edge { protected Symbol symbol; /** * Creates an unconditional Edge. */ public Edge() { symbol = null; } /** * Creates an Edge that requires a particular Symbol to be collected before * it may be used by the player to travel between the Rooms. * * @param symbol the symbol that must be obtained */ public Edge(Symbol symbol) { this.symbol = symbol; } /** * @return whether the Edge is conditional */ public boolean hasSymbol() { return symbol != null; } /** * @return the symbol that must be obtained to pass along this edge or null * if there are no required symbols */ public Symbol getSymbol() { return symbol; } @Override public boolean equals(Object other) { if (other instanceof Edge) { Edge o = (Edge)other; return symbol == o.symbol || symbol.equals(o.symbol); } else { return super.equals(other); } } }
Allow modification of Edges' symbols.
src/net/bytten/metazelda/Edge.java
Allow modification of Edges' symbols.
<ide><path>rc/net/bytten/metazelda/Edge.java <ide> return symbol; <ide> } <ide> <add> public void setSymbol(Symbol symbol) { <add> this.symbol = symbol; <add> } <add> <ide> @Override <ide> public boolean equals(Object other) { <ide> if (other instanceof Edge) {
Java
apache-2.0
d753be20ec7ae58aba868def976422294fe4ee2c
0
shahrzadmn/vaadin,udayinfy/vaadin,fireflyc/vaadin,peterl1084/framework,cbmeeks/vaadin,travisfw/vaadin,udayinfy/vaadin,sitexa/vaadin,asashour/framework,sitexa/vaadin,magi42/vaadin,Scarlethue/vaadin,mittop/vaadin,udayinfy/vaadin,mstahv/framework,asashour/framework,Peppe/vaadin,oalles/vaadin,Flamenco/vaadin,mittop/vaadin,sitexa/vaadin,Flamenco/vaadin,bmitc/vaadin,asashour/framework,Scarlethue/vaadin,oalles/vaadin,fireflyc/vaadin,jdahlstrom/vaadin.react,carrchang/vaadin,jdahlstrom/vaadin.react,sitexa/vaadin,cbmeeks/vaadin,jdahlstrom/vaadin.react,Flamenco/vaadin,Darsstar/framework,Darsstar/framework,bmitc/vaadin,cbmeeks/vaadin,jdahlstrom/vaadin.react,carrchang/vaadin,shahrzadmn/vaadin,synes/vaadin,oalles/vaadin,bmitc/vaadin,synes/vaadin,Peppe/vaadin,asashour/framework,Flamenco/vaadin,sitexa/vaadin,magi42/vaadin,Scarlethue/vaadin,mstahv/framework,cbmeeks/vaadin,kironapublic/vaadin,synes/vaadin,Darsstar/framework,Peppe/vaadin,bmitc/vaadin,Scarlethue/vaadin,Scarlethue/vaadin,magi42/vaadin,magi42/vaadin,travisfw/vaadin,peterl1084/framework,mstahv/framework,Legioth/vaadin,peterl1084/framework,peterl1084/framework,synes/vaadin,Darsstar/framework,kironapublic/vaadin,kironapublic/vaadin,Peppe/vaadin,jdahlstrom/vaadin.react,Legioth/vaadin,udayinfy/vaadin,Legioth/vaadin,shahrzadmn/vaadin,carrchang/vaadin,mstahv/framework,travisfw/vaadin,Legioth/vaadin,travisfw/vaadin,kironapublic/vaadin,mittop/vaadin,travisfw/vaadin,magi42/vaadin,Peppe/vaadin,mittop/vaadin,fireflyc/vaadin,synes/vaadin,oalles/vaadin,udayinfy/vaadin,shahrzadmn/vaadin,Legioth/vaadin,oalles/vaadin,shahrzadmn/vaadin,fireflyc/vaadin,peterl1084/framework,mstahv/framework,fireflyc/vaadin,carrchang/vaadin,Darsstar/framework,kironapublic/vaadin,asashour/framework
/* @ITMillApache2LicenseForJavaFiles@ */ package com.itmill.toolkit.terminal.gwt.client.ui.richtextarea; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.ChangeListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FocusListener; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RichTextArea; import com.google.gwt.user.client.ui.Widget; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.UIDL; import com.itmill.toolkit.terminal.gwt.client.Util; import com.itmill.toolkit.terminal.gwt.client.ui.Field; /** * This class represents a basic text input field with one row. * * @author IT Mill Ltd. * */ public class IRichTextArea extends Composite implements Paintable, Field, ChangeListener, FocusListener { /** * The input node CSS classname. */ public static final String CLASSNAME = "i-richtextarea"; protected String id; protected ApplicationConnection client; private boolean immediate = false; private RichTextArea rta = new RichTextArea(); private IRichTextToolbar formatter = new IRichTextToolbar(rta); private HTML html = new HTML(); private final FlowPanel fp = new FlowPanel(); private boolean enabled = true; private int extraHorizontalPixels = -1; private int extraVerticalPixels = -1; public IRichTextArea() { fp.add(formatter); rta.setWidth("100%"); rta.addFocusListener(this); fp.add(rta); initWidget(fp); setStyleName(CLASSNAME); } public void setEnabled(boolean enabled) { if (this.enabled != enabled) { rta.setEnabled(enabled); if (enabled) { fp.remove(html); fp.add(rta); } else { html.setHTML(rta.getHTML()); fp.remove(rta); fp.add(html); } this.enabled = enabled; } } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { this.client = client; id = uidl.getId(); if (uidl.hasVariable("text")) { rta.setHTML(uidl.getStringVariable("text")); } setEnabled(!uidl.getBooleanAttribute("disabled")); if (client.updateComponent(this, uidl, true)) { return; } immediate = uidl.getBooleanAttribute("immediate"); } public void onChange(Widget sender) { if (client != null && id != null) { client.updateVariable(id, "text", rta.getText(), immediate); } } public void onFocus(Widget sender) { } public void onLostFocus(Widget sender) { final String html = rta.getHTML(); client.updateVariable(id, "text", html, immediate); } /** * @return space used by components paddings and borders */ private int getExtraHorizontalPixels() { if (extraHorizontalPixels < 0) { detectExtraSizes(); } return extraHorizontalPixels; } /** * @return space used by components paddings and borders */ private int getExtraVerticalPixels() { if (extraVerticalPixels < 0) { detectExtraSizes(); } return extraVerticalPixels; } /** * Detects space used by components paddings and borders. */ private void detectExtraSizes() { Element clone = Util.cloneNode(getElement(), false); DOM.setElementAttribute(clone, "id", ""); DOM.setStyleAttribute(clone, "visibility", "hidden"); DOM.setStyleAttribute(clone, "position", "absolute"); // due FF3 bug set size to 10px and later subtract it from extra pixels DOM.setStyleAttribute(clone, "width", "10px"); DOM.setStyleAttribute(clone, "height", "10px"); DOM.appendChild(DOM.getParent(getElement()), clone); extraHorizontalPixels = DOM.getElementPropertyInt(clone, "offsetWidth") - 10; extraVerticalPixels = DOM.getElementPropertyInt(clone, "offsetHeight") - 10; DOM.removeChild(DOM.getParent(getElement()), clone); } @Override public void setHeight(String height) { if (height.endsWith("px")) { int h = Integer.parseInt(height.substring(0, height.length() - 2)); h -= getExtraVerticalPixels(); if (h < 0) { h = 0; } super.setHeight(h + "px"); int editorHeight = h - formatter.getOffsetHeight(); rta.setHeight(editorHeight + "px"); } else { super.setHeight(height); rta.setHeight(""); } } @Override public void setWidth(String width) { if (width.endsWith("px")) { int w = Integer.parseInt(width.substring(0, width.length() - 2)); w -= getExtraHorizontalPixels(); if (w < 0) { w = 0; } super.setWidth(w + "px"); } else { super.setWidth(width); } } }
src/com/itmill/toolkit/terminal/gwt/client/ui/richtextarea/IRichTextArea.java
/* @ITMillApache2LicenseForJavaFiles@ */ package com.itmill.toolkit.terminal.gwt.client.ui.richtextarea; import com.google.gwt.user.client.ui.ChangeListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.FocusListener; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RichTextArea; import com.google.gwt.user.client.ui.Widget; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.UIDL; import com.itmill.toolkit.terminal.gwt.client.ui.Field; /** * This class represents a basic text input field with one row. * * @author IT Mill Ltd. * */ public class IRichTextArea extends Composite implements Paintable, Field, ChangeListener, FocusListener { /** * The input node CSS classname. */ public static final String CLASSNAME = "i-richtextarea"; protected String id; protected ApplicationConnection client; private boolean immediate = false; private RichTextArea rta = new RichTextArea(); private IRichTextToolbar formatter = new IRichTextToolbar(rta); private HTML html = new HTML(); private final FlowPanel fp = new FlowPanel(); private boolean enabled = true; public IRichTextArea() { fp.add(formatter); rta.setWidth("100%"); rta.addFocusListener(this); fp.add(rta); initWidget(fp); setStyleName(CLASSNAME); } public void setEnabled(boolean enabled) { if (this.enabled != enabled) { rta.setEnabled(enabled); if (enabled) { fp.remove(html); fp.add(rta); } else { html.setHTML(rta.getHTML()); fp.remove(rta); fp.add(html); } this.enabled = enabled; } } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { this.client = client; id = uidl.getId(); if (uidl.hasVariable("text")) { rta.setHTML(uidl.getStringVariable("text")); } setEnabled(!uidl.getBooleanAttribute("disabled")); if (client.updateComponent(this, uidl, true)) { return; } immediate = uidl.getBooleanAttribute("immediate"); } public void onChange(Widget sender) { if (client != null && id != null) { client.updateVariable(id, "text", rta.getText(), immediate); } } public void onFocus(Widget sender) { } public void onLostFocus(Widget sender) { final String html = rta.getHTML(); client.updateVariable(id, "text", html, immediate); } }
Fixed RichTextArea dimensions svn changeset:5953/svn branch:trunk
src/com/itmill/toolkit/terminal/gwt/client/ui/richtextarea/IRichTextArea.java
Fixed RichTextArea dimensions
<ide><path>rc/com/itmill/toolkit/terminal/gwt/client/ui/richtextarea/IRichTextArea.java <ide> <ide> package com.itmill.toolkit.terminal.gwt.client.ui.richtextarea; <ide> <add>import com.google.gwt.user.client.DOM; <add>import com.google.gwt.user.client.Element; <ide> import com.google.gwt.user.client.ui.ChangeListener; <ide> import com.google.gwt.user.client.ui.Composite; <ide> import com.google.gwt.user.client.ui.FlowPanel; <ide> import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; <ide> import com.itmill.toolkit.terminal.gwt.client.Paintable; <ide> import com.itmill.toolkit.terminal.gwt.client.UIDL; <add>import com.itmill.toolkit.terminal.gwt.client.Util; <ide> import com.itmill.toolkit.terminal.gwt.client.ui.Field; <ide> <ide> /** <ide> private final FlowPanel fp = new FlowPanel(); <ide> <ide> private boolean enabled = true; <add> <add> private int extraHorizontalPixels = -1; <add> private int extraVerticalPixels = -1; <ide> <ide> public IRichTextArea() { <ide> fp.add(formatter); <ide> <ide> } <ide> <add> /** <add> * @return space used by components paddings and borders <add> */ <add> private int getExtraHorizontalPixels() { <add> if (extraHorizontalPixels < 0) { <add> detectExtraSizes(); <add> } <add> return extraHorizontalPixels; <add> } <add> <add> /** <add> * @return space used by components paddings and borders <add> */ <add> private int getExtraVerticalPixels() { <add> if (extraVerticalPixels < 0) { <add> detectExtraSizes(); <add> } <add> return extraVerticalPixels; <add> } <add> <add> /** <add> * Detects space used by components paddings and borders. <add> */ <add> private void detectExtraSizes() { <add> Element clone = Util.cloneNode(getElement(), false); <add> DOM.setElementAttribute(clone, "id", ""); <add> DOM.setStyleAttribute(clone, "visibility", "hidden"); <add> DOM.setStyleAttribute(clone, "position", "absolute"); <add> // due FF3 bug set size to 10px and later subtract it from extra pixels <add> DOM.setStyleAttribute(clone, "width", "10px"); <add> DOM.setStyleAttribute(clone, "height", "10px"); <add> DOM.appendChild(DOM.getParent(getElement()), clone); <add> extraHorizontalPixels = DOM.getElementPropertyInt(clone, "offsetWidth") - 10; <add> extraVerticalPixels = DOM.getElementPropertyInt(clone, "offsetHeight") - 10; <add> <add> DOM.removeChild(DOM.getParent(getElement()), clone); <add> } <add> <add> @Override <add> public void setHeight(String height) { <add> if (height.endsWith("px")) { <add> int h = Integer.parseInt(height.substring(0, height.length() - 2)); <add> h -= getExtraVerticalPixels(); <add> if (h < 0) { <add> h = 0; <add> } <add> <add> super.setHeight(h + "px"); <add> int editorHeight = h - formatter.getOffsetHeight(); <add> rta.setHeight(editorHeight + "px"); <add> } else { <add> super.setHeight(height); <add> rta.setHeight(""); <add> } <add> } <add> <add> @Override <add> public void setWidth(String width) { <add> if (width.endsWith("px")) { <add> int w = Integer.parseInt(width.substring(0, width.length() - 2)); <add> w -= getExtraHorizontalPixels(); <add> if (w < 0) { <add> w = 0; <add> } <add> <add> super.setWidth(w + "px"); <add> } else { <add> super.setWidth(width); <add> } <add> } <add> <ide> }
Java
epl-1.0
fcad69634019a60d1ae20600dbb8899e801453c8
0
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
package com.redhat.ceylon.eclipse.code.propose; import static com.redhat.ceylon.eclipse.code.hover.CeylonHover.getDocumentationFor; import static com.redhat.ceylon.eclipse.code.propose.CompletionProcessor.NO_COMPLETIONS; import static com.redhat.ceylon.eclipse.code.propose.ParameterContextValidator.findCharCount; import static com.redhat.ceylon.eclipse.code.quickfix.CeylonQuickFixAssistant.importEdit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedNamesAssistProposal.DeleteBlockingExitPolicy; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IEditingSupport; import org.eclipse.jface.text.IEditingSupportRegistry; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.link.ILinkedModeListener; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedModeUI; import org.eclipse.jface.text.link.LinkedPositionGroup; import org.eclipse.jface.text.link.ProposalPosition; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.text.edits.InsertEdit; import org.eclipse.ui.internal.editors.text.EditorsPlugin; import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; import com.redhat.ceylon.eclipse.code.editor.CeylonSourceViewer; import com.redhat.ceylon.eclipse.code.editor.CeylonSourceViewerConfiguration; import com.redhat.ceylon.eclipse.code.editor.Util; import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; class DeclarationCompletionProposal extends CompletionProposal { private final CeylonParseController cpc; private final Declaration declaration; private final boolean addimport; private final ProducedReference producedReference; private Scope scope; DeclarationCompletionProposal(int offset, String prefix, String desc, String text, boolean selectParams, CeylonParseController cpc, Declaration d) { this(offset, prefix, desc, text, selectParams, cpc, d, false, null, null); } DeclarationCompletionProposal(int offset, String prefix, String desc, String text, boolean selectParams, CeylonParseController cpc, Declaration d, boolean addimport, ProducedReference producedReference, Scope scope) { super(offset, prefix, CeylonLabelProvider.getImage(d), desc, text, selectParams); this.cpc = cpc; this.declaration = d; this.addimport = addimport; this.producedReference = producedReference; this.scope = scope; } @Override public void apply(IDocument document) { if (addimport) { try { List<InsertEdit> ies = importEdit(cpc.getRootNode(), Collections.singleton(declaration), null, null); for (InsertEdit ie: ies) { ie.apply(document); offset+=ie.getText().length(); } } catch (Exception e) { e.printStackTrace(); } } super.apply(document); if (EditorsPlugin.getDefault().getPreferenceStore() .getBoolean(CeylonSourceViewerConfiguration.LINKED_MODE)) { if (declaration instanceof Generic) { ParameterList paramList = null; if (declaration instanceof Functional && getFirstPosition(false)>0) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty() && !pls.get(0).getParameters().isEmpty()) { paramList = pls.get(0); } } enterLinkedMode(document, paramList, (Generic) declaration); } } } @Override public Point getSelection(IDocument document) { if (declaration instanceof Generic) { ParameterList pl = null; if (declaration instanceof Functional) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty() && !pls.get(0).getParameters().isEmpty()) { pl = pls.get(0); } } int paren = pl==null ? text.indexOf('<') : text.indexOf('('); if (paren<0) { return super.getSelection(document); } int comma = getNextPosition(document, paren, pl==null); return new Point(offset-prefix.length()+paren+1, comma-1); } return super.getSelection(document); } public int getNextPosition(IDocument document, int lastOffset, boolean typeArgList) { int loc = offset-prefix.length(); int comma = -1; try { int start = loc+lastOffset+1; int end = loc+text.length()-1; if (text.endsWith(";")) end--; comma = findCharCount(1, document, start, end, ",;", "", true) - start; } catch (BadLocationException e) { e.printStackTrace(); } if (comma<0) { int angleIndex = text.lastIndexOf('>'); int parenIndex = text.lastIndexOf(')'); int braceIndex = text.lastIndexOf('}'); comma = (typeArgList ? angleIndex : (braceIndex>parenIndex?braceIndex:parenIndex))-lastOffset; } return comma; } public String getAdditionalProposalInfo() { return getDocumentationFor(cpc, declaration); } private IEditingSupport editingSupport; public void enterLinkedMode(IDocument document, ParameterList parameterList, Generic generic) { boolean basicProposal = parameterList==null; int paramCount = basicProposal ? generic.getTypeParameters().size() : parameterList.getParameters().size(); if (paramCount==0) return; //Big TODO: handle named arguments! try { final LinkedModeModel linkedModeModel = new LinkedModeModel(); final int loc = offset-prefix.length(); int first = getFirstPosition(basicProposal); if (first<0) return; int next = getNextPosition(document, first, basicProposal); int i=0; while (next>1 && i<paramCount) { List<ICompletionProposal> props = new ArrayList<ICompletionProposal>(); if (basicProposal) { addBasicProposals(generic, loc, first, props, i); } else { addProposals(parameterList, loc, first, props, i); } LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup(); int space = getCompletionPosition(first, next); ProposalPosition linkedPosition = new ProposalPosition(document, loc+first+1+space, next-1-space, i, props.toArray(NO_COMPLETIONS)); linkedPositionGroup.addPosition(linkedPosition); first = first+next+1; next = getNextPosition(document, first, basicProposal); linkedModeModel.addGroup(linkedPositionGroup); i++; } linkedModeModel.forceInstall(); final CeylonEditor editor = (CeylonEditor) Util.getCurrentEditor(); linkedModeModel.addLinkingListener(new ILinkedModeListener() { @Override public void left(LinkedModeModel model, int flags) { editor.setLinkedMode(null); // linkedModeModel.exit(ILinkedModeListener.NONE); CeylonSourceViewer viewer= editor.getCeylonSourceViewer(); if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer; registry.unregister(editingSupport); } editor.getSite().getPage().activate(editor); if ((flags&EXTERNAL_MODIFICATION)==0) { viewer.invalidateTextPresentation(); } } @Override public void suspend(LinkedModeModel model) { editor.setLinkedMode(null); } @Override public void resume(LinkedModeModel model, int flags) { editor.setLinkedMode(model); } }); editor.setLinkedMode(linkedModeModel); CeylonSourceViewer viewer = editor.getCeylonSourceViewer(); EditorLinkedModeUI ui= new EditorLinkedModeUI(linkedModeModel, viewer); ui.setExitPosition(viewer, loc+text.length(), 0, i); ui.setExitPolicy(new DeleteBlockingExitPolicy(document)); ui.setCyclingMode(LinkedModeUI.CYCLE_WHEN_NO_PARENT); ui.setDoContextInfo(true); ui.enter(); if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer; editingSupport = new IEditingSupport() { public boolean ownsFocusShell() { Shell editorShell= editor.getSite().getShell(); Shell activeShell= editorShell.getDisplay().getActiveShell(); if (editorShell == activeShell) return true; return false; } public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) { return false; //leave on external modification outside positions } }; registry.register(editingSupport); } } catch (Exception e) { e.printStackTrace(); } } protected int getCompletionPosition(int first, int next) { int space = text.substring(first, first+next-1).lastIndexOf(' '); if (space<0) space=0; return space; } protected int getFirstPosition(boolean basicProposal) { int anglePos = text.indexOf('<'); int parenPos = text.indexOf('('); int bracePos = text.indexOf('{'); int first = basicProposal ? anglePos : (parenPos<0 ? bracePos : parenPos); return first; } private void addProposals(ParameterList parameterList, final int loc, int first, List<ICompletionProposal> props, final int index) { Parameter p = parameterList.getParameters().get(index); if (p.getModel().isDynamicallyTyped()) { return; } ProducedType type = producedReference.getTypedParameter(p) .getFullType(); if (type==null) return; TypeDeclaration td = type.getDeclaration(); for (DeclarationWithProximity dwp: getSortedProposedValues()) { Declaration d = dwp.getDeclaration(); if (d instanceof Value && !dwp.isUnimported()) { if (d.getUnit().getPackage().getNameAsString() .equals(Module.LANGUAGE_MODULE_NAME)) { if (d.getName().equals("process") || d.getName().equals("language") || d.getName().equals("emptyIterator") || d.getName().equals("infinity") || d.getName().endsWith("IntegerValue") || d.getName().equals("finished")) { continue; } } ProducedType vt = ((Value) d).getType(); if (vt!=null && !vt.isNothing() && ((td instanceof TypeParameter) && isInBounds(((TypeParameter)td).getSatisfiedTypes(), vt) || vt.isSubtypeOf(type))) { addProposal(loc, first, props, index, d, false); } } } } private void addBasicProposals(Generic generic, final int loc, int first, List<ICompletionProposal> props, final int index) { TypeParameter p = generic.getTypeParameters().get(index); for (DeclarationWithProximity dwp: getSortedProposedValues()) { Declaration d = dwp.getDeclaration(); if (d instanceof TypeDeclaration && !dwp.isUnimported()) { TypeDeclaration td = (TypeDeclaration) d; ProducedType t = td.getType(); if (td.getTypeParameters().isEmpty() && !td.isAnnotation() && !(td instanceof NothingType) && !td.inherits(td.getUnit().getExceptionDeclaration())) { if (td.getUnit().getPackage().getNameAsString() .equals(Module.LANGUAGE_MODULE_NAME)) { if (!td.getName().equals("Object") && !td.getName().equals("Anything") && !td.getName().equals("String") && !td.getName().equals("Integer") && !td.getName().equals("Character") && !td.getName().equals("Float") && !td.getName().equals("Boolean")) { continue; } } if (isInBounds(p.getSatisfiedTypes(), t)) { addProposal(loc, first, props, index, d, true); } } } } } public boolean isInBounds(List<ProducedType> upperBounds, ProducedType t) { boolean ok = true; for (ProducedType ub: upperBounds) { if (!t.isSubtypeOf(ub) && !(ub.containsTypeParameters() && t.getDeclaration().inherits(ub.getDeclaration()))) { ok = false; break; } } return ok; } public List<DeclarationWithProximity> getSortedProposedValues() { List<DeclarationWithProximity> results = new ArrayList<DeclarationWithProximity>( scope.getMatchingDeclarations(cpc.getRootNode().getUnit(), "", 0).values()); Collections.sort(results, new Comparator<DeclarationWithProximity>() { public int compare(DeclarationWithProximity x, DeclarationWithProximity y) { if (x.getProximity()<y.getProximity()) return -1; if (x.getProximity()>y.getProximity()) return 1; int c = x.getDeclaration().getName().compareTo(y.getDeclaration().getName()); if (c!=0) return c; return x.getDeclaration().getQualifiedNameString() .compareTo(y.getDeclaration().getQualifiedNameString()); } }); return results; } private void addProposal(final int loc, int first, List<ICompletionProposal> props, final int index, final Declaration d, final boolean basic) { props.add(new ICompletionProposal() { public String getAdditionalProposalInfo() { return null; } @Override public void apply(IDocument document) { try { IRegion li = document.getLineInformationOfOffset(loc); int len = li.getOffset() + li.getLength() - loc; String rest = document.get(loc, len); int paren = getFirstPosition(basic); int offset = findCharCount(index, document, loc+paren+1, loc+len, ",;", "", true); while (offset>0&&document.getChar(offset)==' ') offset++; int nextOffset = findCharCount(index+1, document, loc+paren+1, loc+len, ",;", "", true); int middleOffset = findCharCount(index+1, document, loc+paren+1, loc+len, "=", "", true); while (middleOffset>0&&document.getChar(middleOffset)==' ') middleOffset++; if (middleOffset>offset&&middleOffset<nextOffset) offset = middleOffset; document.replace(offset, nextOffset-offset-1, d.getName()); } catch (BadLocationException e) { e.printStackTrace(); } } @Override public Point getSelection(IDocument document) { return null; } @Override public String getDisplayString() { return d.getName(); } @Override public Image getImage() { return CeylonLabelProvider.getImage(d); } @Override public IContextInformation getContextInformation() { return null; } }); } @Override public IContextInformation getContextInformation() { if (declaration instanceof Functional) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty() && //TODO: for now there is no context info for type args lists - fix that! !(pls.get(0).getParameters().isEmpty()&&!((Generic)declaration).getTypeParameters().isEmpty())) { int paren = text.indexOf('('); if (paren<0 && !getDisplayString().equals("show parameters")) { //ugh, horrible, todo! return super.getContextInformation(); } return new ParameterContextInformation(declaration, producedReference, pls.get(0), offset-prefix.length()); } } return null; } }
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/propose/DeclarationCompletionProposal.java
package com.redhat.ceylon.eclipse.code.propose; import static com.redhat.ceylon.eclipse.code.hover.CeylonHover.getDocumentationFor; import static com.redhat.ceylon.eclipse.code.propose.CompletionProcessor.NO_COMPLETIONS; import static com.redhat.ceylon.eclipse.code.propose.ParameterContextValidator.findCharCount; import static com.redhat.ceylon.eclipse.code.quickfix.CeylonQuickFixAssistant.importEdit; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedNamesAssistProposal.DeleteBlockingExitPolicy; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IEditingSupport; import org.eclipse.jface.text.IEditingSupportRegistry; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.link.ILinkedModeListener; import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedModeUI; import org.eclipse.jface.text.link.LinkedPositionGroup; import org.eclipse.jface.text.link.ProposalPosition; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.text.edits.InsertEdit; import org.eclipse.ui.internal.editors.text.EditorsPlugin; import org.eclipse.ui.texteditor.link.EditorLinkedModeUI; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Generic; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.NothingType; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedReference; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; import com.redhat.ceylon.eclipse.code.editor.CeylonSourceViewer; import com.redhat.ceylon.eclipse.code.editor.CeylonSourceViewerConfiguration; import com.redhat.ceylon.eclipse.code.editor.Util; import com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; class DeclarationCompletionProposal extends CompletionProposal { private final CeylonParseController cpc; private final Declaration declaration; private final boolean addimport; private final ProducedReference producedReference; private Scope scope; DeclarationCompletionProposal(int offset, String prefix, String desc, String text, boolean selectParams, CeylonParseController cpc, Declaration d) { this(offset, prefix, desc, text, selectParams, cpc, d, false, null, null); } DeclarationCompletionProposal(int offset, String prefix, String desc, String text, boolean selectParams, CeylonParseController cpc, Declaration d, boolean addimport, ProducedReference producedReference, Scope scope) { super(offset, prefix, CeylonLabelProvider.getImage(d), desc, text, selectParams); this.cpc = cpc; this.declaration = d; this.addimport = addimport; this.producedReference = producedReference; this.scope = scope; } @Override public void apply(IDocument document) { if (addimport) { try { List<InsertEdit> ies = importEdit(cpc.getRootNode(), Collections.singleton(declaration), null, null); for (InsertEdit ie: ies) { ie.apply(document); offset+=ie.getText().length(); } } catch (Exception e) { e.printStackTrace(); } } super.apply(document); if (EditorsPlugin.getDefault().getPreferenceStore() .getBoolean(CeylonSourceViewerConfiguration.LINKED_MODE)) { if (declaration instanceof Generic) { ParameterList paramList = null; if (declaration instanceof Functional && text.indexOf('(')>0) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty() && !pls.get(0).getParameters().isEmpty()) { paramList = pls.get(0); } } enterLinkedMode(document, paramList, (Generic) declaration); } } } @Override public Point getSelection(IDocument document) { if (declaration instanceof Generic) { ParameterList pl = null; if (declaration instanceof Functional) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty() && !pls.get(0).getParameters().isEmpty()) { pl = pls.get(0); } } int paren = pl==null ? text.indexOf('<') : text.indexOf('('); if (paren<0) { return super.getSelection(document); } int comma = getNextComma(document, paren, pl==null); return new Point(offset-prefix.length()+paren+1, comma-1); } return super.getSelection(document); } public int getNextComma(IDocument document, int lastOffset, boolean typeArgList) { int loc = offset-prefix.length(); int comma = -1; try { int start = loc+lastOffset+1; int end = loc+text.length(); comma = findCharCount(1, document, start, end, ",", "", true) - start; } catch (BadLocationException e) { e.printStackTrace(); } if (comma<0) { comma = (typeArgList ? text.indexOf('>') : text.length()-1)-lastOffset; } return comma; } public String getAdditionalProposalInfo() { return getDocumentationFor(cpc, declaration); } private IEditingSupport editingSupport; public void enterLinkedMode(IDocument document, ParameterList parameterList, Generic generic) { boolean basicProposal = parameterList==null; int paramCount = basicProposal ? generic.getTypeParameters().size() : parameterList.getParameters().size(); if (paramCount==0) return; //Big TODO: handle named arguments! try { final LinkedModeModel linkedModeModel = new LinkedModeModel(); final int loc = offset-prefix.length(); int first = basicProposal ? text.indexOf('<') : text.indexOf('('); if (first<0) return; int next = getNextComma(document, first, basicProposal); int i=0; while (next>1 && i<paramCount) { List<ICompletionProposal> props = new ArrayList<ICompletionProposal>(); if (basicProposal) { addBasicProposals(generic, loc, first, props, i); } else { addProposals(parameterList, loc, first, props, i); } LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup(); ProposalPosition linkedPosition = new ProposalPosition(document, loc+first+1, next-1, i, props.toArray(NO_COMPLETIONS)); linkedPositionGroup.addPosition(linkedPosition); first = first+next+1; next = getNextComma(document, first, basicProposal); linkedModeModel.addGroup(linkedPositionGroup); i++; } linkedModeModel.forceInstall(); final CeylonEditor editor = (CeylonEditor) Util.getCurrentEditor(); linkedModeModel.addLinkingListener(new ILinkedModeListener() { @Override public void left(LinkedModeModel model, int flags) { editor.setLinkedMode(null); // linkedModeModel.exit(ILinkedModeListener.NONE); CeylonSourceViewer viewer= editor.getCeylonSourceViewer(); if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer; registry.unregister(editingSupport); } editor.getSite().getPage().activate(editor); if ((flags&EXTERNAL_MODIFICATION)==0) { viewer.invalidateTextPresentation(); } } @Override public void suspend(LinkedModeModel model) { editor.setLinkedMode(null); } @Override public void resume(LinkedModeModel model, int flags) { editor.setLinkedMode(model); } }); editor.setLinkedMode(linkedModeModel); CeylonSourceViewer viewer = editor.getCeylonSourceViewer(); EditorLinkedModeUI ui= new EditorLinkedModeUI(linkedModeModel, viewer); ui.setExitPosition(viewer, loc+text.length(), 0, i); ui.setExitPolicy(new DeleteBlockingExitPolicy(document)); ui.setCyclingMode(LinkedModeUI.CYCLE_WHEN_NO_PARENT); ui.setDoContextInfo(true); ui.enter(); if (viewer instanceof IEditingSupportRegistry) { IEditingSupportRegistry registry= (IEditingSupportRegistry) viewer; editingSupport = new IEditingSupport() { public boolean ownsFocusShell() { Shell editorShell= editor.getSite().getShell(); Shell activeShell= editorShell.getDisplay().getActiveShell(); if (editorShell == activeShell) return true; return false; } public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) { return false; //leave on external modification outside positions } }; registry.register(editingSupport); } } catch (Exception e) { e.printStackTrace(); } } private void addProposals(ParameterList parameterList, final int loc, int first, List<ICompletionProposal> props, final int index) { Parameter p = parameterList.getParameters().get(index); if (p.getModel().isDynamicallyTyped()) { return; } ProducedType type = producedReference.getTypedParameter(p) .getFullType(); if (type==null) return; TypeDeclaration td = type.getDeclaration(); for (DeclarationWithProximity dwp: getSortedProposedValues()) { Declaration d = dwp.getDeclaration(); if (d instanceof Value && !dwp.isUnimported()) { if (d.getUnit().getPackage().getNameAsString() .equals(Module.LANGUAGE_MODULE_NAME)) { if (d.getName().equals("process") || d.getName().equals("language") || d.getName().equals("emptyIterator") || d.getName().equals("infinity") || d.getName().endsWith("IntegerValue") || d.getName().equals("finished")) { continue; } } ProducedType vt = ((Value) d).getType(); if (vt!=null && !vt.isNothing() && ((td instanceof TypeParameter) && isInBounds(((TypeParameter)td).getSatisfiedTypes(), vt) || vt.isSubtypeOf(type))) { addProposal(loc, first, props, index, d, false); } } } } private void addBasicProposals(Generic generic, final int loc, int first, List<ICompletionProposal> props, final int index) { TypeParameter p = generic.getTypeParameters().get(index); for (DeclarationWithProximity dwp: getSortedProposedValues()) { Declaration d = dwp.getDeclaration(); if (d instanceof TypeDeclaration && !dwp.isUnimported()) { TypeDeclaration td = (TypeDeclaration) d; ProducedType t = td.getType(); if (td.getTypeParameters().isEmpty() && !td.isAnnotation() && !(td instanceof NothingType) && !td.inherits(td.getUnit().getExceptionDeclaration())) { if (td.getUnit().getPackage().getNameAsString() .equals(Module.LANGUAGE_MODULE_NAME)) { if (!td.getName().equals("Object") && !td.getName().equals("Anything") && !td.getName().equals("String") && !td.getName().equals("Integer") && !td.getName().equals("Character") && !td.getName().equals("Float") && !td.getName().equals("Boolean")) { continue; } } if (isInBounds(p.getSatisfiedTypes(), t)) { addProposal(loc, first, props, index, d, true); } } } } } public boolean isInBounds(List<ProducedType> upperBounds, ProducedType t) { boolean ok = true; for (ProducedType ub: upperBounds) { if (!t.isSubtypeOf(ub) && !(ub.containsTypeParameters() && t.getDeclaration().inherits(ub.getDeclaration()))) { ok = false; break; } } return ok; } public List<DeclarationWithProximity> getSortedProposedValues() { List<DeclarationWithProximity> results = new ArrayList<DeclarationWithProximity>( scope.getMatchingDeclarations(cpc.getRootNode().getUnit(), "", 0).values()); Collections.sort(results, new Comparator<DeclarationWithProximity>() { public int compare(DeclarationWithProximity x, DeclarationWithProximity y) { if (x.getProximity()<y.getProximity()) return -1; if (x.getProximity()>y.getProximity()) return 1; int c = x.getDeclaration().getName().compareTo(y.getDeclaration().getName()); if (c!=0) return c; return x.getDeclaration().getQualifiedNameString() .compareTo(y.getDeclaration().getQualifiedNameString()); } }); return results; } private void addProposal(final int loc, int first, List<ICompletionProposal> props, final int index, final Declaration d, final boolean basic) { props.add(new ICompletionProposal() { public String getAdditionalProposalInfo() { return null; } @Override public void apply(IDocument document) { try { IRegion li = document.getLineInformationOfOffset(loc); int len = li.getOffset() + li.getLength() - loc; String rest = document.get(loc, len); int paren = basic ? rest.indexOf('<') : rest.indexOf('('); int offset = findCharCount(index, document, loc+paren+1, loc+len, ",", "", true); while (document.getChar(offset)==' ') offset++; int nextOffset = findCharCount(index+1, document, loc+paren+1, loc+len, ",", "", true); document.replace(offset, nextOffset-offset-1, d.getName()); } catch (BadLocationException e) { e.printStackTrace(); } } @Override public Point getSelection(IDocument document) { return null; } @Override public String getDisplayString() { return d.getName(); } @Override public Image getImage() { return CeylonLabelProvider.getImage(d); } @Override public IContextInformation getContextInformation() { return null; } }); } @Override public IContextInformation getContextInformation() { if (declaration instanceof Functional) { List<ParameterList> pls = ((Functional) declaration).getParameterLists(); if (!pls.isEmpty() && //TODO: for now there is no context info for type args lists - fix that! !(pls.get(0).getParameters().isEmpty()&&!((Generic)declaration).getTypeParameters().isEmpty())) { int paren = text.indexOf('('); if (paren<0 && !getDisplayString().equals("show parameters")) { //ugh, horrible, todo! return super.getContextInformation(); } return new ParameterContextInformation(declaration, producedReference, pls.get(0), offset-prefix.length()); } } return null; } }
linked mode completion for named args
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/propose/DeclarationCompletionProposal.java
linked mode completion for named args
<ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/propose/DeclarationCompletionProposal.java <ide> .getBoolean(CeylonSourceViewerConfiguration.LINKED_MODE)) { <ide> if (declaration instanceof Generic) { <ide> ParameterList paramList = null; <del> if (declaration instanceof Functional && text.indexOf('(')>0) { <add> if (declaration instanceof Functional && getFirstPosition(false)>0) { <ide> List<ParameterList> pls = ((Functional) declaration).getParameterLists(); <ide> if (!pls.isEmpty() && !pls.get(0).getParameters().isEmpty()) { <ide> paramList = pls.get(0); <ide> if (paren<0) { <ide> return super.getSelection(document); <ide> } <del> int comma = getNextComma(document, paren, pl==null); <add> int comma = getNextPosition(document, paren, pl==null); <ide> return new Point(offset-prefix.length()+paren+1, comma-1); <ide> } <ide> return super.getSelection(document); <ide> } <ide> <del> public int getNextComma(IDocument document, int lastOffset, <add> public int getNextPosition(IDocument document, int lastOffset, <ide> boolean typeArgList) { <ide> int loc = offset-prefix.length(); <ide> int comma = -1; <ide> try { <ide> int start = loc+lastOffset+1; <del> int end = loc+text.length(); <del> comma = findCharCount(1, document, start, end, ",", "", true) - start; <add> int end = loc+text.length()-1; <add> if (text.endsWith(";")) end--; <add> comma = findCharCount(1, document, start, end, ",;", "", true) - start; <ide> } <ide> catch (BadLocationException e) { <ide> e.printStackTrace(); <ide> } <ide> if (comma<0) { <del> comma = (typeArgList ? text.indexOf('>') : text.length()-1)-lastOffset; <add> int angleIndex = text.lastIndexOf('>'); <add> int parenIndex = text.lastIndexOf(')'); <add> int braceIndex = text.lastIndexOf('}'); <add> comma = (typeArgList ? angleIndex : (braceIndex>parenIndex?braceIndex:parenIndex))-lastOffset; <ide> } <ide> return comma; <ide> } <ide> try { <ide> final LinkedModeModel linkedModeModel = new LinkedModeModel(); <ide> final int loc = offset-prefix.length(); <del> int first = basicProposal ? text.indexOf('<') : text.indexOf('('); <add> int first = getFirstPosition(basicProposal); <ide> if (first<0) return; <del> int next = getNextComma(document, first, basicProposal); <add> int next = getNextPosition(document, first, basicProposal); <ide> int i=0; <ide> while (next>1 && i<paramCount) { <ide> List<ICompletionProposal> props = new ArrayList<ICompletionProposal>(); <ide> addProposals(parameterList, loc, first, props, i); <ide> } <ide> LinkedPositionGroup linkedPositionGroup = new LinkedPositionGroup(); <add> int space = getCompletionPosition(first, next); <ide> ProposalPosition linkedPosition = new ProposalPosition(document, <del> loc+first+1, next-1, i, <add> loc+first+1+space, next-1-space, i, <ide> props.toArray(NO_COMPLETIONS)); <ide> linkedPositionGroup.addPosition(linkedPosition); <ide> first = first+next+1; <del> next = getNextComma(document, first, basicProposal); <add> next = getNextPosition(document, first, basicProposal); <ide> linkedModeModel.addGroup(linkedPositionGroup); <ide> i++; <ide> } <ide> } <ide> } <ide> <add> protected int getCompletionPosition(int first, int next) { <add> int space = text.substring(first, first+next-1).lastIndexOf(' '); <add> if (space<0) space=0; <add> return space; <add> } <add> <add> protected int getFirstPosition(boolean basicProposal) { <add> int anglePos = text.indexOf('<'); <add> int parenPos = text.indexOf('('); <add> int bracePos = text.indexOf('{'); <add> int first = basicProposal ? anglePos : (parenPos<0 ? bracePos : parenPos); <add> return first; <add> } <add> <ide> private void addProposals(ParameterList parameterList, final int loc, <ide> int first, List<ICompletionProposal> props, final int index) { <ide> Parameter p = parameterList.getParameters().get(index); <ide> IRegion li = document.getLineInformationOfOffset(loc); <ide> int len = li.getOffset() + li.getLength() - loc; <ide> String rest = document.get(loc, len); <del> int paren = basic ? rest.indexOf('<') : rest.indexOf('('); <add> int paren = getFirstPosition(basic); <ide> int offset = findCharCount(index, document, <ide> loc+paren+1, loc+len, <del> ",", "", true); <del> while (document.getChar(offset)==' ') offset++; <add> ",;", "", true); <add> while (offset>0&&document.getChar(offset)==' ') offset++; <ide> int nextOffset = findCharCount(index+1, document, <ide> loc+paren+1, loc+len, <del> ",", "", true); <add> ",;", "", true); <add> int middleOffset = findCharCount(index+1, document, <add> loc+paren+1, loc+len, <add> "=", "", true); <add> while (middleOffset>0&&document.getChar(middleOffset)==' ') middleOffset++; <add> if (middleOffset>offset&&middleOffset<nextOffset) offset = middleOffset; <ide> document.replace(offset, nextOffset-offset-1, d.getName()); <ide> } <ide> catch (BadLocationException e) {
Java
unlicense
1f01ac316ad70735c7b73e476f3365d4739e58a5
0
JamesHealey94/Breakout
package com.gmail.jameshealey1994.breakout; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * GUI for Breakout Game Main Menu. * * @author JamesHealey94 <jameshealey1994.gmail.com> */ public class MainMenuGUI extends JFrame { /** * Creates a new instance of the Game GUI. * * @throws HeadlessException thrown if user does not have a mouse or keyboard. */ public MainMenuGUI() throws HeadlessException { this.setTitle("Breakout - Main Menu"); this.setLocationRelativeTo(null); this.setBackground(Color.LIGHT_GRAY); this.setDefaultCloseOperation(EXIT_ON_CLOSE); //this.setIconImage(null); // TODO create Icon this.setLayout(new BorderLayout()); final JPanel buttonPanel = new JPanel(new GridLayout(2, 1)); buttonPanel.setVisible(true); this.add(buttonPanel); final JButton playButton = new JButton("Play"); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createAndShowGameGUI(); } }); buttonPanel.add(playButton); playButton.setVisible(true); buttonPanel.add(playButton); final JButton scoresButton = new JButton("Scores"); scoresButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Display scores } }); buttonPanel.add(scoresButton); this.pack(); } /** * Creates and shows the game gui. */ private void createAndShowGameGUI() { final GameGUI gameGUI = new GameGUI(); gameGUI.setLocationRelativeTo(this); gameGUI.setVisible(true); gameGUI.start(); } }
Breakout/src/com/gmail/jameshealey1994/breakout/MainMenuGUI.java
package com.gmail.jameshealey1994.breakout; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * GUI for Breakout Game Main Menu. * * @author JamesHealey94 <jameshealey1994.gmail.com> */ public class MainMenuGUI extends JFrame { /** * Creates a new instance of the Game GUI. * * @throws HeadlessException thrown if user does not have a mouse or keyboard. */ public MainMenuGUI() throws HeadlessException { this.setTitle("Breakout - Main Menu"); this.setLocationRelativeTo(null); this.setBackground(Color.LIGHT_GRAY); this.setDefaultCloseOperation(EXIT_ON_CLOSE); //this.setIconImage(null); // TODO create Icon this.setLayout(new BorderLayout()); final JPanel buttonPanel = new JPanel(new GridLayout(2, 1)); final JButton playButton = new JButton("Play"); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { createAndShowGameGUI(); } }); playButton.setVisible(true); buttonPanel.add(playButton); buttonPanel.setVisible(true); this.add(buttonPanel); this.pack(); } /** * Creates and shows the game gui. */ private void createAndShowGameGUI() { final GameGUI gameGUI = new GameGUI(); gameGUI.setLocationRelativeTo(this); gameGUI.setVisible(true); gameGUI.start(); } }
Add Scores button to Main Menu GUI, waiting on scores JFrame or JPanel.
Breakout/src/com/gmail/jameshealey1994/breakout/MainMenuGUI.java
Add Scores button to Main Menu GUI, waiting on scores JFrame or JPanel.
<ide><path>reakout/src/com/gmail/jameshealey1994/breakout/MainMenuGUI.java <ide> this.setLayout(new BorderLayout()); <ide> <ide> final JPanel buttonPanel = new JPanel(new GridLayout(2, 1)); <add> buttonPanel.setVisible(true); <add> this.add(buttonPanel); <add> <ide> final JButton playButton = new JButton("Play"); <ide> playButton.addActionListener(new ActionListener() { <ide> @Override <ide> createAndShowGameGUI(); <ide> } <ide> }); <add> buttonPanel.add(playButton); <ide> <ide> playButton.setVisible(true); <ide> buttonPanel.add(playButton); <del> buttonPanel.setVisible(true); <del> this.add(buttonPanel); <add> <add> final JButton scoresButton = new JButton("Scores"); <add> scoresButton.addActionListener(new ActionListener() { <add> @Override <add> public void actionPerformed(ActionEvent e) { <add> // Display scores <add> } <add> }); <add> buttonPanel.add(scoresButton); <add> <ide> this.pack(); <ide> } <ide>
JavaScript
apache-2.0
bb2e434c76e2aa1f1b97d87b78ed9927818a611b
0
digitalfruit/limejs,GeorgeMe/limejs,saulpw/nucleotron,ZzCalvinzZ/ludumdare26,sjamog/Lime-Projects,runawaygo/Saver2012,sjamog/Lime-Projects,saulpw/nucleotron,oleg-kipling/limejs,ZzCalvinzZ/ludumdare26,wikieswan/limejs,squallyan/limejs,wikieswan/limejs,sjamog/Lime-Projects,wikieswan/limejs,runawaygo/Saver2012,Diaosir/limejs,squallyan/limejs,srbala/limejs,GeorgeMe/limejs,GeorgeMe/limejs,digitalfruit/limejs,srbala/limejs,oleg-kipling/limejs,Diaosir/limejs,Diaosir/limejs,Inframatic/theBasics,digitalfruit/limejs,srbala/limejs,oleg-kipling/limejs,squallyan/limejs,Inframatic/theBasics
goog.provide('lime.Director'); goog.require('lime'); goog.require('lime.Node'); goog.require('lime.events.EventDispatcher'); goog.require('lime.helper.PauseScene'); goog.require('lime.scheduleManager'); goog.require('lime.transitions.Transition'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.ViewportSizeMonitor'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.math.Box'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Size'); goog.require('goog.math.Vec2'); goog.require('goog.style'); /** * Director object. Base object for every game. * @param {DOMElement} parentElement Parent element for director. * @constructor * @extends lime.Node */ lime.Director = function(parentElement) { lime.Node.call(this); // Unlike other nodes Director is always in the DOM as // it requires parentNode in the constructor this.inTree_ = true; this.setAnchorPoint(0, 0); // todo: maybe easier if director just positions itselt // to the center of the screen /** * Array of Scene instances. Last one is the active scene. * @type {Array.<lime.Scene>} * @private */ this.sceneStack_ = []; /** * Array of CoverNode instances. * @type {Array.<lime.CoverNode>} * @private */ this.coverStack_ = []; this.domClassName = goog.getCssName('lime-director'); this.createDomElement(); parentElement.appendChild(this.domElement); if (goog.userAgent.WEBKIT && goog.userAgent.MOBILE) { //todo: Not pretty solution. Cover layers may not be needed at all. this.coverElementBelow = document.createElement('div'); goog.dom.classes.add(this.coverElementBelow, goog.getCssName('lime-cover-below')); goog.dom.insertSiblingBefore(this.coverElementBelow, this.domElement); this.coverElementAbove = document.createElement('div'); goog.dom.classes.add(this.coverElementAbove, goog.getCssName('lime-cover-above')); goog.dom.insertSiblingAfter(this.coverElementAbove, this.domElement); } if (parentElement.style['position'] != 'absolute') { parentElement.style['position'] = 'relative'; } parentElement.style['overflow'] = 'hidden'; if (parentElement == document.body) { //todo: installstyles is better goog.style.installStyles('html,body{margin:0;padding:0;height:100%;}'); var meta=document.createElement('meta'); meta.name='viewport'; var content = 'width=device-width,initial-scale=1.0,minimum-scale=1,maximum-scale=1.0,user-scalable=no'; if((/android/i).test(navigator.userAgent)){ content+=',target-densityDpi=device-dpi'; } meta.content = content; document.getElementsByTagName('head').item(0).appendChild(meta); window.scrollTo(0,0); } var width, parentSize = goog.style.getSize(parentElement); // todo: this 400x400 default should probably be constants instead this.setSize(new goog.math.Size( width = arguments[1] || parentSize.width || 400, arguments[2] || parentSize.height * width / parentSize.width || 400 )); // --define goog.debug=false this.setDisplayFPS(goog.DEBUG);//todo: connect with DEBUG flags this.setPaused(false); var vsm = new goog.dom.ViewportSizeMonitor(); goog.events.listen(vsm, goog.events.EventType.RESIZE, this.invalidateSize_, false, this); goog.events.listen(window, 'orientationchange', this.invalidateSize_, false, this); lime.scheduleManager.schedule(this.step_, this); this.eventDispatcher = new lime.events.EventDispatcher(this); // Prevent page scrolling on touch events goog.events.listen(this, 'touchmove', function(e) {e.event.preventDefault();}, false, this); // todo: check if all those are really neccessary as Event code // is much more mature now goog.events.listen(this, ['mouseup', 'touchend', 'mouseout', 'touchcancel'], function() {},false); this.invalidateSize_(); }; goog.inherits(lime.Director, lime.Node); /** * Milliseconds between recalculating FPS value * @const * @type {number} */ lime.Director.FPS_INTERVAL = 100; /** * Returns true if director is paused? On paused state * the update timer doesn't fire. * @return {boolean} If director is paused. */ lime.Director.prototype.isPaused = function() { return this.isPaused_; }; /** * Pauses or resumes the director * @param {boolean} value Pause or resume. * @return {lime.Director} The director object itself. */ lime.Director.prototype.setPaused = function(value) { this.isPaused_ = value; lime.scheduleManager.changeDirectorActivity(this, value ? 0 : 1); if (this.isPaused_) { this.pauseScene = new lime.helper.PauseScene(); this.pushScene(this.pauseScene); } else if (this.pauseScene) { this.popScene(); delete this.pauseScene; } return this; }; /** * Returns true if FPS counter is displayed * @return {boolean} FPS is displayed. */ lime.Director.prototype.isDisplayFPS = function() { return this.displayFPS_; }; /** * Show or hide FPS counter * @param {boolean} value Display FPS? * @return {lime.Director} The director object itself. */ lime.Director.prototype.setDisplayFPS = function(value) { if (this.displayFPS_ && !value) { goog.dom.removeNode(this.fpsElement_); } else if (!this.displayFPS_ && value) { this.frames_ = 0; this.accumDt_ = 0; this.fpsElement_ = goog.dom.createDom('div'); goog.dom.classes.add(this.fpsElement_, goog.getCssName('lime-fps')); this.domElement.parentNode.appendChild(this.fpsElement_); } this.displayFPS_ = value; return this; }; /** * Get current active scene * @return {lime.Scene} Currently active scene. */ lime.Director.prototype.getCurrentScene = function() { return this.sceneStack_.length ? this.sceneStack_[this.sceneStack_.length - 1] : null; }; /** @inheritDoc */ lime.Director.prototype.getDirector = function() { return this; }; /** @inheritDoc */ lime.Director.prototype.getScene = function() { return null; }; /** * Timeline function. * @param {number} delta Milliseconds since last step. * @private */ lime.Director.prototype.step_ = function(delta) { if (this.isDisplayFPS()) { this.frames_++; this.accumDt_ += delta; if (this.accumDt_ > lime.Director.FPS_INTERVAL) { this.fps = ((1000 * this.frames_) / this.accumDt_); goog.dom.setTextContent(this.fpsElement_, this.fps.toFixed(2)); this.frames_ = 0; this.accumDt_ = 0; } } lime.updateDirtyObjects(); }; /** * Replace current scene with new scene * @param {lime.Scene} scene New scene. * @param {function(lime.scene,lime.scene,boolean=)} opt_transition Transition played. * @param {number} opt_duration Duration of transition. */ lime.Director.prototype.replaceScene = function(scene, opt_transition, opt_duration) { scene.setSize(this.getSize().clone()); var transitionclass = opt_transition || lime.transitions.Transition; var outgoing = null; if (this.sceneStack_.length) outgoing = this.sceneStack_[this.sceneStack_.length - 1]; var removelist = []; var i = this.sceneStack_.length; while (--i >= 0) { this.sceneStack_[i].wasRemovedFromTree(); removelist.push(this.sceneStack_[i].domElement); this.sceneStack_[i].parent_ = null; } this.sceneStack_.length = 0; this.sceneStack_.push(scene); this.domElement.appendChild(scene.domElement); scene.parent_ = this; scene.wasAddedToTree(); var transition = new transitionclass(outgoing, scene).setFinishCallback( function() { var i = removelist.length; while (--i >= 0) { goog.dom.removeNode(removelist[i]); } }); if (goog.isDef(opt_duration)) { transition.setDuration(opt_duration); } transition.start(); }; /** @inheritDoc */ lime.Director.prototype.updateLayout = function() { // debugger; this.dirty &= ~lime.Dirty.LAYOUT; }; /** * Push scene to the top of scene stack * @param {lime.Scene} scene New scene. */ lime.Director.prototype.pushScene = function(scene) { this.sceneStack_.push(scene); this.domElement.appendChild(scene.domElement); scene.parent_ = this; scene.wasAddedToTree(); }; /** * Remove current scene from the stack */ lime.Director.prototype.popScene = function() { if (!this.sceneStack_.length) return; this.sceneStack_[this.sceneStack_.length - 1].wasRemovedFromTree(); this.sceneStack_[this.sceneStack_.length - 1].parent_ = null; goog.dom.removeNode(this.sceneStack_[this.sceneStack_.length - 1].domElement); this.sceneStack_.pop(); }; /** * Add CoverNode object to the viewport * @param {lime.CoverNode} cover Covernode. * @param {boolean} opt_addAboveDirector Cover is added above director object. */ lime.Director.prototype.addCover = function(cover, opt_addAboveDirector) { //mobile safari performes much better with this hack. needs investigation. if (goog.userAgent.WEBKIT && goog.userAgent.MOBILE) { if (opt_addAboveDirector) { this.coverElementAbove.appendChild(cover.domElement); } else { this.coverElementBelow.appendChild(cover.domElement); } } else { if (opt_addAboveDirector) { goog.dom.insertSiblingAfter(cover.domElement, this.domElement); } else { goog.dom.insertSiblingBefore(cover.domElement, this.domElement); } } cover.director = this; this.coverStack_.push(cover); }; /** * Remove CoverNode object from the viewport * @param {lime.CoverNode} cover Cover to remove. */ lime.Director.prototype.removeCover = function(cover) { goog.array.remove(this.coverStack_, cover); goog.dom.removeNode(cover.domElement); }; /** * Return bounds of director, * @param {goog.math.Box} box Edges. * @return {goog.math.Box} new bounds. */ lime.Director.prototype.getBounds = function(box) { //todo:This should basically be same as boundingbox on lime.node var position = this.getPosition(), scale = this.getScale(); return new goog.math.Box( box.top - position.y / scale.y, box.right - position.x / scale.x, box.bottom - position.y / scale.y, box.left - position.x / scale.x ); }; /** * @inheritDoc */ lime.Director.prototype.screenToLocal = function(coord) { var coord = coord.clone(); coord.x -= this.domOffset.x + this.position_.x; coord.y -= this.domOffset.y + this.position_.y; coord.x /= this.scale_.x; coord.y /= this.scale_.y; return coord; }; /** * @inheritDoc */ lime.Director.prototype.localToScreen = function(coord) { var coord = coord.clone(); coord.x *= this.scale_.x; coord.y *= this.scale_.y; coord.x += this.domOffset.x + this.position_.x; coord.y += this.domOffset.y + this.position_.y; return coord; }; /** * @inheritDoc */ lime.Director.prototype.update = function() { lime.Node.prototype.update.call(this); var i = this.coverStack_.length; while (--i >= 0) { this.coverStack_[i].update(true); } }; /** * Update dimensions based on viewport dimension changes * @private */ lime.Director.prototype.invalidateSize_ = function() { var stageSize = goog.style.getSize(this.domElement.parentNode); if (this.domElement.parentNode == document.body) { window.scrollTo(0, 0); if(goog.isNumber(window.innerHeight)){ stageSize.height = window.innerHeight; } } var realSize = this.getSize().clone().scaleToFit(stageSize); var scale = realSize.width / this.getSize().width; this.setScale(scale); if (stageSize.aspectRatio() < realSize.aspectRatio()) { this.setPosition(0, (stageSize.height - realSize.height) / 2); } else { this.setPosition((stageSize.width - realSize.width) / 2, 0); } this.updateDomOffset_(); }; /** * Add support for adding game to Springboard as a * web application on iOS devices */ lime.Director.prototype.makeMobileWebAppCapable = function() { var meta = document.createElement('meta'); meta.name = 'apple-mobile-web-app-capable'; meta.content = 'yes'; document.getElementsByTagName('head').item(0).appendChild(meta); meta = document.createElement('meta'); meta.name = 'apple-mobile-web-app-status-bar-style'; meta.content = 'black'; document.getElementsByTagName('head').item(0).appendChild(meta); var visited = false; if (goog.isDef(localStorage)) { visited = localStorage.getItem("_lime_visited"); } var ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent); if(ios && !window.navigator.standalone && COMPILED && !visited) { alert('Please install this page as a web app by clicking Share + Add to home screen.'); if (goog.isDef(localStorage)) { localStorage.setItem("_lime_visited",true); } } }; /** * Updates the cached value of directors parentelement position in the viewport * @private */ lime.Director.prototype.updateDomOffset_ = function() { this.domOffset = goog.style.getPageOffset(this.domElement.parentNode); }; /** * @inheritDoc */ lime.Director.prototype.hitTest = function(e) { if (e && e.screenPosition) e.position = this.screenToLocal(e.screenPosition); return true; };
lime/src/director.js
goog.provide('lime.Director'); goog.require('lime'); goog.require('lime.Node'); goog.require('lime.events.EventDispatcher'); goog.require('lime.helper.PauseScene'); goog.require('lime.scheduleManager'); goog.require('lime.transitions.Transition'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.ViewportSizeMonitor'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.math.Box'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Size'); goog.require('goog.math.Vec2'); goog.require('goog.style'); /** * Director object. Base object for every game. * @param {DOMElement} parentElement Parent element for director. * @constructor * @extends lime.Node */ lime.Director = function(parentElement) { lime.Node.call(this); // Unlike other nodes Director is always in the DOM as // it requires parentNode in the constructor this.inTree_ = true; this.setAnchorPoint(0, 0); // todo: maybe easier if director just positions itselt // to the center of the screen /** * Array of Scene instances. Last one is the active scene. * @type {Array.<lime.Scene>} * @private */ this.sceneStack_ = []; /** * Array of CoverNode instances. * @type {Array.<lime.CoverNode>} * @private */ this.coverStack_ = []; this.domClassName = goog.getCssName('lime-director'); this.createDomElement(); parentElement.appendChild(this.domElement); if (goog.userAgent.WEBKIT && goog.userAgent.MOBILE) { //todo: Not pretty solution. Cover layers may not be needed at all. this.coverElementBelow = document.createElement('div'); goog.dom.classes.add(this.coverElementBelow, goog.getCssName('lime-cover-below')); goog.dom.insertSiblingBefore(this.coverElementBelow, this.domElement); this.coverElementAbove = document.createElement('div'); goog.dom.classes.add(this.coverElementAbove, goog.getCssName('lime-cover-above')); goog.dom.insertSiblingAfter(this.coverElementAbove, this.domElement); } if (parentElement.style['position'] != 'absolute') { parentElement.style['position'] = 'relative'; } parentElement.style['overflow'] = 'hidden'; if (parentElement == document.body) { //todo: installstyles is better goog.style.installStyles('html,body{margin:0;padding:0;height:100%;}'); var meta=document.createElement('meta'); meta.name='viewport'; meta.content='width=device-width,initial-scale=1.0,minimum-scale=1,maximum-scale=1.0,user-scalable=no,target-densityDpi=device-dpi'; document.getElementsByTagName('head').item(0).appendChild(meta); window.scrollTo(0,0); } var width, parentSize = goog.style.getSize(parentElement); // todo: this 400x400 default should probably be constants instead this.setSize(new goog.math.Size( width = arguments[1] || parentSize.width || 400, arguments[2] || parentSize.height * width / parentSize.width || 400 )); // --define goog.debug=false this.setDisplayFPS(goog.DEBUG);//todo: connect with DEBUG flags this.setPaused(false); var vsm = new goog.dom.ViewportSizeMonitor(); goog.events.listen(vsm, goog.events.EventType.RESIZE, this.invalidateSize_, false, this); goog.events.listen(window, 'orientationchange', this.invalidateSize_, false, this); lime.scheduleManager.schedule(this.step_, this); this.eventDispatcher = new lime.events.EventDispatcher(this); // Prevent page scrolling on touch events goog.events.listen(this, 'touchmove', function(e) {e.event.preventDefault();}, false, this); // todo: check if all those are really neccessary as Event code // is much more mature now goog.events.listen(this, ['mouseup', 'touchend', 'mouseout', 'touchcancel'], function() {},false); this.invalidateSize_(); }; goog.inherits(lime.Director, lime.Node); /** * Milliseconds between recalculating FPS value * @const * @type {number} */ lime.Director.FPS_INTERVAL = 100; /** * Returns true if director is paused? On paused state * the update timer doesn't fire. * @return {boolean} If director is paused. */ lime.Director.prototype.isPaused = function() { return this.isPaused_; }; /** * Pauses or resumes the director * @param {boolean} value Pause or resume. * @return {lime.Director} The director object itself. */ lime.Director.prototype.setPaused = function(value) { this.isPaused_ = value; lime.scheduleManager.changeDirectorActivity(this, value ? 0 : 1); if (this.isPaused_) { this.pauseScene = new lime.helper.PauseScene(); this.pushScene(this.pauseScene); } else if (this.pauseScene) { this.popScene(); delete this.pauseScene; } return this; }; /** * Returns true if FPS counter is displayed * @return {boolean} FPS is displayed. */ lime.Director.prototype.isDisplayFPS = function() { return this.displayFPS_; }; /** * Show or hide FPS counter * @param {boolean} value Display FPS? * @return {lime.Director} The director object itself. */ lime.Director.prototype.setDisplayFPS = function(value) { if (this.displayFPS_ && !value) { goog.dom.removeNode(this.fpsElement_); } else if (!this.displayFPS_ && value) { this.frames_ = 0; this.accumDt_ = 0; this.fpsElement_ = goog.dom.createDom('div'); goog.dom.classes.add(this.fpsElement_, goog.getCssName('lime-fps')); this.domElement.parentNode.appendChild(this.fpsElement_); } this.displayFPS_ = value; return this; }; /** * Get current active scene * @return {lime.Scene} Currently active scene. */ lime.Director.prototype.getCurrentScene = function() { return this.sceneStack_.length ? this.sceneStack_[this.sceneStack_.length - 1] : null; }; /** @inheritDoc */ lime.Director.prototype.getDirector = function() { return this; }; /** @inheritDoc */ lime.Director.prototype.getScene = function() { return null; }; /** * Timeline function. * @param {number} delta Milliseconds since last step. * @private */ lime.Director.prototype.step_ = function(delta) { if (this.isDisplayFPS()) { this.frames_++; this.accumDt_ += delta; if (this.accumDt_ > lime.Director.FPS_INTERVAL) { this.fps = ((1000 * this.frames_) / this.accumDt_); goog.dom.setTextContent(this.fpsElement_, this.fps.toFixed(2)); this.frames_ = 0; this.accumDt_ = 0; } } lime.updateDirtyObjects(); }; /** * Replace current scene with new scene * @param {lime.Scene} scene New scene. * @param {function(lime.scene,lime.scene,boolean=)} opt_transition Transition played. * @param {number} opt_duration Duration of transition. */ lime.Director.prototype.replaceScene = function(scene, opt_transition, opt_duration) { scene.setSize(this.getSize().clone()); var transitionclass = opt_transition || lime.transitions.Transition; var outgoing = null; if (this.sceneStack_.length) outgoing = this.sceneStack_[this.sceneStack_.length - 1]; var removelist = []; var i = this.sceneStack_.length; while (--i >= 0) { this.sceneStack_[i].wasRemovedFromTree(); removelist.push(this.sceneStack_[i].domElement); this.sceneStack_[i].parent_ = null; } this.sceneStack_.length = 0; this.sceneStack_.push(scene); this.domElement.appendChild(scene.domElement); scene.parent_ = this; scene.wasAddedToTree(); var transition = new transitionclass(outgoing, scene).setFinishCallback( function() { var i = removelist.length; while (--i >= 0) { goog.dom.removeNode(removelist[i]); } }); if (goog.isDef(opt_duration)) { transition.setDuration(opt_duration); } transition.start(); }; /** @inheritDoc */ lime.Director.prototype.updateLayout = function() { // debugger; this.dirty &= ~lime.Dirty.LAYOUT; }; /** * Push scene to the top of scene stack * @param {lime.Scene} scene New scene. */ lime.Director.prototype.pushScene = function(scene) { this.sceneStack_.push(scene); this.domElement.appendChild(scene.domElement); scene.parent_ = this; scene.wasAddedToTree(); }; /** * Remove current scene from the stack */ lime.Director.prototype.popScene = function() { if (!this.sceneStack_.length) return; this.sceneStack_[this.sceneStack_.length - 1].wasRemovedFromTree(); this.sceneStack_[this.sceneStack_.length - 1].parent_ = null; goog.dom.removeNode(this.sceneStack_[this.sceneStack_.length - 1].domElement); this.sceneStack_.pop(); }; /** * Add CoverNode object to the viewport * @param {lime.CoverNode} cover Covernode. * @param {boolean} opt_addAboveDirector Cover is added above director object. */ lime.Director.prototype.addCover = function(cover, opt_addAboveDirector) { //mobile safari performes much better with this hack. needs investigation. if (goog.userAgent.WEBKIT && goog.userAgent.MOBILE) { if (opt_addAboveDirector) { this.coverElementAbove.appendChild(cover.domElement); } else { this.coverElementBelow.appendChild(cover.domElement); } } else { if (opt_addAboveDirector) { goog.dom.insertSiblingAfter(cover.domElement, this.domElement); } else { goog.dom.insertSiblingBefore(cover.domElement, this.domElement); } } cover.director = this; this.coverStack_.push(cover); }; /** * Remove CoverNode object from the viewport * @param {lime.CoverNode} cover Cover to remove. */ lime.Director.prototype.removeCover = function(cover) { goog.array.remove(this.coverStack_, cover); goog.dom.removeNode(cover.domElement); }; /** * Return bounds of director, * @param {goog.math.Box} box Edges. * @return {goog.math.Box} new bounds. */ lime.Director.prototype.getBounds = function(box) { //todo:This should basically be same as boundingbox on lime.node var position = this.getPosition(), scale = this.getScale(); return new goog.math.Box( box.top - position.y / scale.y, box.right - position.x / scale.x, box.bottom - position.y / scale.y, box.left - position.x / scale.x ); }; /** * @inheritDoc */ lime.Director.prototype.screenToLocal = function(coord) { var coord = coord.clone(); coord.x -= this.domOffset.x + this.position_.x; coord.y -= this.domOffset.y + this.position_.y; coord.x /= this.scale_.x; coord.y /= this.scale_.y; return coord; }; /** * @inheritDoc */ lime.Director.prototype.localToScreen = function(coord) { var coord = coord.clone(); coord.x *= this.scale_.x; coord.y *= this.scale_.y; coord.x += this.domOffset.x + this.position_.x; coord.y += this.domOffset.y + this.position_.y; return coord; }; /** * @inheritDoc */ lime.Director.prototype.update = function() { lime.Node.prototype.update.call(this); var i = this.coverStack_.length; while (--i >= 0) { this.coverStack_[i].update(true); } }; /** * Update dimensions based on viewport dimension changes * @private */ lime.Director.prototype.invalidateSize_ = function() { var stageSize = goog.style.getSize(this.domElement.parentNode); if (this.domElement.parentNode == document.body) { window.scrollTo(0, 0); if(goog.isNumber(window.innerHeight)){ stageSize.height = window.innerHeight; } } var realSize = this.getSize().clone().scaleToFit(stageSize); var scale = realSize.width / this.getSize().width; this.setScale(scale); if (stageSize.aspectRatio() < realSize.aspectRatio()) { this.setPosition(0, (stageSize.height - realSize.height) / 2); } else { this.setPosition((stageSize.width - realSize.width) / 2, 0); } this.updateDomOffset_(); }; /** * Add support for adding game to Springboard as a * web application on iOS devices */ lime.Director.prototype.makeMobileWebAppCapable = function() { var meta = document.createElement('meta'); meta.name = 'apple-mobile-web-app-capable'; meta.content = 'yes'; document.getElementsByTagName('head').item(0).appendChild(meta); meta = document.createElement('meta'); meta.name = 'apple-mobile-web-app-status-bar-style'; meta.content = 'black'; document.getElementsByTagName('head').item(0).appendChild(meta); var visited = false; if (goog.isDef(localStorage)) { visited = localStorage.getItem("_lime_visited"); } var ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent); if(ios && !window.navigator.standalone && COMPILED && !visited) { alert('Please install this page as a web app by clicking Share + Add to home screen.'); if (goog.isDef(localStorage)) { localStorage.setItem("_lime_visited",true); } } }; /** * Updates the cached value of directors parentelement position in the viewport * @private */ lime.Director.prototype.updateDomOffset_ = function() { this.domOffset = goog.style.getPageOffset(this.domElement.parentNode); }; /** * @inheritDoc */ lime.Director.prototype.hitTest = function(e) { if (e && e.screenPosition) e.position = this.screenToLocal(e.screenPosition); return true; };
Limit densityDpi to only Android devices
lime/src/director.js
Limit densityDpi to only Android devices
<ide><path>ime/src/director.js <ide> <ide> var meta=document.createElement('meta'); <ide> meta.name='viewport'; <del> meta.content='width=device-width,initial-scale=1.0,minimum-scale=1,maximum-scale=1.0,user-scalable=no,target-densityDpi=device-dpi'; <add> var content = 'width=device-width,initial-scale=1.0,minimum-scale=1,maximum-scale=1.0,user-scalable=no'; <add> if((/android/i).test(navigator.userAgent)){ <add> content+=',target-densityDpi=device-dpi'; <add> } <add> <add> meta.content = content; <ide> document.getElementsByTagName('head').item(0).appendChild(meta); <ide> window.scrollTo(0,0); <ide> }
Java
apache-2.0
e7bcc31885c2f6958ae1944a8d7ed0e7664af3e6
0
kdbanman/nodes
package nodes; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import nodes.Modifier.ModifierType; import nodes.controllers.ModifiersListBox; import org.apache.jena.riot.RiotException; import controlP5.Button; import controlP5.CallbackEvent; import controlP5.CallbackListener; import controlP5.ColorPicker; import controlP5.ControlEvent; import controlP5.ControlP5; import controlP5.DropdownList; import controlP5.Group; import controlP5.ListBox; import controlP5.RadioButton; import controlP5.Slider; import controlP5.Tab; import controlP5.Textfield; import controlP5.Toggle; import processing.core.PVector; import processing.core.PApplet; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; /** * * @author kdbanman */ public class ControlPanel extends PApplet implements Selection.SelectionListener { private static final long serialVersionUID = 7771053293767517965L; int w, h; ControlP5 cp5; Graph graph; // update flag raised if the controllers have not responded to a change in // selection. see selectionChanged() and draw(). AtomicBoolean selectionUpdated; // for copy/paste by keyboard Clipboard clipboard; // control element size parameters int tabHeight; int padding; int elementHeight; int labelledElementHeight; int buttonWidth; int buttonHeight; int modifiersBoxHeight; // Control elements that need to be accessed outside of setup() // copy/paste menu Button copyButton; Button pasteButton; Button clearButton; // tab and subtab containing autolayout so that it can be stopped if the // user leaves either of those tabs Tab transformTab; Group positionGroup; // subtab lists and open tab reference to be manipulated in draw() so that // they behave as tabs ArrayList<Group> importSubTabs; Group openImportSubTab; ArrayList<Group> transformSubTabs; Group openTransformSubTab; ArrayList<Group> saveSubTabs; Group openSaveSubTab; // text field for user-input URIs for description retrieval from the web Textfield importWebURI; // text field for sparql endpoint uri or ip addr for querying uri nbrhoods Textfield importSparqlEndpoint; // text field for sparql query formation Textfield sparqlQueryURI; // text field for file import location Textfield fileImportLocation; // menu for file import query entity uri DropdownList fileImportEntityMenu; // text field for rdf-xml filename save location Textfield dataFilename; // text field for project filename (save/load location) Textfield projectFilename; // Modifier list controller ModifiersListBox modifiersBox; // Lists of modifiers and modifiersets private Collection<Modifier> modifiers = Collections.emptyList(); private Collection<ModifierSet> modifiersets = Collections.emptyList(); // Map of list indexes to each modifier private final ConcurrentHashMap<Integer, Modifier> uiModifiers = new ConcurrentHashMap<Integer, Modifier>(); // radio for radial layout sorting order (lexico or numerical) RadioButton sortOrder; // radio for position scaling direction (expansion or contraction) RadioButton scaleDirection; // toggle button for laying out the entire graph (force-directed algorithm) Toggle autoLayout; // controller group for colorizing selected nodes and edges ColorPicker colorPicker; // since colorpicker is a controlgroup, and its events can't be handled with // the listener architecture like *everything* else, this flag is necessary // so that changes in colorpicker as it reacts to selection changes do not // propagate to element color changes. boolean changeElementColor; Slider sizeSlider; Slider labelSizeSlider; public ControlPanel(int frameWidth, int frameHeight, Graph parentGraph) { w = frameWidth; h = frameHeight; // initialize graph graph = parentGraph; selectionUpdated = new AtomicBoolean(); // for copy/paste clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // element size parameters padding = 10; tabHeight = 30; elementHeight = 20; labelledElementHeight = 40; buttonWidth = 100; buttonHeight = 30; modifiersBoxHeight = 200; // sub tab lists to manipulate in draw() for tab behaviour importSubTabs = new ArrayList<>(); transformSubTabs = new ArrayList<>(); saveSubTabs = new ArrayList<>(); } @Override public void setup() { // subscribe to changes in selection. see overridden selectionChanged() graph.getSelection().addListener(this); size(w, h); cp5 = new ControlP5(this) .setMoveable(false); // define main controller tabs Tab importTab = cp5.addTab("Load Triples") .setWidth(w / 4) .setHeight(tabHeight) .setActive(true); // transformTab is defined externally so that autolayout can be stopped // if the tab is left by the user transformTab = cp5.addTab("Transform") .setWidth(w / 4) .setHeight(tabHeight); @SuppressWarnings("unused") //will probably have later use Tab optionTab = cp5.addTab("Options") .setWidth(w / 4) .setHeight(tabHeight); Tab saveTab = cp5.addTab("Save/Load") .setWidth(w / 4) .setHeight(tabHeight); cp5.getDefaultTab().remove(); // copy/paste 'menu' copyButton = cp5.addButton("Copy to Clipboard") .setWidth(buttonWidth) .setHeight(elementHeight) .setVisible(false) .addCallback(new CopyListener()); pasteButton = cp5.addButton("Paste from Clipboard") .setWidth(buttonWidth) .setHeight(elementHeight) .setVisible(false) .addCallback(new PasteListener()); clearButton = cp5.addButton("Clear Field") .setWidth(buttonWidth) .setHeight(elementHeight) .setVisible(false) .addCallback(new ClearListener()); //=========== // Import tab //=========== // triple import subtabs //////////////////////// int importTabsVert = 2 * tabHeight + padding; Group webGroup = new SubTab(cp5, "Web") .setBarHeight(tabHeight) .setPosition(0, importTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(true) .moveTo(importTab); Group sparqlGroup = new SubTab(cp5, "SPARQL") .setBarHeight(tabHeight) .setPosition(w / 4, importTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(importTab); Group fileGroup = new SubTab(cp5, "File") .setBarHeight(tabHeight) .setPosition(w / 2, importTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(importTab); // register triple import subtabs so that they may be manipulated in // draw() to behave as tabs importSubTabs.add(webGroup); importSubTabs.add(sparqlGroup); importSubTabs.add(fileGroup); openImportSubTab = webGroup; // Web import elements importWebURI = cp5.addTextfield("Entity or Document URI", padding, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .moveTo(webGroup) .setText("http://www.w3.org/1999/02/22-rdf-syntax-ns") .addCallback(new CopyPasteMenuListener()); cp5.addButton("Query Web") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding, labelledElementHeight + padding) .moveTo(webGroup) .addCallback(new QueryWebListener()); // SPARQL import elements importSparqlEndpoint = cp5.addTextfield("Endpoint IP:Port or URL", padding - w / 4, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .setText("http://dbpedia.org/sparql") .addCallback(new CopyPasteMenuListener()) .moveTo(sparqlGroup); sparqlQueryURI = cp5.addTextfield("Entity URI ", padding - w / 4, labelledElementHeight + padding, w - 2 * padding, elementHeight) .setAutoClear(false) .setText("http://dbpedia.org/resource/Albert_Einstein") .addCallback(new CopyPasteMenuListener()) .moveTo(sparqlGroup); cp5.addButton("Query Endpoint") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding - w / 4, 3 * labelledElementHeight + padding) .addCallback(new QuerySparqlListener()) .moveTo(sparqlGroup); // File import elements fileImportLocation = cp5.addTextfield("File Path (Relative or Absolute)", padding - w / 2, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .addCallback(new CopyPasteMenuListener()) .moveTo(fileGroup); cp5.addButton("Select File") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding - w / 2, labelledElementHeight + 2 * padding) .addCallback(new SelectFileListener()) .moveTo(fileGroup); // fileImportEntityMenu is technically the next in order of appearance, // but is initialized last so it renders on top of the rest of fileGroup cp5.addButton("Query File") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding - w / 2, 2 * labelledElementHeight + buttonHeight + 4 * padding) .addCallback(new FileQueryListener()) .moveTo(fileGroup); fileImportEntityMenu = cp5.addDropdownList("Entity of Interest (Optional)") .setPosition(padding - w / 2, labelledElementHeight + buttonHeight + 5 * padding) .setSize(w - 3 * padding - buttonWidth, h - padding - (90 + labelledElementHeight + buttonHeight + 4 * padding)) .setItemHeight(elementHeight) .setBarHeight(elementHeight) .moveTo(fileGroup); //============== // Transform tab //============== // modifier list controller modifiersBox = new ModifiersListBox(cp5, (Tab) cp5.controlWindow .getTabs().get(1), "ModifiersBox", padding, tabHeight + padding, w - 2 * padding, modifiersBoxHeight); //equivalent to cp5.AddListBox cp5.register(null, "", modifiersBox); modifiersBox.registerProperty("listBoxItems") .registerProperty("value") .setBarHeight(tabHeight) .setItemHeight(elementHeight) .setScrollbarWidth(elementHeight) .moveTo(transformTab) .hideBar(); //get a list of modifiers and modifiersets try { modifiers = graph.getModifiersList(); modifiersets = graph.getModifierSetsList(); } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: getting list of Modifiers/ModifierSets"); } populateModifierMenu(); // Transformation subtabs ///////////////////////// // vertical positiion of transformation subtabs int transformTabsVert = modifiersBoxHeight + 3 * tabHeight + padding; // positionGroup is defined externally so that autolayout can be stopped // if the tab is left by the user positionGroup = new SubTab(cp5, "Layout") .setBarHeight(tabHeight) .setPosition(0, transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(true) .moveTo(transformTab); Group colorSizeGroup = new SubTab(cp5, "Color and Size") .setBarHeight(tabHeight) .setPosition(w / 4, transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(transformTab); Group labelGroup = new SubTab(cp5, "Label") .setBarHeight(tabHeight) .setPosition(w / 2, transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(transformTab); Group hideGroup = new SubTab(cp5, "Delete") .setBarHeight(tabHeight) .setPosition(3 * (w / 4), transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(transformTab); // register transformation subtabs so that they may be manipulated in // draw() to behave as tabs transformSubTabs.add(positionGroup); transformSubTabs.add(colorSizeGroup); transformSubTabs.add(labelGroup); transformSubTabs.add(hideGroup); openTransformSubTab = positionGroup; // Layout controllers cp5.addButton("Scale Positions") .setPosition(padding, padding) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(positionGroup) .addCallback(new ScaleLayoutListener()); scaleDirection = cp5.addRadio("Scale Direction") .setPosition(2 * padding + buttonWidth, padding) .setItemHeight(buttonHeight / 2) .moveTo(positionGroup) .addItem("Expand from center", 0) .addItem("Contract from center", 1) .activate(0); cp5.addButton("Radial Sort") .setPosition(padding, 2 * padding + buttonHeight) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(positionGroup) .addCallback(new RadialLayoutListener()); sortOrder = cp5.addRadio("Sort Order") .setPosition(2 * padding + buttonWidth, 2 * padding + buttonHeight) .setItemHeight(buttonHeight / 2) .moveTo(positionGroup) .addItem("Numerical Order", 0) .addItem("Alphabetical Order", 1) .activate(0); autoLayout = cp5.addToggle("Autolayout Entire Graph") .setPosition(padding, 4 * padding + 3 * buttonHeight) .setHeight(elementHeight) .setWidth(buttonWidth) .moveTo(positionGroup); cp5.addButton("Center Camera") .setPosition(width - buttonWidth - padding, 4 * padding + 3 * buttonHeight) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(positionGroup) .addCallback(new CenterCameraListener()); // color and size controllers //NOTE: ColorPicker is a ControlGroup, not a Controller, so I can't // attach a callback to it. It's functionality is in the // controlEvent() function of the ControlPanel colorPicker = cp5.addColorPicker("Color") .setPosition(-(w / 4) + padding, padding) .moveTo(colorSizeGroup); changeElementColor = true; sizeSlider = cp5.addSlider("Size") .setPosition(-(w / 4) + padding, 2 * padding + 80) .setHeight(elementHeight) .setWidth(w - 80) .setRange(5, 100) .setValue(10) .moveTo(colorSizeGroup) .addCallback(new ElementSizeListener()); // label controllers cp5.addButton("Show Labels") .setPosition(padding - w / 2, padding) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(labelGroup) .addCallback(new ShowLabelListener()); cp5.addButton("Hide Labels") .setPosition(padding - w / 2, buttonHeight + 2 * padding) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(labelGroup) .addCallback(new HideLabelListener()); labelSizeSlider = cp5.addSlider("Label Size") .setPosition(padding - w / 2, padding * 3 + 2 * buttonHeight) .setWidth(w - 80) .setHeight(elementHeight) .setRange(5, 100) .setValue(10) .moveTo(labelGroup) .addCallback(new LabelSizeListener()); // visibility controllers cp5.addButton("Delete Selection") .setPosition(padding - 3 * (w / 4), padding) .setSize(buttonWidth, buttonHeight) .moveTo(hideGroup) .addCallback(new ElementRemovalListener()); // change color picker, size slider, and label size slider to reflect selection updateControllersToSelection(); //============ // Options tab //============ //============== // Save/Load tab //============== // save/load subtabs //////////////////////// int saveTabsVert = 2 * tabHeight + padding; Group dataGroup = new SubTab(cp5, "Save Data") .setBarHeight(tabHeight) .setPosition(0, saveTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(true) .moveTo(saveTab); Group projectGroup = new SubTab(cp5, "Save/Load Project") .setBarHeight(tabHeight) .setPosition(w / 4, saveTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(saveTab); // register save subtabs so that they may be manipulated in // draw() to behave as tabs saveSubTabs.add(dataGroup); saveSubTabs.add(projectGroup); openSaveSubTab = dataGroup; // Data save elements dataFilename = cp5.addTextfield("RDF-XML Filename", padding, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .moveTo(dataGroup) .setText("myData.rdf") .addCallback(new CopyPasteMenuListener()); cp5.addButton("Save RDF-XML") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding, labelledElementHeight + padding) .moveTo(dataGroup) .addCallback(new SaveTriplesListener()); // Project Save elements projectFilename = cp5.addTextfield("Project Name", padding - w / 4, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .moveTo(projectGroup) .setText("myProject.nod") .addCallback(new CopyPasteMenuListener()); cp5.addButton("Save Project") .setSize(buttonWidth, buttonHeight) .setPosition(3 * w / 4 - buttonWidth - padding, labelledElementHeight + padding) .moveTo(projectGroup) .addCallback(new SaveProjectListener()); cp5.addButton("Load Project") .setSize(buttonWidth, buttonHeight) .setPosition(3 * w / 4 - buttonWidth - padding, 3 * labelledElementHeight + padding) .moveTo(projectGroup) .addCallback(new LoadProjectListener()); } public String getHttpSparqlEndpoint() { return importSparqlEndpoint.getText(); } public boolean autoLayoutSelected() { return autoLayout.getState(); } // all controlP5 controllers are drawn after draw(), so herein lies any // arbiter-style controller logic, as well as miscellaneous actions that // must occur every frame. @Override public void draw() { // make subTabs perform as tabs instead of Groups for (Group subTab : transformSubTabs) { if (subTab.isOpen() && subTab != openTransformSubTab) { openTransformSubTab.setOpen(false); openTransformSubTab = subTab; } } for (Group subTab : importSubTabs) { if (subTab.isOpen() && subTab != openImportSubTab) { openImportSubTab.setOpen(false); openImportSubTab = subTab; } } for (Group subTab : saveSubTabs) { if (subTab.isOpen() && subTab != openSaveSubTab) { openSaveSubTab.setOpen(false); openSaveSubTab = subTab; } } // stop autoLayout if any other tab is selected if (autoLayout.getState() && (!transformTab.isOpen() || !positionGroup.isOpen())) { autoLayout.setState(false); } // update controllers to selection if selection has changed since // last draw() call if (selectionUpdated.getAndSet(false)) { // populate the dynamic, selection-dependent selection modifier menu populateModifierMenu(); // change color picker, size slider, and label size slider to reflect selection updateControllersToSelection(); } background(0); } /** * Callback for import file selection dialog. */ public void importFileSelected(File selection) { if (selection == null) { //user closed window or hit cancel } else { fileImportLocation.setText(selection.getAbsolutePath()); Model entityListTmp = null; try { entityListTmp = IO.getDescription(fileImportLocation.getText()); } catch (RiotException e) { logEvent(fileImportLocation.getText()); logEvent("Error: Valid RDF not contained within:\n"); } finally { populateFileEntityMenu(entityListTmp); } } } /** * Populate the entity selection menu for file import with all subjects of * triples within the model. Objects of triples are ignored. */ public void populateFileEntityMenu(Model fileModel) { fileImportEntityMenu.clear(); if (fileModel != null) { TreeSet<String> resources = new TreeSet<>(); ResIterator objects = fileModel.listSubjects(); while (objects.hasNext()) { Resource node = objects.next(); resources.add(node.getURI()); } int i = 0; for (String resource : resources) { fileImportEntityMenu.addItem(resource, i); fileImportEntityMenu.getItem(i).setText(fileModel.shortForm(resource)); i++; } } } // every time selection is changed, this is called @Override public void selectionChanged() { // queue controller selection update if one is not already queued selectionUpdated.compareAndSet(false, true); } // called every time cp5 broadcasts an event. since ControlGroups cannot // have specific listeners, their actions must be dealt with here. public void controlEvent(ControlEvent event) { // adjust color of selected elements (if event is not from selection update) if (changeElementColor && event.isFrom(colorPicker)) { int newColor = colorPicker.getColorValue(); for (GraphElement<?> e : graph.getSelection()) { e.setColor(newColor); } } else if (event.isFrom(modifiersBox)) { try { uiModifiers.get((int) event.getValue()).modify(); } catch (Exception e) { e.printStackTrace(); } } } // called whenever the mouse is released within the control panel @Override public void mouseReleased() { //clear the copy paste menu if the left mouse button is clicked outside // of any part of the menu if (!(copyButton.isInside() || pasteButton.isInside() || clearButton.isInside()) && mouseButton == LEFT) { copyButton.setVisible(false); pasteButton.setVisible(false); clearButton.setVisible(false); } } public void updateControllersToSelection() { // do not change element colors with the resulting ControlEvent here changeElementColor = false; colorPicker.setColorValue(graph.getSelection().getColorOfSelection()); changeElementColor = true; sizeSlider.setValue(graph.getSelection().getSizeOfSelection()); labelSizeSlider.setValue(graph.getSelection().getLabelSizeOfSelection()); } // log event in infopanel private void logEvent(String s) { graph.pApp.logEvent(s); } /* * ControlP5 does not support nesting tabs within other tabs, so this is an * extension of controller Groups to behave as nested tabs. NOTE: the * tab-behaviour control logic is maintained for each group of tabs * by a list of each member of the group and a reference to whichever tab is * currently open in the group. these are defined as fields in ControlPanel * and are manipulated within draw(). */ private class SubTab extends Group { SubTab(ControlP5 theControlP5, String theName) { // call Group constructor super(theControlP5, theName); } @Override protected void postDraw(PApplet theApplet) { // draw the group with the color behaviour of a Tab instead of a Group if (isBarVisible) { theApplet.fill(isOpen ? color.getActive() : (isInside ? color.getForeground() : color.getBackground())); theApplet.rect(0, -1, _myWidth - 1, -_myHeight); _myLabel.draw(theApplet, 0, -_myHeight-1, this); if (isCollapse && isArrowVisible) { theApplet.fill(_myLabel.getColor()); theApplet.pushMatrix(); if (isOpen) { theApplet.triangle(_myWidth - 10, -_myHeight / 2 - 3, _myWidth - 4, -_myHeight / 2 - 3, _myWidth - 7, -_myHeight / 2); } else { theApplet.triangle(_myWidth - 10, -_myHeight / 2, _myWidth - 4, -_myHeight / 2, _myWidth - 7, -_myHeight / 2 - 3); } theApplet.popMatrix(); } } } } /***************************** * Import controller listeners ****************************/ /* * attach to a Textfield for copy/paste dropdown menu on right click. * each textfield needs its own unique instance (one controller per listener * is a controlP5 thing (and maybe even a general thing). technically this * risks concurrent modification of the copy and paste buttons, but the odds * of near-simultaneous right-clicks on textfields is low. */ private class CopyPasteMenuListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_PRESSED && mouseButton == RIGHT) { // textfields occur in multiple tabs, so the menu must be moved // to the corret tab Tab activeTab = event.getController().getTab(); // move each button sequentially below the cursor copyButton.setPosition(mouseX, mouseY) .setVisible(true) .moveTo(activeTab) .bringToFront(); pasteButton.setPosition(mouseX, mouseY + elementHeight) .setVisible(true) .moveTo(activeTab) .bringToFront(); clearButton.setPosition(mouseX, mouseY + 2 * elementHeight) .setVisible(true) .moveTo(activeTab) .bringToFront(); } } } /* * attach to button for copying from active textfield */ private class CopyListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get active text field for (Textfield c : cp5.getAll(Textfield.class)) { if (c.isActive()) { // get text field contents and copy to clipboard String fieldContents = c.getText(); StringSelection data = new StringSelection(fieldContents); // data is passed as both parameters because of an // unimplemented feature in AWT clipboard.setContents(data, data); } } } } } /* * attach to button for pasting to active textfield */ private class PasteListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get active text field for (Textfield c : cp5.getAll(Textfield.class)) { if (c.isActive()) { // separate current textfield contents about cursor position int idx = c.getIndex(); String before = c.getText().substring(0, idx); String after = ""; if (c.getIndex() != c.getText().length()) { after = c.getText().substring(idx, c.getText().length()); } // get (valid) clipboard contents and insert at cursor position Transferable clipData = clipboard.getContents(this); String s = ""; try { s = (String) (clipData.getTransferData(DataFlavor.stringFlavor)); } catch (UnsupportedFlavorException | IOException ee) { System.out.println("Cannot paste clipboard contents."); } c.setText(before + s + after); } } } } } /* * attach to button for clearing active text field */ private class ClearListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get active text field for (Textfield c : cp5.getAll(Textfield.class)) { if (c.isActive()) { c.clear(); } } } } } /* * attach to web query button in import tab to enable retrieval of rdf * descriptions as published at resources' uris. */ private class QueryWebListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get uri from text field String uri = importWebURI.getText(); Model toAdd; try { toAdd = IO.getDescription(uri); } catch (RiotException e) { logEvent("Valid RDF not hosted at uri \n " + uri); return; } // add the retrived model to the graph (toAdd is empty if // an error was encountered). // log results to user. graph.addTriplesLogged(toAdd); logEvent("From uri:\n " + uri + "\n "); } } } /* * attach to sparql query button for sparql query functionality */ private class QuerySparqlListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get endpoint uri String endpoint = importSparqlEndpoint.getText(); // get uri from text field and form query String uri = sparqlQueryURI.getText(); // retrieve description as a jena model Model toAdd; try { toAdd = IO.getDescriptionSparql(endpoint, uri); } catch (Exception e) { logEvent("Valid RDF not returned from endpoint:\n" + endpoint); return; } // add the retriveed model to the graph (toAdd is empty if // an error was encountered) // log results. graph.addTriplesLogged(toAdd); logEvent("From endpoint:\n" + endpoint + "\n\n" + "about uri: \n" + uri + "\n "); } } } private class SelectFileListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { ControlPanel.this.selectFolder("Select RDF File:", "importFileSelected"); } } } private class FileQueryListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get uris from text fields String docUri = fileImportLocation.getText(); // if the user did not specify an entity to describe, first entity of list will be queried because of controlp5 behaviour String entityUri = ""; if (fileImportEntityMenu.getListBoxItems().length > 0) { entityUri = fileImportEntityMenu.getItem((int)fileImportEntityMenu.getValue()).getName(); } Model toAdd; try { toAdd = IO.getDescription(docUri, entityUri); } catch (RiotException e) { logEvent("Error encountered reading RDF from\n " + docUri); return; } //NOTE: the logged items will be in reverse order as they appear below. RDFNode entityAsResource = toAdd.createResource(entityUri); if (toAdd.containsResource(entityAsResource)) { // add the retrived model to the graph (toAdd is empty if // an IO error was encountered). // log results to user. graph.addTriplesLogged(toAdd); logEvent("Describing entity:\n " + entityUri + "\n "); } else { logEvent("Warning: entity:\n " + entityUri + "\n not found!\n"); } // add the retrived model to the graph (toAdd is empty if // an IO error was encountered). // log results to user. graph.addTriplesLogged(toAdd); logEvent("From file:\n " + docUri + "\n "); } } } /************************************* * Transformation controller listeners ************************************/ /* * attach to layout scale button to enable expansion/contraction of the positions * of each node in the selection about their average center. */ private class ScaleLayoutListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // calculate center of current selection of nodes PVector center = new PVector(); for (Node n : graph.getSelection().getNodes()) { center.add(n.getPosition()); } center.x = center.x / graph.getSelection().nodeCount(); center.y = center.y / graph.getSelection().nodeCount(); center.z = center.z / graph.getSelection().nodeCount(); // set scale based on user selection. // index 0 == expand, 1 == contract float scale; if (scaleDirection.getState(0)) scale = -0.2f; else scale = 0.2f; // scale each node position outward or inward from center for (Node n : graph.getSelection().getNodes()) { n.getPosition().lerp(center, scale); } } } } /* * attach to button that centers PApplet camera on center of graph at a * heuristically calculated distance to contain most of the graph */ private class CenterCameraListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { Iterator<GraphElement<?>> it; if (graph.getSelection().empty()) { it = graph.iterator(); } else { it = graph.getSelection().iterator(); } if (it.hasNext()) { GraphElement<?> first = it.next(); // calculate center of graph PVector center = first.getPosition().get(); float minX = center.x; float maxX = center.x; float minY = center.y; float maxY = center.y; float minZ = center.z; float maxZ = center.z; float minCamDist = 15 * first.getSize(); float nodeCount = 1f; while (it.hasNext()) { GraphElement<?> e = it.next(); if (e instanceof Edge) continue; Node n = (Node) e; PVector nPos = n.getPosition(); center.add(n.getPosition()); minX = Nodes.min(minX, nPos.x); maxX = Nodes.max(maxX, nPos.x); minY = Nodes.min(minY, nPos.y); maxY = Nodes.max(maxY, nPos.y); minZ = Nodes.min(minZ, nPos.z); maxZ = Nodes.max(maxZ, nPos.z); nodeCount += 1f; } center.x = center.x / (float) nodeCount; center.y = center.y / (float) nodeCount; center.z = center.z / (float) nodeCount; float avgDist = (maxX - minX + maxY - minY + maxZ - minZ) / 3; // set camera graph.pApp.cam.lookAt(center.x, center.y, center.z); graph.pApp.cam.setDistance(Nodes.max(minCamDist, 1.3f * avgDist)); } } } } /* * attach to radial sort button. selected nodes are laid out in a circle * whose axis is perpendicular to the screen and whose radius is chosen to * accomodate all the nodes with a bit of room to spare. the nodes will * be ordered along the circumference lexicographically or numerically, * depending on the state of a separate radio button called sortOrder. */ private class RadialLayoutListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get array of names of selected nodes (Selection stores // things as HashSets, which are not sortable) String[] names = new String[graph.getSelection().nodeCount()]; int i = 0; for (Node n : graph.getSelection().getNodes()) { names[i] = n.getName(); i++; } // sort the array of names according to the user choice // index 0 == numerical, 1 == lexicographical if (sortOrder.getState(0)) { quickSort(names, 0, names.length - 1, true); } else { // lexicographical sort implicit quickSort(names, 0, names.length - 1, false); } // calculate radius of circle from number and size of nodes // along with the midpoint of the nodes PVector center = new PVector(); float maxSize = 0; for (Node n : graph.getSelection().getNodes()) { center.add(n.getPosition()); maxSize = Nodes.max(maxSize, n.getSize()); } // radius is circumference / 2pi, but this has been adjusted for appearance float radius = (float) ((float) graph.getSelection().nodeCount() * 2 * maxSize) / (Nodes.PI); // center is average position center.x = center.x / graph.getSelection().nodeCount(); center.y = center.y / graph.getSelection().nodeCount(); center.z = center.z / graph.getSelection().nodeCount(); // get horizontal and vertical unit vectors w.r.t. screen PVector horiz = graph.proj.getScreenHoriz(); //upper left corner graph.proj.calculatePickPoints(0, 0); PVector vert = graph.proj.getScreenVert(); // angular separation of nodes is 2pi / number of nodes float theta = 2 * Nodes.PI / (float) graph.getSelection().nodeCount(); float currAngle = 0; // lay out the selected nodes in the new order in a circle // whose axis is orthogonal to the screen for (String name : names) { Node n = graph.getNode(name); PVector hComp = horiz.get(); hComp.mult(Nodes.cos(currAngle) * radius); PVector vComp = vert.get(); vComp.mult(Nodes.sin(currAngle) * radius); hComp.add(vComp); n.setPosition(hComp); currAngle += theta; } } } // standard quicksort implementation with a boolean parameter to // indicate numerical or lexicographical ordering of the strings private void quickSort(String[] arr, int p, int r, boolean numerical) { if (p < r) { int pivot = partition(arr, p, r, numerical); quickSort(arr, p, pivot - 1, numerical); quickSort(arr, pivot + 1, r, numerical); } } // quicksort partition function with choice of sort order private int partition(String[] arr, int p, int r, boolean numerical) { String pivot = arr[r]; int swap = p - 1; for (int j = p ; j < r ; j++) { boolean greaterThanPivot; if (numerical) greaterThanPivot = numLess(arr[j], pivot); else greaterThanPivot = lexLess(arr[j], pivot); if (greaterThanPivot) { swap++; String tmp = arr[swap]; arr[swap] = arr[j]; arr[j] = tmp; } } String tmp = arr[swap + 1]; arr[swap + 1] = arr[r]; arr[r] = tmp; return swap + 1; } // numerical string comparison private boolean numLess(String left, String right) { if (left.length() > right.length()) { return false; } else if (left.length() < right.length()) { return true; } return lexLess(left, right); } // lexicographical string comparison private boolean lexLess(String left, String right) { return left.compareToIgnoreCase(right) < 0; } } /* * attach to element size slider to enable node/edge size manipulation */ private class ElementSizeListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED || event.getAction() == ControlP5.ACTION_RELEASEDOUTSIDE) { // get the size from the slider control int newSize = 10; try { newSize = (int) ((Slider) event.getController()).getValue(); } catch (Exception e) { System.out.println("ERROR: ElementSizeListener not hooked up to a Slider."); } // apply the new size to each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setSize(newSize); } } } } /* * attach to hide label button to enable label-showing control */ private class HideLabelListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // hide label for each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setDisplayLabel(false); } } } } /* * attach to show label button to enable label-hiding control */ private class ShowLabelListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // show each label for each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setDisplayLabel(true); } } } } /* * attach to label size slider to enable label size control */ private class LabelSizeListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED || event.getAction() == ControlP5.ACTION_RELEASEDOUTSIDE) { int newSize = 10; // get the new size from the slider control try { newSize = (int) ((Slider) event.getController()).getValue(); } catch (Exception e) { System.out.println("ERROR: LabelSizeListener not hooked up to a Slider."); } // apply the new label size to each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setLabelSize(newSize); } } } } /* * attach to element removal button to enable removal of any subset of * the graph's nodes or edges */ private class ElementRemovalListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // hold graph drawing while controllers are removed graph.pApp.waitForNewFrame(this); // for both removal loops below, deep copies of the selected // nodes and edges are created. the removal calls still work // because the Graph.remove*(GraphElement) methods are wrappers // for Graph.remove*(String) methods (only names matter) HashSet<Node> nodesCopy = new HashSet<>(graph.getSelection().getNodes()); // remove all nodes in the selection (this will remove all // connected edges for (Node n : nodesCopy) { // nodes may have been removed between iterations, so check // membership before removal. if (graph.getSelection().contains(n)) graph.removeNode(n); } HashSet<Edge> edgesCopy = new HashSet<>(graph.getSelection().getEdges()); // remove all remaining edges in the selection for (Edge e : edgesCopy) { // edges may have been removed between iterations, so check // membership before removal. if (graph.getSelection().contains(e)) graph.removeEdge(e); } graph.pApp.restartRendering(this); } } } /* * saves rendered triples to an rdf-xml file as named by the respective text box */ private class SaveTriplesListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(dataFilename.getText()), "utf-8")); graph.getRenderedTriples().write(writer); logEvent("RDF-XML file " + dataFilename.getText() + "\nsaved to application directory."); } catch (IOException ex) { logEvent("Failed to save file " + dataFilename.getText()); } finally { try {writer.close();} catch (Exception ex) {} } } } } /* * saves the (relevant) current state of the Nodes application to be loaded * at a later date. */ private class SaveProjectListener implements CallbackListener { /* * TODO */ @Override public void controlEvent(CallbackEvent ce) { throw new UnsupportedOperationException("Not supported yet."); } } /* * loads previously saved application state. */ private class LoadProjectListener implements CallbackListener { /* * TODO */ @Override public void controlEvent(CallbackEvent ce) { throw new UnsupportedOperationException("Not supported yet."); } } /* * Refreshes the visual modifiers menu list */ private void populateModifierMenu() { if (modifiersBox == null || (modifiers.isEmpty() && modifiersets.isEmpty())) return; uiModifiers.clear(); modifiersBox.clear(); for (Modifier m : modifiers) { if ((m.getType() == ModifierType.ALL || m.getType() == ModifierType.PANEL) && m.isCompatible()) { modifiersBox.addItem(m.getTitle(), uiModifiers.size()); uiModifiers.put(uiModifiers.size(), m); } } for (ModifierSet s : modifiersets) { if (s.getType() != ModifierType.ALL || s.getType() != ModifierType.PANEL) continue; if ((s.getType() == ModifierType.ALL || s.getType() == ModifierType.PANEL) && s.isCompatible()) { s.constructModifiers(); for (Modifier m : s.getModifiers()) { modifiersBox.addItem(m.getTitle(), uiModifiers.size()); uiModifiers.put(uiModifiers.size(), m); } } } } }
src/nodes/ControlPanel.java
package nodes; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.RDFNode; import nodes.Modifier.ModifierType; import nodes.controllers.ModifiersListBox; import org.apache.jena.riot.RiotException; import controlP5.Button; import controlP5.CallbackEvent; import controlP5.CallbackListener; import controlP5.ColorPicker; import controlP5.ControlEvent; import controlP5.ControlP5; import controlP5.Group; import controlP5.RadioButton; import controlP5.Slider; import controlP5.Tab; import controlP5.Textfield; import controlP5.Toggle; import processing.core.PVector; import processing.core.PApplet; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; /** * * @author kdbanman */ public class ControlPanel extends PApplet implements Selection.SelectionListener { private static final long serialVersionUID = 7771053293767517965L; int w, h; ControlP5 cp5; Graph graph; // update flag raised if the controllers have not responded to a change in // selection. see selectionChanged() and draw(). AtomicBoolean selectionUpdated; // for copy/paste by keyboard Clipboard clipboard; // control element size parameters int tabHeight; int padding; int elementHeight; int labelledElementHeight; int buttonWidth; int buttonHeight; int modifiersBoxHeight; // Control elements that need to be accessed outside of setup() // copy/paste menu Button copyButton; Button pasteButton; Button clearButton; // tab and subtab containing autolayout so that it can be stopped if the // user leaves either of those tabs Tab transformTab; Group positionGroup; // subtab lists and open tab reference to be manipulated in draw() so that // they behave as tabs ArrayList<Group> importSubTabs; Group openImportSubTab; ArrayList<Group> transformSubTabs; Group openTransformSubTab; ArrayList<Group> saveSubTabs; Group openSaveSubTab; // text field for user-input URIs for description retrieval from the web Textfield importWebURI; // text field for sparql endpoint uri or ip addr for querying uri nbrhoods Textfield importSparqlEndpoint; // text field for sparql query formation Textfield sparqlQueryURI; // text field for file import location Textfield fileImportLocation; // text field for file import query entity uri Textfield fileImportQueryEntity; // text field for rdf-xml filename save location Textfield dataFilename; // text field for project filename (save/load location) Textfield projectFilename; // Modifier list controller ModifiersListBox modifiersBox; // Lists of modifiers and modifiersets private Collection<Modifier> modifiers = Collections.emptyList(); private Collection<ModifierSet> modifiersets = Collections.emptyList(); // Map of list indexes to each modifier private final ConcurrentHashMap<Integer, Modifier> uiModifiers = new ConcurrentHashMap<Integer, Modifier>(); // radio for radial layout sorting order (lexico or numerical) RadioButton sortOrder; // radio for position scaling direction (expansion or contraction) RadioButton scaleDirection; // toggle button for laying out the entire graph (force-directed algorithm) Toggle autoLayout; // controller group for colorizing selected nodes and edges ColorPicker colorPicker; // since colorpicker is a controlgroup, and its events can't be handled with // the listener architecture like *everything* else, this flag is necessary // so that changes in colorpicker as it reacts to selection changes do not // propagate to element color changes. boolean changeElementColor; Slider sizeSlider; Slider labelSizeSlider; public ControlPanel(int frameWidth, int frameHeight, Graph parentGraph) { w = frameWidth; h = frameHeight; // initialize graph graph = parentGraph; selectionUpdated = new AtomicBoolean(); // for copy/paste clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // element size parameters padding = 10; tabHeight = 30; elementHeight = 20; labelledElementHeight = 40; buttonWidth = 100; buttonHeight = 30; modifiersBoxHeight = 200; // sub tab lists to manipulate in draw() for tab behaviour importSubTabs = new ArrayList<>(); transformSubTabs = new ArrayList<>(); saveSubTabs = new ArrayList<>(); } @Override public void setup() { // subscribe to changes in selection. see overridden selectionChanged() graph.getSelection().addListener(this); size(w, h); cp5 = new ControlP5(this) .setMoveable(false); // define main controller tabs Tab importTab = cp5.addTab("Load Triples") .setWidth(w / 4) .setHeight(tabHeight) .setActive(true); // transformTab is defined externally so that autolayout can be stopped // if the tab is left by the user transformTab = cp5.addTab("Transform") .setWidth(w / 4) .setHeight(tabHeight); @SuppressWarnings("unused") //will probably have later use Tab optionTab = cp5.addTab("Options") .setWidth(w / 4) .setHeight(tabHeight); Tab saveTab = cp5.addTab("Save/Load") .setWidth(w / 4) .setHeight(tabHeight); cp5.getDefaultTab().remove(); // copy/paste 'menu' copyButton = cp5.addButton("Copy to Clipboard") .setWidth(buttonWidth) .setHeight(elementHeight) .setVisible(false) .addCallback(new CopyListener()); pasteButton = cp5.addButton("Paste from Clipboard") .setWidth(buttonWidth) .setHeight(elementHeight) .setVisible(false) .addCallback(new PasteListener()); clearButton = cp5.addButton("Clear Field") .setWidth(buttonWidth) .setHeight(elementHeight) .setVisible(false) .addCallback(new ClearListener()); //=========== // Import tab //=========== // triple import subtabs //////////////////////// int importTabsVert = 2 * tabHeight + padding; Group webGroup = new SubTab(cp5, "Web") .setBarHeight(tabHeight) .setPosition(0, importTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(true) .moveTo(importTab); Group sparqlGroup = new SubTab(cp5, "SPARQL") .setBarHeight(tabHeight) .setPosition(w / 4, importTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(importTab); Group fileGroup = new SubTab(cp5, "File") .setBarHeight(tabHeight) .setPosition(w / 2, importTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(importTab); // register triple import subtabs so that they may be manipulated in // draw() to behave as tabs importSubTabs.add(webGroup); importSubTabs.add(sparqlGroup); importSubTabs.add(fileGroup); openImportSubTab = webGroup; // Web import elements importWebURI = cp5.addTextfield("Entity or Document URI", padding, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .moveTo(webGroup) .setText("http://www.w3.org/1999/02/22-rdf-syntax-ns") .addCallback(new CopyPasteMenuListener()); cp5.addButton("Query Web") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding, labelledElementHeight + padding) .moveTo(webGroup) .addCallback(new QueryWebListener()); // SPARQL import elements importSparqlEndpoint = cp5.addTextfield("Endpoint IP:Port or URL", padding - w / 4, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .setText("http://dbpedia.org/sparql") .addCallback(new CopyPasteMenuListener()) .moveTo(sparqlGroup); sparqlQueryURI = cp5.addTextfield("Entity URI ", padding - w / 4, labelledElementHeight + padding, w - 2 * padding, elementHeight) .setAutoClear(false) .setText("http://dbpedia.org/resource/Albert_Einstein") .addCallback(new CopyPasteMenuListener()) .moveTo(sparqlGroup); cp5.addButton("Query Endpoint") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding - w / 4, 3 * labelledElementHeight + padding) .addCallback(new QuerySparqlListener()) .moveTo(sparqlGroup); // File import elements fileImportLocation = cp5.addTextfield("File Path (Relative or Absolute)", padding - w / 2, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .addCallback(new CopyPasteMenuListener()) .setText("Einstein.rdf") .moveTo(fileGroup); cp5.addButton("Select File") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding - w / 2, labelledElementHeight + 2 * padding) .addCallback(new SelectFileListener()) .moveTo(fileGroup); fileImportQueryEntity = cp5.addTextfield("Entity to Query (Optional)", padding - w / 2, labelledElementHeight + buttonHeight + 3 * padding, w - 2 * padding, elementHeight) .setAutoClear(false) .addCallback(new CopyPasteMenuListener()) .moveTo(fileGroup); cp5.addButton("Query File") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding - w / 2, 2 * labelledElementHeight + buttonHeight + 4 * padding) .addCallback(new FileQueryListener()) .moveTo(fileGroup); //============== // Transform tab //============== // modifier list controller modifiersBox = new ModifiersListBox(cp5, (Tab) cp5.controlWindow .getTabs().get(1), "ModifiersBox", padding, tabHeight + padding, w - 2 * padding, modifiersBoxHeight); //equivalent to cp5.AddListBox cp5.register(null, "", modifiersBox); modifiersBox.registerProperty("listBoxItems") .registerProperty("value") .setBarHeight(tabHeight) .setItemHeight(elementHeight) .setScrollbarWidth(elementHeight) .moveTo(transformTab) .hideBar(); //get a list of modifiers and modifiersets try { modifiers = graph.getModifiersList(); modifiersets = graph.getModifierSetsList(); } catch (Exception e) { e.printStackTrace(); System.err.println("ERROR: getting list of Modifiers/ModifierSets"); } populateModifierMenu(); // Transformation subtabs ///////////////////////// // vertical positiion of transformation subtabs int transformTabsVert = modifiersBoxHeight + 3 * tabHeight + padding; // positionGroup is defined externally so that autolayout can be stopped // if the tab is left by the user positionGroup = new SubTab(cp5, "Layout") .setBarHeight(tabHeight) .setPosition(0, transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(true) .moveTo(transformTab); Group colorSizeGroup = new SubTab(cp5, "Color and Size") .setBarHeight(tabHeight) .setPosition(w / 4, transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(transformTab); Group labelGroup = new SubTab(cp5, "Label") .setBarHeight(tabHeight) .setPosition(w / 2, transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(transformTab); Group hideGroup = new SubTab(cp5, "Delete") .setBarHeight(tabHeight) .setPosition(3 * (w / 4), transformTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(transformTab); // register transformation subtabs so that they may be manipulated in // draw() to behave as tabs transformSubTabs.add(positionGroup); transformSubTabs.add(colorSizeGroup); transformSubTabs.add(labelGroup); transformSubTabs.add(hideGroup); openTransformSubTab = positionGroup; // Layout controllers cp5.addButton("Scale Positions") .setPosition(padding, padding) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(positionGroup) .addCallback(new ScaleLayoutListener()); scaleDirection = cp5.addRadio("Scale Direction") .setPosition(2 * padding + buttonWidth, padding) .setItemHeight(buttonHeight / 2) .moveTo(positionGroup) .addItem("Expand from center", 0) .addItem("Contract from center", 1) .activate(0); cp5.addButton("Radial Sort") .setPosition(padding, 2 * padding + buttonHeight) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(positionGroup) .addCallback(new RadialLayoutListener()); sortOrder = cp5.addRadio("Sort Order") .setPosition(2 * padding + buttonWidth, 2 * padding + buttonHeight) .setItemHeight(buttonHeight / 2) .moveTo(positionGroup) .addItem("Numerical Order", 0) .addItem("Alphabetical Order", 1) .activate(0); autoLayout = cp5.addToggle("Autolayout Entire Graph") .setPosition(padding, 4 * padding + 3 * buttonHeight) .setHeight(elementHeight) .setWidth(buttonWidth) .moveTo(positionGroup); cp5.addButton("Center Camera") .setPosition(width - buttonWidth - padding, 4 * padding + 3 * buttonHeight) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(positionGroup) .addCallback(new CenterCameraListener()); // color and size controllers //NOTE: ColorPicker is a ControlGroup, not a Controller, so I can't // attach a callback to it. It's functionality is in the // controlEvent() function of the ControlPanel colorPicker = cp5.addColorPicker("Color") .setPosition(-(w / 4) + padding, padding) .moveTo(colorSizeGroup); changeElementColor = true; sizeSlider = cp5.addSlider("Size") .setPosition(-(w / 4) + padding, 2 * padding + 80) .setHeight(elementHeight) .setWidth(w - 80) .setRange(5, 100) .setValue(10) .moveTo(colorSizeGroup) .addCallback(new ElementSizeListener()); // label controllers cp5.addButton("Show Labels") .setPosition(padding - w / 2, padding) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(labelGroup) .addCallback(new ShowLabelListener()); cp5.addButton("Hide Labels") .setPosition(padding - w / 2, buttonHeight + 2 * padding) .setHeight(buttonHeight) .setWidth(buttonWidth) .moveTo(labelGroup) .addCallback(new HideLabelListener()); labelSizeSlider = cp5.addSlider("Label Size") .setPosition(padding - w / 2, padding * 3 + 2 * buttonHeight) .setWidth(w - 80) .setHeight(elementHeight) .setRange(5, 100) .setValue(10) .moveTo(labelGroup) .addCallback(new LabelSizeListener()); // visibility controllers cp5.addButton("Delete Selection") .setPosition(padding - 3 * (w / 4), padding) .setSize(buttonWidth, buttonHeight) .moveTo(hideGroup) .addCallback(new ElementRemovalListener()); // change color picker, size slider, and label size slider to reflect selection updateControllersToSelection(); //============ // Options tab //============ //============== // Save/Load tab //============== // save/load subtabs //////////////////////// int saveTabsVert = 2 * tabHeight + padding; Group dataGroup = new SubTab(cp5, "Save Data") .setBarHeight(tabHeight) .setPosition(0, saveTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(true) .moveTo(saveTab); Group projectGroup = new SubTab(cp5, "Save/Load Project") .setBarHeight(tabHeight) .setPosition(w / 4, saveTabsVert) .setWidth(w / 4) .hideArrow() .setOpen(false) .moveTo(saveTab); // register save subtabs so that they may be manipulated in // draw() to behave as tabs saveSubTabs.add(dataGroup); saveSubTabs.add(projectGroup); openSaveSubTab = dataGroup; // Data save elements dataFilename = cp5.addTextfield("RDF-XML Filename", padding, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .moveTo(dataGroup) .setText("myData.rdf") .addCallback(new CopyPasteMenuListener()); cp5.addButton("Save RDF-XML") .setSize(buttonWidth, buttonHeight) .setPosition(w - buttonWidth - padding, labelledElementHeight + padding) .moveTo(dataGroup) .addCallback(new SaveTriplesListener()); // Project Save elements projectFilename = cp5.addTextfield("Project Name", padding - w / 4, padding, w - 2 * padding, elementHeight) .setAutoClear(false) .moveTo(projectGroup) .setText("myProject.nod") .addCallback(new CopyPasteMenuListener()); cp5.addButton("Save Project") .setSize(buttonWidth, buttonHeight) .setPosition(3 * w / 4 - buttonWidth - padding, labelledElementHeight + padding) .moveTo(projectGroup) .addCallback(new SaveProjectListener()); cp5.addButton("Load Project") .setSize(buttonWidth, buttonHeight) .setPosition(3 * w / 4 - buttonWidth - padding, 3 * labelledElementHeight + padding) .moveTo(projectGroup) .addCallback(new LoadProjectListener()); } public String getHttpSparqlEndpoint() { return importSparqlEndpoint.getText(); } public boolean autoLayoutSelected() { return autoLayout.getState(); } // all controlP5 controllers are drawn after draw(), so herein lies any // arbiter-style controller logic, as well as miscellaneous actions that // must occur every frame. @Override public void draw() { // make subTabs perform as tabs instead of Groups for (Group subTab : transformSubTabs) { if (subTab.isOpen() && subTab != openTransformSubTab) { openTransformSubTab.setOpen(false); openTransformSubTab = subTab; } } for (Group subTab : importSubTabs) { if (subTab.isOpen() && subTab != openImportSubTab) { openImportSubTab.setOpen(false); openImportSubTab = subTab; } } for (Group subTab : saveSubTabs) { if (subTab.isOpen() && subTab != openSaveSubTab) { openSaveSubTab.setOpen(false); openSaveSubTab = subTab; } } // stop autoLayout if any other tab is selected if (autoLayout.getState() && (!transformTab.isOpen() || !positionGroup.isOpen())) { autoLayout.setState(false); } // update controllers to selection if selection has changed since // last draw() call if (selectionUpdated.getAndSet(false)) { // populate the dynamic, selection-dependent selection modifier menu populateModifierMenu(); // change color picker, size slider, and label size slider to reflect selection updateControllersToSelection(); } background(0); } /** * Callback for import file selection dialog. */ public void importFileSelected(File selection) { if (selection == null) { //user closed window or hit cancel } else { fileImportLocation.setText(selection.getAbsolutePath()); } } // every time selection is changed, this is called @Override public void selectionChanged() { // queue controller selection update if one is not already queued selectionUpdated.compareAndSet(false, true); } // called every time cp5 broadcasts an event. since ControlGroups cannot // have specific listeners, their actions must be dealt with here. public void controlEvent(ControlEvent event) { // adjust color of selected elements (if event is not from selection update) if (changeElementColor && event.isFrom(colorPicker)) { int newColor = colorPicker.getColorValue(); for (GraphElement<?> e : graph.getSelection()) { e.setColor(newColor); } } else if (event.isFrom(modifiersBox)) { try { uiModifiers.get((int) event.getValue()).modify(); } catch (Exception e) { e.printStackTrace(); } } } // called whenever the mouse is released within the control panel @Override public void mouseReleased() { //clear the copy paste menu if the left mouse button is clicked outside // of any part of the menu if (!(copyButton.isInside() || pasteButton.isInside() || clearButton.isInside()) && mouseButton == LEFT) { copyButton.setVisible(false); pasteButton.setVisible(false); clearButton.setVisible(false); } } public void updateControllersToSelection() { // do not change element colors with the resulting ControlEvent here changeElementColor = false; colorPicker.setColorValue(graph.getSelection().getColorOfSelection()); changeElementColor = true; sizeSlider.setValue(graph.getSelection().getSizeOfSelection()); labelSizeSlider.setValue(graph.getSelection().getLabelSizeOfSelection()); } // log event in infopanel private void logEvent(String s) { graph.pApp.logEvent(s); } /* * ControlP5 does not support nesting tabs within other tabs, so this is an * extension of controller Groups to behave as nested tabs. NOTE: the * tab-behaviour control logic is maintained for each group of tabs * by a list of each member of the group and a reference to whichever tab is * currently open in the group. these are defined as fields in ControlPanel * and are manipulated within draw(). */ private class SubTab extends Group { SubTab(ControlP5 theControlP5, String theName) { // call Group constructor super(theControlP5, theName); } @Override protected void postDraw(PApplet theApplet) { // draw the group with the color behaviour of a Tab instead of a Group if (isBarVisible) { theApplet.fill(isOpen ? color.getActive() : (isInside ? color.getForeground() : color.getBackground())); theApplet.rect(0, -1, _myWidth - 1, -_myHeight); _myLabel.draw(theApplet, 0, -_myHeight-1, this); if (isCollapse && isArrowVisible) { theApplet.fill(_myLabel.getColor()); theApplet.pushMatrix(); if (isOpen) { theApplet.triangle(_myWidth - 10, -_myHeight / 2 - 3, _myWidth - 4, -_myHeight / 2 - 3, _myWidth - 7, -_myHeight / 2); } else { theApplet.triangle(_myWidth - 10, -_myHeight / 2, _myWidth - 4, -_myHeight / 2, _myWidth - 7, -_myHeight / 2 - 3); } theApplet.popMatrix(); } } } } /***************************** * Import controller listeners ****************************/ /* * attach to a Textfield for copy/paste dropdown menu on right click. * each textfield needs its own unique instance (one controller per listener * is a controlP5 thing (and maybe even a general thing). technically this * risks concurrent modification of the copy and paste buttons, but the odds * of near-simultaneous right-clicks on textfields is low. */ private class CopyPasteMenuListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_PRESSED && mouseButton == RIGHT) { // textfields occur in multiple tabs, so the menu must be moved // to the corret tab Tab activeTab = event.getController().getTab(); // move each button sequentially below the cursor copyButton.setPosition(mouseX, mouseY) .setVisible(true) .moveTo(activeTab) .bringToFront(); pasteButton.setPosition(mouseX, mouseY + elementHeight) .setVisible(true) .moveTo(activeTab) .bringToFront(); clearButton.setPosition(mouseX, mouseY + 2 * elementHeight) .setVisible(true) .moveTo(activeTab) .bringToFront(); } } } /* * attach to button for copying from active textfield */ private class CopyListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get active text field for (Textfield c : cp5.getAll(Textfield.class)) { if (c.isActive()) { // get text field contents and copy to clipboard String fieldContents = c.getText(); StringSelection data = new StringSelection(fieldContents); // data is passed as both parameters because of an // unimplemented feature in AWT clipboard.setContents(data, data); } } } } } /* * attach to button for pasting to active textfield */ private class PasteListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get active text field for (Textfield c : cp5.getAll(Textfield.class)) { if (c.isActive()) { // separate current textfield contents about cursor position int idx = c.getIndex(); String before = c.getText().substring(0, idx); String after = ""; if (c.getIndex() != c.getText().length()) { after = c.getText().substring(idx, c.getText().length()); } // get (valid) clipboard contents and insert at cursor position Transferable clipData = clipboard.getContents(this); String s = ""; try { s = (String) (clipData.getTransferData(DataFlavor.stringFlavor)); } catch (UnsupportedFlavorException | IOException ee) { System.out.println("Cannot paste clipboard contents."); } c.setText(before + s + after); } } } } } /* * attach to button for clearing active text field */ private class ClearListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get active text field for (Textfield c : cp5.getAll(Textfield.class)) { if (c.isActive()) { c.clear(); } } } } } /* * attach to web query button in import tab to enable retrieval of rdf * descriptions as published at resources' uris. */ private class QueryWebListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get uri from text field String uri = importWebURI.getText(); Model toAdd; try { toAdd = IO.getDescription(uri); } catch (RiotException e) { logEvent("Valid RDF not hosted at uri \n " + uri); return; } // add the retrived model to the graph (toAdd is empty if // an error was encountered). // log results to user. graph.addTriplesLogged(toAdd); logEvent("From uri:\n " + uri + "\n "); } } } /* * attach to sparql query button for sparql query functionality */ private class QuerySparqlListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get endpoint uri String endpoint = importSparqlEndpoint.getText(); // get uri from text field and form query String uri = sparqlQueryURI.getText(); // retrieve description as a jena model Model toAdd; try { toAdd = IO.getDescriptionSparql(endpoint, uri); } catch (Exception e) { logEvent("Valid RDF not returned from endpoint:\n" + endpoint); return; } // add the retriveed model to the graph (toAdd is empty if // an error was encountered) // log results. graph.addTriplesLogged(toAdd); logEvent("From endpoint:\n" + endpoint + "\n\n" + "about uri: \n" + uri + "\n "); } } } private class SelectFileListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { ControlPanel.this.selectFolder("Select RDF File:", "importFileSelected"); } } } private class FileQueryListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get uris from text fields String docUri = fileImportLocation.getText(); String entityUri = fileImportQueryEntity.getText(); Model toAdd; try { toAdd = IO.getDescription(docUri, entityUri); } catch (RiotException e) { logEvent("Error encountered reading RDF from\n " + docUri); return; } //NOTE: the logged items will be in reverse order as they appear below. // UI BEHAVIOUR: // if the user did not specify an entity to describe, load all data from file // if the user did specify such an entity, and that entity is within the file, load the desrcibing data // if the user did specify such an entity, and that entity is not within the file, load no data // provide feedback as to whethere or not the file contains // the query entity if (!entityUri.equals("")) { RDFNode entityAsResource = toAdd.createResource(entityUri); if (toAdd.containsResource(entityAsResource)) { // add the retrived model to the graph (toAdd is empty if // an IO error was encountered). // log results to user. graph.addTriplesLogged(toAdd); logEvent("Describing entity:\n " + entityUri + "\n "); } else { logEvent("Warning: entity:\n " + entityUri + "\n not found!\n(All eoeo"); } } else { // add the retrived model to the graph (toAdd is empty if // an IO error was encountered). // log results to user. graph.addTriplesLogged(toAdd); } logEvent("From file:\n " + docUri + "\n "); } } } /************************************* * Transformation controller listeners ************************************/ /* * attach to layout scale button to enable expansion/contraction of the positions * of each node in the selection about their average center. */ private class ScaleLayoutListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // calculate center of current selection of nodes PVector center = new PVector(); for (Node n : graph.getSelection().getNodes()) { center.add(n.getPosition()); } center.x = center.x / graph.getSelection().nodeCount(); center.y = center.y / graph.getSelection().nodeCount(); center.z = center.z / graph.getSelection().nodeCount(); // set scale based on user selection. // index 0 == expand, 1 == contract float scale; if (scaleDirection.getState(0)) scale = -0.2f; else scale = 0.2f; // scale each node position outward or inward from center for (Node n : graph.getSelection().getNodes()) { n.getPosition().lerp(center, scale); } } } } /* * attach to button that centers PApplet camera on center of graph at a * heuristically calculated distance to contain most of the graph */ private class CenterCameraListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { Iterator<GraphElement<?>> it; if (graph.getSelection().empty()) { it = graph.iterator(); } else { it = graph.getSelection().iterator(); } if (it.hasNext()) { GraphElement<?> first = it.next(); // calculate center of graph PVector center = first.getPosition().get(); float minX = center.x; float maxX = center.x; float minY = center.y; float maxY = center.y; float minZ = center.z; float maxZ = center.z; float minCamDist = 15 * first.getSize(); float nodeCount = 1f; while (it.hasNext()) { GraphElement<?> e = it.next(); if (e instanceof Edge) continue; Node n = (Node) e; PVector nPos = n.getPosition(); center.add(n.getPosition()); minX = Nodes.min(minX, nPos.x); maxX = Nodes.max(maxX, nPos.x); minY = Nodes.min(minY, nPos.y); maxY = Nodes.max(maxY, nPos.y); minZ = Nodes.min(minZ, nPos.z); maxZ = Nodes.max(maxZ, nPos.z); nodeCount += 1f; } center.x = center.x / (float) nodeCount; center.y = center.y / (float) nodeCount; center.z = center.z / (float) nodeCount; float avgDist = (maxX - minX + maxY - minY + maxZ - minZ) / 3; // set camera graph.pApp.cam.lookAt(center.x, center.y, center.z); graph.pApp.cam.setDistance(Nodes.max(minCamDist, 1.3f * avgDist)); } } } } /* * attach to radial sort button. selected nodes are laid out in a circle * whose axis is perpendicular to the screen and whose radius is chosen to * accomodate all the nodes with a bit of room to spare. the nodes will * be ordered along the circumference lexicographically or numerically, * depending on the state of a separate radio button called sortOrder. */ private class RadialLayoutListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // get array of names of selected nodes (Selection stores // things as HashSets, which are not sortable) String[] names = new String[graph.getSelection().nodeCount()]; int i = 0; for (Node n : graph.getSelection().getNodes()) { names[i] = n.getName(); i++; } // sort the array of names according to the user choice // index 0 == numerical, 1 == lexicographical if (sortOrder.getState(0)) { quickSort(names, 0, names.length - 1, true); } else { // lexicographical sort implicit quickSort(names, 0, names.length - 1, false); } // calculate radius of circle from number and size of nodes // along with the midpoint of the nodes PVector center = new PVector(); float maxSize = 0; for (Node n : graph.getSelection().getNodes()) { center.add(n.getPosition()); maxSize = Nodes.max(maxSize, n.getSize()); } // radius is circumference / 2pi, but this has been adjusted for appearance float radius = (float) ((float) graph.getSelection().nodeCount() * 2 * maxSize) / (Nodes.PI); // center is average position center.x = center.x / graph.getSelection().nodeCount(); center.y = center.y / graph.getSelection().nodeCount(); center.z = center.z / graph.getSelection().nodeCount(); // get horizontal and vertical unit vectors w.r.t. screen PVector horiz = graph.proj.getScreenHoriz(); //upper left corner graph.proj.calculatePickPoints(0, 0); PVector vert = graph.proj.getScreenVert(); // angular separation of nodes is 2pi / number of nodes float theta = 2 * Nodes.PI / (float) graph.getSelection().nodeCount(); float currAngle = 0; // lay out the selected nodes in the new order in a circle // whose axis is orthogonal to the screen for (String name : names) { Node n = graph.getNode(name); PVector hComp = horiz.get(); hComp.mult(Nodes.cos(currAngle) * radius); PVector vComp = vert.get(); vComp.mult(Nodes.sin(currAngle) * radius); hComp.add(vComp); n.setPosition(hComp); currAngle += theta; } } } // standard quicksort implementation with a boolean parameter to // indicate numerical or lexicographical ordering of the strings private void quickSort(String[] arr, int p, int r, boolean numerical) { if (p < r) { int pivot = partition(arr, p, r, numerical); quickSort(arr, p, pivot - 1, numerical); quickSort(arr, pivot + 1, r, numerical); } } // quicksort partition function with choice of sort order private int partition(String[] arr, int p, int r, boolean numerical) { String pivot = arr[r]; int swap = p - 1; for (int j = p ; j < r ; j++) { boolean greaterThanPivot; if (numerical) greaterThanPivot = numLess(arr[j], pivot); else greaterThanPivot = lexLess(arr[j], pivot); if (greaterThanPivot) { swap++; String tmp = arr[swap]; arr[swap] = arr[j]; arr[j] = tmp; } } String tmp = arr[swap + 1]; arr[swap + 1] = arr[r]; arr[r] = tmp; return swap + 1; } // numerical string comparison private boolean numLess(String left, String right) { if (left.length() > right.length()) { return false; } else if (left.length() < right.length()) { return true; } return lexLess(left, right); } // lexicographical string comparison private boolean lexLess(String left, String right) { return left.compareToIgnoreCase(right) < 0; } } /* * attach to element size slider to enable node/edge size manipulation */ private class ElementSizeListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED || event.getAction() == ControlP5.ACTION_RELEASEDOUTSIDE) { // get the size from the slider control int newSize = 10; try { newSize = (int) ((Slider) event.getController()).getValue(); } catch (Exception e) { System.out.println("ERROR: ElementSizeListener not hooked up to a Slider."); } // apply the new size to each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setSize(newSize); } } } } /* * attach to hide label button to enable label-showing control */ private class HideLabelListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // hide label for each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setDisplayLabel(false); } } } } /* * attach to show label button to enable label-hiding control */ private class ShowLabelListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // show each label for each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setDisplayLabel(true); } } } } /* * attach to label size slider to enable label size control */ private class LabelSizeListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED || event.getAction() == ControlP5.ACTION_RELEASEDOUTSIDE) { int newSize = 10; // get the new size from the slider control try { newSize = (int) ((Slider) event.getController()).getValue(); } catch (Exception e) { System.out.println("ERROR: LabelSizeListener not hooked up to a Slider."); } // apply the new label size to each element in the selection for (GraphElement<?> e : graph.getSelection()) { e.setLabelSize(newSize); } } } } /* * attach to element removal button to enable removal of any subset of * the graph's nodes or edges */ private class ElementRemovalListener implements CallbackListener { @Override public void controlEvent(CallbackEvent event) { if (event.getAction() == ControlP5.ACTION_RELEASED) { // hold graph drawing while controllers are removed graph.pApp.waitForNewFrame(this); // for both removal loops below, deep copies of the selected // nodes and edges are created. the removal calls still work // because the Graph.remove*(GraphElement) methods are wrappers // for Graph.remove*(String) methods (only names matter) HashSet<Node> nodesCopy = new HashSet<>(graph.getSelection().getNodes()); // remove all nodes in the selection (this will remove all // connected edges for (Node n : nodesCopy) { // nodes may have been removed between iterations, so check // membership before removal. if (graph.getSelection().contains(n)) graph.removeNode(n); } HashSet<Edge> edgesCopy = new HashSet<>(graph.getSelection().getEdges()); // remove all remaining edges in the selection for (Edge e : edgesCopy) { // edges may have been removed between iterations, so check // membership before removal. if (graph.getSelection().contains(e)) graph.removeEdge(e); } graph.pApp.restartRendering(this); } } } /* * saves rendered triples to an rdf-xml file as named by the respective text box */ private class SaveTriplesListener implements CallbackListener { @Override public void controlEvent(CallbackEvent ce) { Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(dataFilename.getText()), "utf-8")); graph.getRenderedTriples().write(writer); logEvent("RDF-XML file " + dataFilename.getText() + "\nsaved to application directory."); } catch (IOException ex) { logEvent("Failed to save file " + dataFilename.getText()); } finally { try {writer.close();} catch (Exception ex) {} } } } /* * saves the (relevant) current state of the Nodes application to be loaded * at a later date. */ private class SaveProjectListener implements CallbackListener { /* * TODO */ @Override public void controlEvent(CallbackEvent ce) { throw new UnsupportedOperationException("Not supported yet."); } } /* * loads previously saved application state. */ private class LoadProjectListener implements CallbackListener { /* * TODO */ @Override public void controlEvent(CallbackEvent ce) { throw new UnsupportedOperationException("Not supported yet."); } } /* * Refreshes the visual modifiers menu list */ private void populateModifierMenu() { if (modifiersBox == null || (modifiers.isEmpty() && modifiersets.isEmpty())) return; uiModifiers.clear(); modifiersBox.clear(); for (Modifier m : modifiers) { if ((m.getType() == ModifierType.ALL || m.getType() == ModifierType.PANEL) && m.isCompatible()) { modifiersBox.addItem(m.getTitle(), uiModifiers.size()); uiModifiers.put(uiModifiers.size(), m); } } for (ModifierSet s : modifiersets) { if (s.getType() != ModifierType.ALL || s.getType() != ModifierType.PANEL) continue; if ((s.getType() == ModifierType.ALL || s.getType() == ModifierType.PANEL) && s.isCompatible()) { s.constructModifiers(); for (Modifier m : s.getModifiers()) { modifiersBox.addItem(m.getTitle(), uiModifiers.size()); uiModifiers.put(uiModifiers.size(), m); } } } } }
add file selector and sorted dropdown
src/nodes/ControlPanel.java
add file selector and sorted dropdown
<ide><path>rc/nodes/ControlPanel.java <ide> package nodes; <ide> <ide> import com.hp.hpl.jena.rdf.model.Model; <add>import com.hp.hpl.jena.rdf.model.NodeIterator; <ide> import com.hp.hpl.jena.rdf.model.RDFNode; <add>import com.hp.hpl.jena.rdf.model.ResIterator; <add>import com.hp.hpl.jena.rdf.model.Resource; <ide> <ide> import nodes.Modifier.ModifierType; <ide> import nodes.controllers.ModifiersListBox; <ide> import controlP5.ColorPicker; <ide> import controlP5.ControlEvent; <ide> import controlP5.ControlP5; <add>import controlP5.DropdownList; <ide> import controlP5.Group; <add>import controlP5.ListBox; <ide> import controlP5.RadioButton; <ide> import controlP5.Slider; <ide> import controlP5.Tab; <ide> import java.util.Collections; <ide> import java.util.HashSet; <ide> import java.util.Iterator; <add>import java.util.TreeSet; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> // text field for file import location <ide> Textfield fileImportLocation; <ide> <del> // text field for file import query entity uri <del> Textfield fileImportQueryEntity; <add> // menu for file import query entity uri <add> DropdownList fileImportEntityMenu; <ide> <ide> // text field for rdf-xml filename save location <ide> Textfield dataFilename; <ide> elementHeight) <ide> .setAutoClear(false) <ide> .addCallback(new CopyPasteMenuListener()) <del> .setText("Einstein.rdf") <ide> .moveTo(fileGroup); <ide> cp5.addButton("Select File") <ide> .setSize(buttonWidth, buttonHeight) <ide> labelledElementHeight + 2 * padding) <ide> .addCallback(new SelectFileListener()) <ide> .moveTo(fileGroup); <del> fileImportQueryEntity = cp5.addTextfield("Entity to Query (Optional)", <del> padding - w / 2, <del> labelledElementHeight + buttonHeight + 3 * padding, <del> w - 2 * padding, <del> elementHeight) <del> .setAutoClear(false) <del> .addCallback(new CopyPasteMenuListener()) <del> .moveTo(fileGroup); <add> // fileImportEntityMenu is technically the next in order of appearance, <add> // but is initialized last so it renders on top of the rest of fileGroup <ide> cp5.addButton("Query File") <ide> .setSize(buttonWidth, buttonHeight) <ide> .setPosition(w - buttonWidth - padding - w / 2, <ide> 2 * labelledElementHeight + buttonHeight + 4 * padding) <ide> .addCallback(new FileQueryListener()) <add> .moveTo(fileGroup); <add> fileImportEntityMenu = cp5.addDropdownList("Entity of Interest (Optional)") <add> .setPosition(padding - w / 2, <add> labelledElementHeight + buttonHeight + 5 * padding) <add> .setSize(w - 3 * padding - buttonWidth, h - padding - (90 + labelledElementHeight + buttonHeight + 4 * padding)) <add> .setItemHeight(elementHeight) <add> .setBarHeight(elementHeight) <ide> .moveTo(fileGroup); <ide> <ide> //============== <ide> //user closed window or hit cancel <ide> } else { <ide> fileImportLocation.setText(selection.getAbsolutePath()); <add> Model entityListTmp = null; <add> try { <add> entityListTmp = IO.getDescription(fileImportLocation.getText()); <add> } catch (RiotException e) { <add> logEvent(fileImportLocation.getText()); <add> logEvent("Error: Valid RDF not contained within:\n"); <add> } finally { <add> populateFileEntityMenu(entityListTmp); <add> } <add> } <add> } <add> <add> /** <add> * Populate the entity selection menu for file import with all subjects of <add> * triples within the model. Objects of triples are ignored. <add> */ <add> public void populateFileEntityMenu(Model fileModel) { <add> fileImportEntityMenu.clear(); <add> <add> if (fileModel != null) { <add> TreeSet<String> resources = new TreeSet<>(); <add> ResIterator objects = fileModel.listSubjects(); <add> while (objects.hasNext()) { <add> Resource node = objects.next(); <add> resources.add(node.getURI()); <add> } <add> <add> int i = 0; <add> for (String resource : resources) { <add> fileImportEntityMenu.addItem(resource, i); <add> fileImportEntityMenu.getItem(i).setText(fileModel.shortForm(resource)); <add> i++; <add> } <ide> } <ide> } <ide> <ide> if (event.getAction() == ControlP5.ACTION_RELEASED) { <ide> // get uris from text fields <ide> String docUri = fileImportLocation.getText(); <del> String entityUri = fileImportQueryEntity.getText(); <add> // if the user did not specify an entity to describe, first entity of list will be queried because of controlp5 behaviour <add> String entityUri = ""; <add> if (fileImportEntityMenu.getListBoxItems().length > 0) { <add> entityUri = fileImportEntityMenu.getItem((int)fileImportEntityMenu.getValue()).getName(); <add> } <add> <ide> Model toAdd; <ide> try { <ide> toAdd = IO.getDescription(docUri, entityUri); <ide> <ide> //NOTE: the logged items will be in reverse order as they appear below. <ide> <del> // UI BEHAVIOUR: <del> // if the user did not specify an entity to describe, load all data from file <del> // if the user did specify such an entity, and that entity is within the file, load the desrcibing data <del> // if the user did specify such an entity, and that entity is not within the file, load no data <del> <del> // provide feedback as to whethere or not the file contains <del> // the query entity <del> if (!entityUri.equals("")) { <del> RDFNode entityAsResource = toAdd.createResource(entityUri); <del> if (toAdd.containsResource(entityAsResource)) { <del> // add the retrived model to the graph (toAdd is empty if <del> // an IO error was encountered). <del> // log results to user. <del> graph.addTriplesLogged(toAdd); <del> logEvent("Describing entity:\n " + entityUri + "\n "); <del> } else { <del> logEvent("Warning: entity:\n " + entityUri + "\n not found!\n(All eoeo"); <del> } <del> } else { <add> RDFNode entityAsResource = toAdd.createResource(entityUri); <add> if (toAdd.containsResource(entityAsResource)) { <ide> // add the retrived model to the graph (toAdd is empty if <ide> // an IO error was encountered). <ide> // log results to user. <ide> graph.addTriplesLogged(toAdd); <del> } <add> logEvent("Describing entity:\n " + entityUri + "\n "); <add> } else { <add> logEvent("Warning: entity:\n " + entityUri + "\n not found!\n"); <add> } <add> // add the retrived model to the graph (toAdd is empty if <add> // an IO error was encountered). <add> // log results to user. <add> graph.addTriplesLogged(toAdd); <ide> <ide> logEvent("From file:\n " + docUri + "\n "); <ide> } <ide> private class SaveTriplesListener implements CallbackListener { <ide> <ide> @Override <del> public void controlEvent(CallbackEvent ce) { <del> Writer writer = null; <del> try { <del> writer = new BufferedWriter(new OutputStreamWriter( <del> new FileOutputStream(dataFilename.getText()), "utf-8")); <del> graph.getRenderedTriples().write(writer); <del> logEvent("RDF-XML file " + dataFilename.getText() + "\nsaved to application directory."); <del> } catch (IOException ex) { <del> logEvent("Failed to save file " + dataFilename.getText()); <del> } finally { <del> try {writer.close();} catch (Exception ex) {} <add> public void controlEvent(CallbackEvent event) { <add> if (event.getAction() == ControlP5.ACTION_RELEASED) { <add> Writer writer = null; <add> try { <add> writer = new BufferedWriter(new OutputStreamWriter( <add> new FileOutputStream(dataFilename.getText()), "utf-8")); <add> graph.getRenderedTriples().write(writer); <add> logEvent("RDF-XML file " + dataFilename.getText() + "\nsaved to application directory."); <add> } catch (IOException ex) { <add> logEvent("Failed to save file " + dataFilename.getText()); <add> } finally { <add> try {writer.close();} catch (Exception ex) {} <add> } <ide> } <ide> } <ide> }
Java
bsd-3-clause
39865466bd75c71ee119efee721b2e2f9f6195e2
0
arnoldlankamp/parser
package gtd; import gtd.generator.ParserStructure; import gtd.result.AbstractContainerNode; import gtd.result.AbstractNode; import gtd.result.ListContainerNode; import gtd.result.SortContainerNode; import gtd.result.struct.Link; import gtd.stack.AbstractExpandableStackNode; import gtd.stack.AbstractStackNode; import gtd.stack.SortStackNode; import gtd.stack.edge.EdgesSet; import gtd.stack.filter.IAfterFilter; import gtd.stack.filter.IBeforeFilter; import gtd.util.ArrayList; import gtd.util.DoubleStack; import gtd.util.IntegerList; import gtd.util.IntegerObjectList; import gtd.util.Stack; @SuppressWarnings({"unchecked"}) public final class Parser implements IParser{ private final static int DEFAULT_TODOLIST_CAPACITY = 16; private final char[] input; private DoubleStack<AbstractStackNode, AbstractNode>[] todoLists; private int queueIndex; private final Stack<AbstractStackNode> stacksToExpand; private DoubleStack<AbstractStackNode, AbstractNode> stacksWithTerminalsToReduce; private final DoubleStack<AbstractStackNode, AbstractNode> stacksWithNonTerminalsToReduce; private EdgesSet[] cachedEdgesForExpect; private AbstractStackNode[] sharedNextNodes; private int location; private final AbstractStackNode[][] expectMatrix; private final ArrayList<String> containerIndexMap; private final int numberOfContainers; private final int numberOfUniqueNodes; public Parser(char[] input, ParserStructure structure){ super(); this.input = input; expectMatrix = structure.expectMatrix; containerIndexMap = structure.containerIndexMap; numberOfContainers = containerIndexMap.size(); numberOfUniqueNodes = structure.numberOfUniqueNodes; stacksToExpand = new Stack<AbstractStackNode>(); stacksWithTerminalsToReduce = new DoubleStack<AbstractStackNode, AbstractNode>(); stacksWithNonTerminalsToReduce = new DoubleStack<AbstractStackNode, AbstractNode>(); cachedEdgesForExpect = new EdgesSet[numberOfContainers]; sharedNextNodes = new AbstractStackNode[numberOfUniqueNodes]; location = 0; } private boolean canEnter(AbstractStackNode node){ IBeforeFilter[] beforeFilters = node.getBeforeFilters(); if(beforeFilters != null){ for(int i = beforeFilters.length - 1; i >= 0; --i){ if(beforeFilters[i].isFiltered(input, location)) return false; } } return true; } private boolean canComplete(AbstractStackNode node){ IAfterFilter[] afterFilters = node.getAfterFilters(); if(afterFilters != null){ for(int i = afterFilters.length - 1; i >= 0; --i){ if(afterFilters[i].isFiltered(input, node.getStartLocation(), location)) return false; } } return true; } private AbstractStackNode updateNextNode(AbstractStackNode next, AbstractStackNode node, AbstractNode result){ AbstractStackNode alternative = sharedNextNodes[next.getId()]; if(alternative != null){ if(node.getStartLocation() == location){ if(alternative.isMatchable()){ if(alternative.isEmptyLeafNode()){ // Encountered possible stack 'overtake'. if(node.getStartLocation() != location){ propagateEdgesAndPrefixes(node, result, alternative, alternative.getResult()); }else{ propagateEdgesAndPrefixesForNullable(node, result, alternative, alternative.getResult(), node.getEdges().size()); } return alternative; } }else{ if(alternative.getStartLocation() == location){ EdgesSet alternativeEdgesSet = alternative.getIncomingEdges(); if(alternativeEdgesSet != null && alternativeEdgesSet.getLastVisistedLevel() == location){ // Encountered possible stack 'overtake'. if(node.getStartLocation() != location){ propagateEdgesAndPrefixes(node, result, alternative, alternativeEdgesSet.getLastResult()); }else{ propagateEdgesAndPrefixesForNullable(node, result, alternative, alternativeEdgesSet.getLastResult(), node.getEdges().size()); } return alternative; } } } } alternative.updateNode(node, result); return alternative; } if(next.isMatchable()){ if((location + next.getLength()) > input.length) return null; AbstractNode nextResult = next.match(input, location); if(nextResult == null){ sharedNextNodes[next.getId()] = null; return null; } next = next.getCleanCopyWithResult(location, nextResult); }else{ next = next.getCleanCopy(location); } if(!node.isMatchable() || node.getStartLocation() == location){ next.updateNode(node, result); }else{ next.updateNodeAfterNonEmptyMatchable(node, result); } sharedNextNodes[next.getId()] = next; stacksToExpand.push(next); return next; } private boolean updateAlternativeNextNode(AbstractStackNode next, AbstractStackNode node, AbstractNode result, IntegerObjectList<EdgesSet> edgesMap, ArrayList<Link>[] prefixesMap){ AbstractStackNode alternative = sharedNextNodes[next.getId()]; if(alternative != null){ if(node.getStartLocation() == location){ if(alternative.isMatchable()){ if(alternative.isEmptyLeafNode()){ // Encountered possible stack 'overtake'. propagateAlternativeEdgesAndPrefixes(node, result, alternative, alternative.getResult(), node.getEdges().size(), edgesMap, prefixesMap); return true; } }else{ if(alternative.getStartLocation() == location){ EdgesSet alternativeEdgesSet = alternative.getIncomingEdges(); if(alternativeEdgesSet != null && alternativeEdgesSet.getLastVisistedLevel() == location){ // Encountered possible stack 'overtake'. propagateAlternativeEdgesAndPrefixes(node, result, alternative, alternativeEdgesSet.getLastResult(), node.getEdges().size(), edgesMap, prefixesMap); return true; } } } } alternative.updatePrefixSharedNode(edgesMap, prefixesMap); return true; } if(next.isMatchable()){ if((location + next.getLength()) > input.length) return false; AbstractNode nextResult = next.match(input, location); if(nextResult == null){ sharedNextNodes[next.getId()] = null; return false; } next = next.getCleanCopyWithResult(location, nextResult); }else{ next = next.getCleanCopy(location); } next.updatePrefixSharedNode(edgesMap, prefixesMap); sharedNextNodes[next.getId()] = next; stacksToExpand.push(next); return true; } private void propagateReductions(AbstractStackNode node, AbstractNode nodeResultStore, AbstractStackNode next, AbstractNode nextResultStore, int potentialNewEdges){ IntegerList propagatedReductions = next.getPropagatedReductions(); IntegerObjectList<EdgesSet> edgesMap = node.getEdges(); ArrayList<Link>[] prefixes = node.getPrefixesMap(); int fromIndex = edgesMap.size() - potentialNewEdges; for(int i = edgesMap.size() - 1; i >= fromIndex; --i){ int startLocation = edgesMap.getKey(i); // We know we haven't been here before. propagatedReductions.add(startLocation); ArrayList<Link> edgePrefixes = new ArrayList<Link>(); Link prefix = (prefixes != null) ? new Link(prefixes[i], nodeResultStore) : new Link(null, nodeResultStore); edgePrefixes.add(prefix); Link resultLink = new Link(edgePrefixes, nextResultStore); handleEdgeSet(edgesMap.getValue(i), resultLink, edgesMap.getKey(i)); } } private void propagatePrefixes(AbstractStackNode next, AbstractNode nextResult, int nrOfAddedEdges){ // Proceed with the tail of the production. AbstractStackNode nextNext = next.getNext(); AbstractStackNode nextNextAlternative = sharedNextNodes[nextNext.getId()]; if(nextNextAlternative != null){ if(nextNextAlternative.isMatchable()){ if(nextNextAlternative.isEmptyLeafNode()){ propagateEdgesAndPrefixesForNullable(next, nextResult, nextNextAlternative, nextNextAlternative.getResult(), nrOfAddedEdges); }else{ nextNextAlternative.updateNode(next, nextResult); } }else{ EdgesSet nextNextAlternativeEdgesSet = nextNextAlternative.getIncomingEdges(); if(nextNextAlternativeEdgesSet != null && nextNextAlternativeEdgesSet.getLastVisistedLevel() == location){ propagateEdgesAndPrefixesForNullable(next, nextResult, nextNextAlternative, nextNextAlternativeEdgesSet.getLastResult(), nrOfAddedEdges); }else{ nextNextAlternative.updateNode(next, nextResult); } } } // Handle alternative nexts (and prefix sharing). AbstractStackNode[] alternateNexts = next.getAlternateNexts(); if(alternateNexts != null){ if(nextNextAlternative == null){ // If the first continuation has not been initialized yet (it may be a matchable that didn't match), create a dummy version to construct the necessary edges and prefixes. if(!nextNext.isMatchable()) return; // Matchable, abort. nextNextAlternative = nextNext.getCleanCopy(location); nextNextAlternative.updateNode(next, nextResult); } IntegerObjectList<EdgesSet> nextNextEdgesMap = nextNextAlternative.getEdges(); ArrayList<Link>[] nextNextPrefixesMap = nextNextAlternative.getPrefixesMap(); for(int i = alternateNexts.length - 1; i >= 0; --i){ AbstractStackNode alternativeNext = alternateNexts[i]; AbstractStackNode nextNextAltAlternative = sharedNextNodes[alternativeNext.getId()]; if(nextNextAltAlternative != null){ if(nextNextAltAlternative.isMatchable()){ if(nextNextAltAlternative.isEmptyLeafNode()){ propagateAlternativeEdgesAndPrefixes(next, nextResult, nextNextAltAlternative, nextNextAltAlternative.getResult(), nrOfAddedEdges, nextNextEdgesMap, nextNextPrefixesMap); }else{ nextNextAltAlternative.updatePrefixSharedNode(nextNextEdgesMap, nextNextPrefixesMap); } }else{ EdgesSet nextAlternativeEdgesSet = nextNextAlternative.getIncomingEdges(); if(nextAlternativeEdgesSet != null && nextAlternativeEdgesSet.getLastVisistedLevel() == location){ propagateAlternativeEdgesAndPrefixes(next, nextResult, nextNextAltAlternative, nextAlternativeEdgesSet.getLastResult(), nrOfAddedEdges, nextNextEdgesMap, nextNextPrefixesMap); }else{ nextNextAltAlternative.updatePrefixSharedNode(nextNextEdgesMap, nextNextPrefixesMap); } } } } } } private void propagateEdgesAndPrefixes(AbstractStackNode node, AbstractNode nodeResult, AbstractStackNode next, AbstractNode nextResult){ int nrOfAddedEdges = next.updateOvertakenNode(node, nodeResult); if(nrOfAddedEdges == 0) return; if(next.isEndNode()){ propagateReductions(node, nodeResult, next, nextResult, nrOfAddedEdges); } if(next.hasNext()){ propagatePrefixes(next, nextResult, nrOfAddedEdges); } } private void propagateEdgesAndPrefixesForNullable(AbstractStackNode node, AbstractNode nodeResult, AbstractStackNode next, AbstractNode nextResult, int potentialNewEdges){ int nrOfAddedEdges = next.updateNullableOvertakenNode(node, nodeResult, potentialNewEdges); if(nrOfAddedEdges == 0) return; if(next.isEndNode()){ propagateReductions(node, nodeResult, next, nextResult, nrOfAddedEdges); } if(next.hasNext()){ propagatePrefixes(next, nextResult, nrOfAddedEdges); } } private void propagateAlternativeEdgesAndPrefixes(AbstractStackNode node, AbstractNode nodeResult, AbstractStackNode next, AbstractNode nextResult, int potentialNewEdges, IntegerObjectList<EdgesSet> edgesMap, ArrayList<Link>[] prefixesMap){ next.updatePrefixSharedNode(edgesMap, prefixesMap); if(potentialNewEdges == 0) return; if(next.isEndNode()){ propagateReductions(node, nodeResult, next, nextResult, potentialNewEdges); } if(next.hasNext()){ propagatePrefixes(next, nextResult, potentialNewEdges); } } private void updateEdges(AbstractStackNode node, AbstractNode result){ IntegerObjectList<EdgesSet> edgesMap = node.getEdges(); ArrayList<Link>[] prefixesMap = node.getPrefixesMap(); for(int i = edgesMap.size() - 1; i >= 0; --i){ Link resultLink = new Link((prefixesMap != null) ? prefixesMap[i] : null, result); handleEdgeSet(edgesMap.getValue(i), resultLink, edgesMap.getKey(i)); } } private void updateNullableEdges(AbstractStackNode node, AbstractNode result){ IntegerList propagatedReductions = node.getPropagatedReductions(); int initialSize = propagatedReductions.size(); IntegerObjectList<EdgesSet> edgesMap = node.getEdges(); ArrayList<Link>[] prefixesMap = node.getPrefixesMap(); for(int i = edgesMap.size() - 1; i >= 0; --i){ int startLocation = edgesMap.getKey(i); if(propagatedReductions.containsBefore(startLocation, initialSize)) continue; propagatedReductions.add(startLocation); Link resultLink = new Link((prefixesMap != null) ? prefixesMap[i] : null, result); handleEdgeSet(edgesMap.getValue(i), resultLink, startLocation); } } private void handleEdgeSet(EdgesSet edgeSet, Link resultLink, int startLocation){ AbstractContainerNode resultStore = null; if(edgeSet.getLastVisistedLevel() != location){ AbstractStackNode edge = edgeSet.get(0); resultStore = (!edge.isExpandable()) ? new SortContainerNode(edge.getName(), startLocation == location, edge.isSeparator()) : new ListContainerNode(edge.getName(), startLocation == location, edge.isSeparator()); stacksWithNonTerminalsToReduce.push(edge, resultStore); for(int j = edgeSet.size() - 1; j >= 1; --j){ edge = edgeSet.get(j); stacksWithNonTerminalsToReduce.push(edge, resultStore); } edgeSet.setLastResult(resultStore, location); }else{ resultStore = edgeSet.getLastResult(); } resultStore.addAlternative(resultLink); } private void moveToNext(AbstractStackNode node, AbstractNode result){ AbstractStackNode newNext = node.getNext(); AbstractStackNode next = updateNextNode(newNext, node, result); // Handle alternative nexts (and prefix sharing). AbstractStackNode[] alternateNexts = node.getAlternateNexts(); if(alternateNexts != null){ IntegerObjectList<EdgesSet> edgesMap = null; ArrayList<Link>[] prefixesMap = null; if(next != null){ edgesMap = next.getEdges(); prefixesMap = next.getPrefixesMap(); } for(int i = alternateNexts.length - 1; i >= 0; --i){ AbstractStackNode newAlternativeNext = alternateNexts[i]; if(edgesMap != null){ updateAlternativeNextNode(newAlternativeNext, node, result, edgesMap, prefixesMap); }else{ AbstractStackNode alternativeNext = updateNextNode(newAlternativeNext, node, result); if(alternativeNext != null){ edgesMap = alternativeNext.getEdges(); prefixesMap = alternativeNext.getPrefixesMap(); } } } } } private void move(AbstractStackNode node, AbstractNode result){ if(!canComplete(node)) return; if(node.isEndNode()){ if(node.getStartLocation() != location || node.getId() == AbstractExpandableStackNode.DEFAULT_LIST_EPSILON_ID){ updateEdges(node, result); }else{ updateNullableEdges(node, result); } } if(node.hasNext()){ moveToNext(node, result); } } private void reduce(){ // Reduce terminals. while(!stacksWithTerminalsToReduce.isEmpty()){ move(stacksWithTerminalsToReduce.peekFirst(), stacksWithTerminalsToReduce.popSecond()); } // Reduce non-terminals. while(!stacksWithNonTerminalsToReduce.isEmpty()){ move(stacksWithNonTerminalsToReduce.peekFirst(), stacksWithNonTerminalsToReduce.popSecond()); } } private boolean findFirstStacksToReduce(){ for(int i = 0; i < todoLists.length; ++i){ DoubleStack<AbstractStackNode, AbstractNode> terminalsTodo = todoLists[i]; if(!(terminalsTodo == null || terminalsTodo.isEmpty())){ stacksWithTerminalsToReduce = terminalsTodo; location += i; queueIndex = i; return true; } } return false; } private boolean findStacksToReduce(){ int queueDepth = todoLists.length; for(int i = 1; i < queueDepth; ++i){ queueIndex = (queueIndex + 1) % queueDepth; DoubleStack<AbstractStackNode, AbstractNode> terminalsTodo = todoLists[queueIndex]; if(!(terminalsTodo == null || terminalsTodo.isEmpty())){ stacksWithTerminalsToReduce = terminalsTodo; location += i; return true; } } return false; } private void addTodo(AbstractStackNode node, int length, AbstractNode result){ int queueDepth = todoLists.length; if(length >= queueDepth){ DoubleStack<AbstractStackNode, AbstractNode>[] oldTodoLists = todoLists; todoLists = new DoubleStack[length + 1]; System.arraycopy(oldTodoLists, queueIndex, todoLists, 0, queueDepth - queueIndex); System.arraycopy(oldTodoLists, 0, todoLists, queueDepth - queueIndex, queueIndex); queueDepth = length + 1; queueIndex = 0; } int insertLocation = (queueIndex + length) % queueDepth; DoubleStack<AbstractStackNode, AbstractNode> terminalsTodo = todoLists[insertLocation]; if(terminalsTodo == null){ terminalsTodo = new DoubleStack<AbstractStackNode, AbstractNode>(); todoLists[insertLocation] = terminalsTodo; } terminalsTodo.push(node, result); } private void handleExpects(EdgesSet cachedEdges, AbstractStackNode[] expects){ for(int i = expects.length - 1; i >= 0; --i){ AbstractStackNode first = expects[i]; if(first.isMatchable()){ int length = first.getLength(); int endLocation = location + length; if(endLocation > input.length) continue; AbstractNode result = first.match(input, location); if(result == null) continue; // Discard if it didn't match. if(!canEnter(first)) return; first = first.getCleanCopyWithResult(location, result); addTodo(first, length, result); }else{ first = first.getCleanCopy(location); stacksToExpand.push(first); } first.initEdges(); first.addEdges(cachedEdges, location); } } private void expandStack(AbstractStackNode node){ if(!canEnter(node)) return; if(node.isMatchable()){ addTodo(node, node.getLength(), node.getResult()); }else if(!node.isExpandable()){ EdgesSet cachedEdges = cachedEdgesForExpect[node.getContainerIndex()]; if(cachedEdges == null){ cachedEdges = new EdgesSet(1); cachedEdgesForExpect[node.getContainerIndex()] = cachedEdges; AbstractStackNode[] expects = expectMatrix[node.getContainerIndex()]; if(expects == null) return; handleExpects(cachedEdges, expects); }else{ if(cachedEdges.getLastVisistedLevel() == location){ // Is nullable, add the known results. stacksWithNonTerminalsToReduce.push(node, cachedEdges.getLastResult()); } } cachedEdges.add(node); node.setIncomingEdges(cachedEdges); }else{ // 'List' EdgesSet cachedEdges = cachedEdgesForExpect[node.getContainerIndex()]; if(cachedEdges == null){ cachedEdges = new EdgesSet(); cachedEdgesForExpect[node.getContainerIndex()] = cachedEdges; AbstractStackNode[] listChildren = node.getChildren(); for(int i = listChildren.length - 1; i >= 0; --i){ AbstractStackNode child = listChildren[i]; int childId = child.getId(); AbstractStackNode sharedChild = sharedNextNodes[childId]; if(sharedChild != null){ sharedChild.setEdgesSetWithPrefix(cachedEdges, null, location); }else{ if(child.isMatchable()){ int length = child.getLength(); int endLocation = location + length; if(endLocation > input.length) continue; AbstractNode result = child.match(input, location); if(result == null) continue; // Discard if it didn't match. if(!canEnter(node)) continue; child = child.getCleanCopyWithResult(location, result); addTodo(child, length, result); }else{ child = child.getCleanCopy(location); stacksToExpand.push(child); } child.initEdges(); child.setEdgesSetWithPrefix(cachedEdges, null, location); sharedNextNodes[childId] = child; } } if(node.canBeEmpty()){ // Star list or optional. AbstractStackNode empty = node.getEmptyChild().getCleanCopy(location); empty.initEdges(); empty.addEdges(cachedEdges, location); stacksToExpand.push(empty); } } if(cachedEdges.getLastVisistedLevel() == location){ // Is nullable, add the known results. stacksWithNonTerminalsToReduce.push(node, cachedEdges.getLastResult()); } cachedEdges.add(node); node.setIncomingEdges(cachedEdges); } } private void expand(){ while(!stacksToExpand.isEmpty()){ expandStack(stacksToExpand.pop()); } } protected boolean isAtEndOfInput(){ return (location == input.length); } protected boolean isInLookAhead(char[][] ranges, char[] characters){ if(location == input.length) return false; char next = input[location]; for(int i = ranges.length - 1; i >= 0; --i){ char[] range = ranges[i]; if(next >= range[0] && next <= range[1]) return true; } for(int i = characters.length - 1; i >= 0; --i){ if(next == characters[i]) return true; } return false; } public AbstractNode parse(String start){ // Initialize. todoLists = new DoubleStack[DEFAULT_TODOLIST_CAPACITY]; AbstractStackNode rootNode = new SortStackNode(AbstractStackNode.START_SYMBOL_ID, containerIndexMap.find(start), true, start, null, null); rootNode = rootNode.getCleanCopy(0); rootNode.initEdges(); stacksToExpand.push(rootNode); expand(); if(findFirstStacksToReduce()){ boolean shiftedLevel = (location != 0); do{ if(shiftedLevel){ // Nullable fix for the first level. sharedNextNodes = new AbstractStackNode[numberOfUniqueNodes]; cachedEdgesForExpect = new EdgesSet[numberOfContainers]; } do{ reduce(); expand(); }while(!stacksWithNonTerminalsToReduce.isEmpty() || !stacksWithTerminalsToReduce.isEmpty()); shiftedLevel = true; }while(findStacksToReduce()); } if(location == input.length){ EdgesSet rootNodeEdgesSet = rootNode.getIncomingEdges(); if(rootNodeEdgesSet != null && rootNodeEdgesSet.getLastVisistedLevel() == input.length){ return rootNodeEdgesSet.getLastResult(); // Success. } } // Parse error. throw new RuntimeException("Parse Error before: "+(location == Integer.MAX_VALUE ? 0 : location)); } }
src/main/java/gtd/Parser.java
package gtd; import gtd.generator.ParserStructure; import gtd.result.AbstractContainerNode; import gtd.result.AbstractNode; import gtd.result.ListContainerNode; import gtd.result.SortContainerNode; import gtd.result.struct.Link; import gtd.stack.AbstractExpandableStackNode; import gtd.stack.AbstractStackNode; import gtd.stack.SortStackNode; import gtd.stack.edge.EdgesSet; import gtd.stack.filter.IAfterFilter; import gtd.stack.filter.IBeforeFilter; import gtd.util.ArrayList; import gtd.util.DoubleStack; import gtd.util.IntegerList; import gtd.util.IntegerObjectList; import gtd.util.Stack; @SuppressWarnings({"unchecked"}) public final class Parser implements IParser{ private final static int DEFAULT_TODOLIST_CAPACITY = 16; private final char[] input; private DoubleStack<AbstractStackNode, AbstractNode>[] todoLists; private int queueIndex; private final Stack<AbstractStackNode> stacksToExpand; private DoubleStack<AbstractStackNode, AbstractNode> stacksWithTerminalsToReduce; private final DoubleStack<AbstractStackNode, AbstractNode> stacksWithNonTerminalsToReduce; private EdgesSet[] cachedEdgesForExpect; private AbstractStackNode[] sharedNextNodes; private int location; private final AbstractStackNode[][] expectMatrix; private final ArrayList<String> containerIndexMap; private final int numberOfContainers; private final int numberOfUniqueNodes; public Parser(char[] input, ParserStructure structure){ super(); this.input = input; expectMatrix = structure.expectMatrix; containerIndexMap = structure.containerIndexMap; numberOfContainers = containerIndexMap.size(); numberOfUniqueNodes = structure.numberOfUniqueNodes; stacksToExpand = new Stack<AbstractStackNode>(); stacksWithTerminalsToReduce = new DoubleStack<AbstractStackNode, AbstractNode>(); stacksWithNonTerminalsToReduce = new DoubleStack<AbstractStackNode, AbstractNode>(); cachedEdgesForExpect = new EdgesSet[numberOfContainers]; sharedNextNodes = new AbstractStackNode[numberOfUniqueNodes]; location = 0; } private boolean canEnter(AbstractStackNode node){ IBeforeFilter[] beforeFilters = node.getBeforeFilters(); if(beforeFilters != null){ for(int i = beforeFilters.length - 1; i >= 0; --i){ if(beforeFilters[i].isFiltered(input, location)) return false; } } return true; } private boolean canComplete(AbstractStackNode node){ IAfterFilter[] afterFilters = node.getAfterFilters(); if(afterFilters != null){ for(int i = afterFilters.length - 1; i >= 0; --i){ if(afterFilters[i].isFiltered(input, node.getStartLocation(), location)) return false; } } return true; } private AbstractStackNode updateNextNode(AbstractStackNode next, AbstractStackNode node, AbstractNode result){ AbstractStackNode alternative = sharedNextNodes[next.getId()]; if(alternative != null){ if(node.getStartLocation() == location){ if(alternative.isMatchable()){ if(alternative.isEmptyLeafNode()){ // Encountered possible stack 'overtake'. if(node.getStartLocation() != location){ propagateEdgesAndPrefixes(node, result, alternative, alternative.getResult()); }else{ propagateEdgesAndPrefixesForNullable(node, result, alternative, alternative.getResult(), node.getEdges().size()); } return alternative; } }else{ if(alternative.getStartLocation() == location){ EdgesSet alternativeEdgesSet = alternative.getIncomingEdges(); if(alternativeEdgesSet != null && alternativeEdgesSet.getLastVisistedLevel() == location){ // Encountered possible stack 'overtake'. if(node.getStartLocation() != location){ propagateEdgesAndPrefixes(node, result, alternative, alternativeEdgesSet.getLastResult()); }else{ propagateEdgesAndPrefixesForNullable(node, result, alternative, alternativeEdgesSet.getLastResult(), node.getEdges().size()); } return alternative; } } } } alternative.updateNode(node, result); return alternative; } if(next.isMatchable()){ if((location + next.getLength()) > input.length) return null; AbstractNode nextResult = next.match(input, location); if(nextResult == null){ sharedNextNodes[next.getId()] = null; return null; } next = next.getCleanCopyWithResult(location, nextResult); }else{ next = next.getCleanCopy(location); } if(!node.isMatchable() || node.getStartLocation() == location){ next.updateNode(node, result); }else{ next.updateNodeAfterNonEmptyMatchable(node, result); } sharedNextNodes[next.getId()] = next; stacksToExpand.push(next); return next; } private boolean updateAlternativeNextNode(AbstractStackNode next, AbstractStackNode node, AbstractNode result, IntegerObjectList<EdgesSet> edgesMap, ArrayList<Link>[] prefixesMap){ AbstractStackNode alternative = sharedNextNodes[next.getId()]; if(alternative != null){ if(node.getStartLocation() == location){ if(alternative.isMatchable()){ if(alternative.isEmptyLeafNode()){ // Encountered possible stack 'overtake'. propagateAlternativeEdgesAndPrefixes(node, result, alternative, alternative.getResult(), node.getEdges().size(), edgesMap, prefixesMap); return true; } }else{ if(alternative.getStartLocation() == location){ EdgesSet alternativeEdgesSet = alternative.getIncomingEdges(); if(alternativeEdgesSet != null && alternativeEdgesSet.getLastVisistedLevel() == location){ // Encountered possible stack 'overtake'. propagateAlternativeEdgesAndPrefixes(node, result, alternative, alternativeEdgesSet.getLastResult(), node.getEdges().size(), edgesMap, prefixesMap); return true; } } } } alternative.updatePrefixSharedNode(edgesMap, prefixesMap); return true; } if(next.isMatchable()){ if((location + next.getLength()) > input.length) return false; AbstractNode nextResult = next.match(input, location); if(nextResult == null){ sharedNextNodes[next.getId()] = null; return false; } next = next.getCleanCopyWithResult(location, nextResult); }else{ next = next.getCleanCopy(location); } next.updatePrefixSharedNode(edgesMap, prefixesMap); sharedNextNodes[next.getId()] = next; stacksToExpand.push(next); return true; } private void propagateReductions(AbstractStackNode node, AbstractNode nodeResultStore, AbstractStackNode next, AbstractNode nextResultStore, int potentialNewEdges){ IntegerList propagatedReductions = next.getPropagatedReductions(); IntegerObjectList<EdgesSet> edgesMap = node.getEdges(); ArrayList<Link>[] prefixes = node.getPrefixesMap(); int fromIndex = edgesMap.size() - potentialNewEdges; for(int i = edgesMap.size() - 1; i >= fromIndex; --i){ int startLocation = edgesMap.getKey(i); // We know we haven't been here before. propagatedReductions.add(startLocation); ArrayList<Link> edgePrefixes = new ArrayList<Link>(); Link prefix = (prefixes != null) ? new Link(prefixes[i], nodeResultStore) : new Link(null, nodeResultStore); edgePrefixes.add(prefix); Link resultLink = new Link(edgePrefixes, nextResultStore); handleEdgeSet(edgesMap.getValue(i), resultLink, edgesMap.getKey(i)); } } private void propagatePrefixes(AbstractStackNode next, AbstractNode nextResult, int nrOfAddedEdges){ // Proceed with the tail of the production. AbstractStackNode nextNext = next.getNext(); AbstractStackNode nextNextAlternative = sharedNextNodes[nextNext.getId()]; if(nextNextAlternative != null){ if(nextNextAlternative.isMatchable()){ if(nextNextAlternative.isEmptyLeafNode()){ propagateEdgesAndPrefixesForNullable(next, nextResult, nextNextAlternative, nextNextAlternative.getResult(), nrOfAddedEdges); }else{ nextNextAlternative.updateNode(next, nextResult); } }else{ EdgesSet nextNextAlternativeEdgesSet = nextNextAlternative.getIncomingEdges(); if(nextNextAlternativeEdgesSet != null && nextNextAlternativeEdgesSet.getLastVisistedLevel() == location){ propagateEdgesAndPrefixesForNullable(next, nextResult, nextNextAlternative, nextNextAlternativeEdgesSet.getLastResult(), nrOfAddedEdges); }else{ nextNextAlternative.updateNode(next, nextResult); } } } // Handle alternative nexts (and prefix sharing). AbstractStackNode[] alternateNexts = next.getAlternateNexts(); if(alternateNexts != null){ if(nextNextAlternative == null){ // If the first continuation has not been initialized yet (it may be a matchable that didn't match), create a dummy version to construct the necessary edges and prefixes. if(!nextNext.isMatchable()) return; // Matchable, abort. nextNextAlternative = nextNext.getCleanCopy(location); nextNextAlternative.updateNode(next, nextResult); } IntegerObjectList<EdgesSet> nextNextEdgesMap = nextNextAlternative.getEdges(); ArrayList<Link>[] nextNextPrefixesMap = nextNextAlternative.getPrefixesMap(); for(int i = alternateNexts.length - 1; i >= 0; --i){ AbstractStackNode alternativeNext = alternateNexts[i]; AbstractStackNode nextNextAltAlternative = sharedNextNodes[alternativeNext.getId()]; if(nextNextAltAlternative != null){ if(nextNextAltAlternative.isMatchable()){ if(nextNextAltAlternative.isEmptyLeafNode()){ propagateAlternativeEdgesAndPrefixes(next, nextResult, nextNextAltAlternative, nextNextAltAlternative.getResult(), nrOfAddedEdges, nextNextEdgesMap, nextNextPrefixesMap); }else{ nextNextAltAlternative.updatePrefixSharedNode(nextNextEdgesMap, nextNextPrefixesMap); } }else{ EdgesSet nextAlternativeEdgesSet = nextNextAlternative.getIncomingEdges(); if(nextAlternativeEdgesSet != null && nextAlternativeEdgesSet.getLastVisistedLevel() == location){ propagateAlternativeEdgesAndPrefixes(next, nextResult, nextNextAltAlternative, nextAlternativeEdgesSet.getLastResult(), nrOfAddedEdges, nextNextEdgesMap, nextNextPrefixesMap); }else{ nextNextAltAlternative.updatePrefixSharedNode(nextNextEdgesMap, nextNextPrefixesMap); } } } } } } private void propagateEdgesAndPrefixes(AbstractStackNode node, AbstractNode nodeResult, AbstractStackNode next, AbstractNode nextResult){ int nrOfAddedEdges = next.updateOvertakenNode(node, nodeResult); if(nrOfAddedEdges == 0) return; if(next.isEndNode()){ propagateReductions(node, nodeResult, next, nextResult, nrOfAddedEdges); } if(next.hasNext()){ propagatePrefixes(next, nextResult, nrOfAddedEdges); } } private void propagateEdgesAndPrefixesForNullable(AbstractStackNode node, AbstractNode nodeResult, AbstractStackNode next, AbstractNode nextResult, int potentialNewEdges){ int nrOfAddedEdges = next.updateNullableOvertakenNode(node, nodeResult, potentialNewEdges); if(nrOfAddedEdges == 0) return; if(next.isEndNode()){ propagateReductions(node, nodeResult, next, nextResult, nrOfAddedEdges); } if(next.hasNext()){ propagatePrefixes(next, nextResult, nrOfAddedEdges); } } private void propagateAlternativeEdgesAndPrefixes(AbstractStackNode node, AbstractNode nodeResult, AbstractStackNode next, AbstractNode nextResult, int potentialNewEdges, IntegerObjectList<EdgesSet> edgesMap, ArrayList<Link>[] prefixesMap){ next.updatePrefixSharedNode(edgesMap, prefixesMap); if(potentialNewEdges == 0) return; if(next.isEndNode()){ propagateReductions(node, nodeResult, next, nextResult, potentialNewEdges); } if(next.hasNext()){ propagatePrefixes(next, nextResult, potentialNewEdges); } } private void updateEdges(AbstractStackNode node, AbstractNode result){ IntegerObjectList<EdgesSet> edgesMap = node.getEdges(); ArrayList<Link>[] prefixesMap = node.getPrefixesMap(); for(int i = edgesMap.size() - 1; i >= 0; --i){ Link resultLink = new Link((prefixesMap != null) ? prefixesMap[i] : null, result); handleEdgeSet(edgesMap.getValue(i), resultLink, edgesMap.getKey(i)); } } private void updateNullableEdges(AbstractStackNode node, AbstractNode result){ IntegerList propagatedReductions = node.getPropagatedReductions(); int initialSize = propagatedReductions.size(); IntegerObjectList<EdgesSet> edgesMap = node.getEdges(); ArrayList<Link>[] prefixesMap = node.getPrefixesMap(); for(int i = edgesMap.size() - 1; i >= 0; --i){ int startLocation = edgesMap.getKey(i); if(propagatedReductions.containsBefore(startLocation, initialSize)) continue; propagatedReductions.add(startLocation); Link resultLink = new Link((prefixesMap != null) ? prefixesMap[i] : null, result); handleEdgeSet(edgesMap.getValue(i), resultLink, startLocation); } } private void handleEdgeSet(EdgesSet edgeSet, Link resultLink, int startLocation){ AbstractContainerNode resultStore = null; if(edgeSet.getLastVisistedLevel() != location){ AbstractStackNode edge = edgeSet.get(0); resultStore = (!edge.isExpandable()) ? new SortContainerNode(edge.getName(), startLocation == location, edge.isSeparator()) : new ListContainerNode(edge.getName(), startLocation == location, edge.isSeparator()); stacksWithNonTerminalsToReduce.push(edge, resultStore); for(int j = edgeSet.size() - 1; j >= 1; --j){ edge = edgeSet.get(j); stacksWithNonTerminalsToReduce.push(edge, resultStore); } edgeSet.setLastResult(resultStore, location); }else{ resultStore = edgeSet.getLastResult(); } resultStore.addAlternative(resultLink); } private void moveToNext(AbstractStackNode node, AbstractNode result){ AbstractStackNode newNext = node.getNext(); AbstractStackNode next = updateNextNode(newNext, node, result); // Handle alternative nexts (and prefix sharing). AbstractStackNode[] alternateNexts = node.getAlternateNexts(); if(alternateNexts != null){ IntegerObjectList<EdgesSet> edgesMap = null; ArrayList<Link>[] prefixesMap = null; if(next != null){ edgesMap = next.getEdges(); prefixesMap = next.getPrefixesMap(); } for(int i = alternateNexts.length - 1; i >= 0; --i){ AbstractStackNode newAlternativeNext = alternateNexts[i]; if(edgesMap != null){ updateAlternativeNextNode(newAlternativeNext, node, result, edgesMap, prefixesMap); }else{ AbstractStackNode alternativeNext = updateNextNode(newAlternativeNext, node, result); if(alternativeNext != null){ edgesMap = alternativeNext.getEdges(); prefixesMap = alternativeNext.getPrefixesMap(); } } } } } private void move(AbstractStackNode node, AbstractNode result){ if(!canComplete(node)) return; if(node.isEndNode()){ if(node.getStartLocation() != location || node.getId() == AbstractExpandableStackNode.DEFAULT_LIST_EPSILON_ID){ updateEdges(node, result); }else{ updateNullableEdges(node, result); } } if(node.hasNext()){ moveToNext(node, result); } } private void reduce(){ // Reduce terminals. while(!stacksWithTerminalsToReduce.isEmpty()){ move(stacksWithTerminalsToReduce.peekFirst(), stacksWithTerminalsToReduce.popSecond()); } // Reduce non-terminals. while(!stacksWithNonTerminalsToReduce.isEmpty()){ move(stacksWithNonTerminalsToReduce.peekFirst(), stacksWithNonTerminalsToReduce.popSecond()); } } private boolean findFirstStacksToReduce(){ for(int i = 0; i < todoLists.length; ++i){ DoubleStack<AbstractStackNode, AbstractNode> terminalsTodo = todoLists[i]; if(!(terminalsTodo == null || terminalsTodo.isEmpty())){ stacksWithTerminalsToReduce = terminalsTodo; location += i; queueIndex = i; return true; } } return false; } private boolean findStacksToReduce(){ int queueDepth = todoLists.length; for(int i = 1; i < queueDepth; ++i){ queueIndex = (queueIndex + 1) % queueDepth; DoubleStack<AbstractStackNode, AbstractNode> terminalsTodo = todoLists[queueIndex]; if(!(terminalsTodo == null || terminalsTodo.isEmpty())){ stacksWithTerminalsToReduce = terminalsTodo; location += i; return true; } } return false; } private void addTodo(AbstractStackNode node, int length, AbstractNode result){ if(result == null) throw new RuntimeException(); int queueDepth = todoLists.length; if(length >= queueDepth){ DoubleStack<AbstractStackNode, AbstractNode>[] oldTodoLists = todoLists; todoLists = new DoubleStack[length + 1]; System.arraycopy(oldTodoLists, queueIndex, todoLists, 0, queueDepth - queueIndex); System.arraycopy(oldTodoLists, 0, todoLists, queueDepth - queueIndex, queueIndex); queueDepth = length + 1; queueIndex = 0; } int insertLocation = (queueIndex + length) % queueDepth; DoubleStack<AbstractStackNode, AbstractNode> terminalsTodo = todoLists[insertLocation]; if(terminalsTodo == null){ terminalsTodo = new DoubleStack<AbstractStackNode, AbstractNode>(); todoLists[insertLocation] = terminalsTodo; } terminalsTodo.push(node, result); } private void handleExpects(EdgesSet cachedEdges, AbstractStackNode[] expects){ for(int i = expects.length - 1; i >= 0; --i){ AbstractStackNode first = expects[i]; if(first.isMatchable()){ int length = first.getLength(); int endLocation = location + length; if(endLocation > input.length) continue; AbstractNode result = first.match(input, location); if(result == null) continue; // Discard if it didn't match. if(!canEnter(first)) return; first = first.getCleanCopyWithResult(location, result); addTodo(first, length, result); }else{ first = first.getCleanCopy(location); stacksToExpand.push(first); } first.initEdges(); first.addEdges(cachedEdges, location); } } private void expandStack(AbstractStackNode node){ if(!canEnter(node)) return; if(node.isMatchable()){ addTodo(node, node.getLength(), node.getResult()); }else if(!node.isExpandable()){ EdgesSet cachedEdges = cachedEdgesForExpect[node.getContainerIndex()]; if(cachedEdges == null){ cachedEdges = new EdgesSet(1); cachedEdgesForExpect[node.getContainerIndex()] = cachedEdges; AbstractStackNode[] expects = expectMatrix[node.getContainerIndex()]; if(expects == null) return; handleExpects(cachedEdges, expects); }else{ if(cachedEdges.getLastVisistedLevel() == location){ // Is nullable, add the known results. stacksWithNonTerminalsToReduce.push(node, cachedEdges.getLastResult()); } } cachedEdges.add(node); node.setIncomingEdges(cachedEdges); }else{ // 'List' EdgesSet cachedEdges = cachedEdgesForExpect[node.getContainerIndex()]; if(cachedEdges == null){ cachedEdges = new EdgesSet(); cachedEdgesForExpect[node.getContainerIndex()] = cachedEdges; AbstractStackNode[] listChildren = node.getChildren(); for(int i = listChildren.length - 1; i >= 0; --i){ AbstractStackNode child = listChildren[i]; int childId = child.getId(); AbstractStackNode sharedChild = sharedNextNodes[childId]; if(sharedChild != null){ sharedChild.setEdgesSetWithPrefix(cachedEdges, null, location); }else{ if(child.isMatchable()){ int length = child.getLength(); int endLocation = location + length; if(endLocation > input.length) continue; AbstractNode result = child.match(input, location); if(result == null) continue; // Discard if it didn't match. if(!canEnter(node)) continue; child = child.getCleanCopyWithResult(location, result); addTodo(child, length, result); }else{ child = child.getCleanCopy(location); stacksToExpand.push(child); } child.initEdges(); child.setEdgesSetWithPrefix(cachedEdges, null, location); sharedNextNodes[childId] = child; } } if(node.canBeEmpty()){ // Star list or optional. AbstractStackNode empty = node.getEmptyChild().getCleanCopy(location); empty.initEdges(); empty.addEdges(cachedEdges, location); stacksToExpand.push(empty); } } if(cachedEdges.getLastVisistedLevel() == location){ // Is nullable, add the known results. stacksWithNonTerminalsToReduce.push(node, cachedEdges.getLastResult()); } cachedEdges.add(node); node.setIncomingEdges(cachedEdges); } } private void expand(){ while(!stacksToExpand.isEmpty()){ expandStack(stacksToExpand.pop()); } } protected boolean isAtEndOfInput(){ return (location == input.length); } protected boolean isInLookAhead(char[][] ranges, char[] characters){ if(location == input.length) return false; char next = input[location]; for(int i = ranges.length - 1; i >= 0; --i){ char[] range = ranges[i]; if(next >= range[0] && next <= range[1]) return true; } for(int i = characters.length - 1; i >= 0; --i){ if(next == characters[i]) return true; } return false; } public AbstractNode parse(String start){ // Initialize. todoLists = new DoubleStack[DEFAULT_TODOLIST_CAPACITY]; AbstractStackNode rootNode = new SortStackNode(AbstractStackNode.START_SYMBOL_ID, containerIndexMap.find(start), true, start, null, null); rootNode = rootNode.getCleanCopy(0); rootNode.initEdges(); stacksToExpand.push(rootNode); expand(); if(findFirstStacksToReduce()){ boolean shiftedLevel = (location != 0); do{ if(shiftedLevel){ // Nullable fix for the first level. sharedNextNodes = new AbstractStackNode[numberOfUniqueNodes]; cachedEdgesForExpect = new EdgesSet[numberOfContainers]; } do{ reduce(); expand(); }while(!stacksWithNonTerminalsToReduce.isEmpty() || !stacksWithTerminalsToReduce.isEmpty()); shiftedLevel = true; }while(findStacksToReduce()); } if(location == input.length){ EdgesSet rootNodeEdgesSet = rootNode.getIncomingEdges(); if(rootNodeEdgesSet != null && rootNodeEdgesSet.getLastVisistedLevel() == input.length){ return rootNodeEdgesSet.getLastResult(); // Success. } } // Parse error. throw new RuntimeException("Parse Error before: "+(location == Integer.MAX_VALUE ? 0 : location)); } }
-Removed unnecessary RuntimeException.
src/main/java/gtd/Parser.java
-Removed unnecessary RuntimeException.
<ide><path>rc/main/java/gtd/Parser.java <ide> } <ide> <ide> private void addTodo(AbstractStackNode node, int length, AbstractNode result){ <del> if(result == null) throw new RuntimeException(); <ide> int queueDepth = todoLists.length; <ide> if(length >= queueDepth){ <ide> DoubleStack<AbstractStackNode, AbstractNode>[] oldTodoLists = todoLists;
Java
apache-2.0
e97d5db3f0f30d577aded22520ecc4d4e008b313
0
eFaps/eFaps-Kernel-Install,eFaps/eFaps-Kernel-Install
/* * Copyright 2003 - 2013 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev:1563 $ * Last Changed: $Date:2007-10-28 15:07:41 +0100 (So, 28 Okt 2007) $ * Last Changed By: $Author:tmo $ */ package org.efaps.esjp.admin.access; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.efaps.admin.EFapsSystemConfiguration; import org.efaps.admin.KernelSettings; import org.efaps.admin.access.AccessCache; import org.efaps.admin.access.AccessKey; import org.efaps.admin.access.AccessSet; import org.efaps.admin.access.AccessType; import org.efaps.admin.access.AccessTypeEnums; import org.efaps.admin.datamodel.Classification; import org.efaps.admin.datamodel.Type; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.admin.user.Role; import org.efaps.db.Context; import org.efaps.db.Instance; import org.efaps.db.transaction.ConnectionResource; import org.efaps.util.EFapsException; import org.infinispan.Cache; /** * This Class is used to check if a user can Access this Type.<br> * The method execute is called with the Instance and the Accesstype as * parameters. For the instance object it is checked if the current context user * has the access defined in the list of access types. * * @author The eFaps Team * @version $Id:SimpleAccessCheckOnType.java 1563 2007-10-28 14:07:41Z tmo $ */ @EFapsUUID("628a19f6-463f-415d-865b-ba72e303a507") @EFapsApplication("eFaps-Kernel") public abstract class SimpleAccessCheckOnType_Base extends AbstractAccessCheck { /** * {@inheritDoc} */ @Override protected boolean checkAccess(final Parameter _parameter, final Instance _instance, final AccessType _accessType) throws EFapsException { boolean ret = false; final Cache<AccessKey, Boolean> cache = AccessCache.getKeyCache(); final AccessKey accessKey = AccessKey.get(_instance, _accessType); final Boolean access = cache.get(accessKey); if (access == null) { ret = checkAccessOnDB(_parameter, _instance, _accessType); AbstractAccessCheck_Base.LOG.trace("access result :{} from DB for: {}", ret, _instance); cache.put(accessKey, ret); } else { ret = access; AbstractAccessCheck_Base.LOG.trace("access result :{} from Cache for: {}", ret, _instance); } return ret; } /** * Check for the instance object if the current context user has the access * defined in the list of access types against the eFaps DataBase. * * @param _parameter Parameter as passed by the eFaps API * @param _instance instance to check for access for * @param _accessType accesstyep to check the access for * @return true if access is granted, else false * @throws EFapsException on error */ protected boolean checkAccessOnDB(final Parameter _parameter, final Instance _instance, final AccessType _accessType) throws EFapsException { final Context context = Context.getThreadContext(); final StringBuilder cmd = new StringBuilder(); cmd.append("select count(*) from T_ACCESSSET2USER "); Type type; if (_parameter.get(ParameterValues.CLASS) instanceof Classification) { type = (Classification) _parameter.get(ParameterValues.CLASS); } else { type = _instance.getType(); } final Set<Long> users = new HashSet<Long>(); final Set<Role> localRoles = new HashSet<Role>(); boolean noCompCheck = false; if (type.isCheckStatus() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { cmd.append(" join T_ACCESSSET2STATUS on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2STATUS.ACCESSSET") .append(" join ").append(type.getMainTable().getSqlTable()) .append(" on ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getStatusAttribute().getSqlColNames().get(0)) .append(" = T_ACCESSSET2STATUS.ACCESSSTATUS"); } else if (type.isCompanyDependent() && type.getMainTable().getSqlColType() != null && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { // in case that it is companydependent but not status cmd.append(" join T_ACCESSSET2DMTYPE on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2DMTYPE.ACCESSSET ") .append(" join ").append(type.getMainTable().getSqlTable()) .append(" on ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getMainTable().getSqlColType()) .append(" = T_ACCESSSET2DMTYPE.DMTYPE "); } else { noCompCheck = true; } cmd.append(" where T_ACCESSSET2USER.ACCESSSET in (0"); for (final AccessSet accessSet : type.getAccessSets()) { if (accessSet.getAccessTypes().contains(_accessType)) { cmd.append(",").append(accessSet.getId()); users.addAll(accessSet.getUserIds()); } } cmd.append(") ").append("and T_ACCESSSET2USER.USERABSTRACT in (").append(context.getPersonId()); for (final Long roleId : context.getPerson().getRoles()) { if (users.contains(roleId)) { cmd.append(",").append(roleId); final Role role = Role.get(roleId); if (role.isLocal()) { localRoles.add(role); } } } cmd.append(")"); if (type.isCheckStatus() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".ID = ").append(_instance.getId()); } if (type.isCompanyDependent() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { if (noCompCheck) { AbstractAccessCheck_Base.LOG.error("Cannot check for Company on type '{}'", type); } else { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getCompanyAttribute().getSqlColNames().get(0)).append(" in ("); boolean first = true; for (final Long compId : context.getPerson().getCompanies()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(compId); } cmd.append(")"); } } if (type.isGroupDependent() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType()) && !localRoles.isEmpty() && EFapsSystemConfiguration.get().getAttributeValueAsBoolean( KernelSettings.ACTIVATE_GROUPS)) { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getGroupAttribute().getSqlColNames().get(0)).append(" in (") .append(" select GROUPID from T_USERASSOC where ROLEID in ("); boolean first = true; for (final Role role : localRoles) { if (first) { first = false; } else { cmd.append(","); } cmd.append(role.getId()); } cmd.append(") and GROUPID in ("); first = true; for (final Long group : context.getPerson().getGroups()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(group); } if (first) { cmd.append("0"); AbstractAccessCheck_Base.LOG.error("Missing Group for '{}' on groupdependend Access on type '{}'", context.getPerson().getName(), type); } cmd.append("))"); } AbstractAccessCheck_Base.LOG.debug("cheking access with: {}", cmd); return executeStatement(_parameter, context, cmd); } /** * {@inheritDoc} */ @Override protected Map<Instance, Boolean> checkAccess(final Parameter _parameter, final List<?> _instances, final AccessType _accessType) throws EFapsException { final Map<Instance, Boolean> ret = new HashMap<Instance, Boolean>(); final Cache<AccessKey, Boolean> cache = AccessCache.getKeyCache(); final List<Instance> checkOnDB = new ArrayList<Instance>(); for (final Object instObj : _instances) { final AccessKey accessKey = AccessKey.get((Instance) instObj, _accessType); final Boolean access = cache.get(accessKey); if (access == null) { checkOnDB.add((Instance) instObj); } else { ret.put((Instance) instObj, access); } } AbstractAccessCheck_Base.LOG.trace("access result from Cache: {}", ret); if (!checkOnDB.isEmpty()) { final Map<Instance, Boolean> accessMapTmp = checkAccessOnDB(_parameter, checkOnDB, _accessType); for (final Entry<Instance, Boolean> entry : accessMapTmp.entrySet()) { final AccessKey accessKey = AccessKey.get(entry.getKey(), _accessType); cache.put(accessKey, entry.getValue()); } AbstractAccessCheck_Base.LOG.trace("access result from DB: {}", accessMapTmp); ret.putAll(accessMapTmp); } return ret; } /** * Method to check the access for a list of instances against the efaps DataBase. * * @param _parameter Parameter as passed by the eFaps API * @param _instances instances to be checked * @param _accessType type of access * @return map of access to boolean * @throws EFapsException on error */ protected Map<Instance, Boolean> checkAccessOnDB(final Parameter _parameter, final List<?> _instances, final AccessType _accessType) throws EFapsException { final Map<Instance, Boolean> accessMap = new HashMap<Instance, Boolean>(); final Context context = Context.getThreadContext(); final Type type = ((Instance) _instances.get(0)).getType(); if (type.isCheckStatus() || type.isCompanyDependent()) { final Set<Long> users = new HashSet<Long>(); final Set<Role> localRoles = new HashSet<Role>(); final StringBuilder cmd = new StringBuilder(); cmd.append("select ").append(type.getMainTable().getSqlTable()).append(".ID ") .append(" from T_ACCESSSET2USER "); boolean noCompCheck = false; if (type.isCheckStatus()) { cmd.append(" join T_ACCESSSET2STATUS on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2STATUS.ACCESSSET") .append(" join ").append(type.getMainTable().getSqlTable()).append(" on ") .append(type.getMainTable().getSqlTable()).append(".") .append(type.getStatusAttribute().getSqlColNames().get(0)) .append(" = T_ACCESSSET2STATUS.ACCESSSTATUS"); } else if (type.isCompanyDependent() && type.getMainTable().getSqlColType() != null) { // in case that it is companydependent but not status cmd.append(" join T_ACCESSSET2DMTYPE on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2DMTYPE.ACCESSSET ") .append(" join ").append(type.getMainTable().getSqlTable()) .append(" on ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getMainTable().getSqlColType()) .append(" = T_ACCESSSET2DMTYPE.DMTYPE "); } else { noCompCheck = true; } cmd.append(" where T_ACCESSSET2USER.ACCESSSET in (0"); for (final AccessSet accessSet : type.getAccessSets()) { if (accessSet.getAccessTypes().contains(_accessType)) { cmd.append(",").append(accessSet.getId()); users.addAll(accessSet.getUserIds()); } } cmd.append(") ").append("and T_ACCESSSET2USER.USERABSTRACT in (").append(context.getPersonId()); for (final Long roleId : context.getPerson().getRoles()) { if (users.contains(roleId)) { cmd.append(",").append(roleId); final Role role = Role.get(roleId); if (role.isLocal()) { localRoles.add(role); } } } cmd.append(")"); if (type.isCompanyDependent()) { if (noCompCheck) { AbstractAccessCheck_Base.LOG.error("Cannot check for Company on type '{}'", type); } else { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getCompanyAttribute().getSqlColNames().get(0)).append(" in ("); boolean first = true; for (final Long compId : context.getPerson().getCompanies()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(compId); } cmd.append(")"); } } // add the check for groups if: the type is group depended, a local // role is defined for the user, the group mechanism is activated if (type.isGroupDependent() && !localRoles.isEmpty() && EFapsSystemConfiguration.get().getAttributeValueAsBoolean( KernelSettings.ACTIVATE_GROUPS)) { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getGroupAttribute().getSqlColNames().get(0)).append(" in (") .append(" select GROUPID from T_USERASSOC where ROLEID in ("); boolean first = true; for (final Role role : localRoles) { if (first) { first = false; } else { cmd.append(","); } cmd.append(role.getId()); } cmd.append(") and GROUPID in ("); first = true; for (final Long group : context.getPerson().getGroups()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(group); } if (first) { cmd.append("0"); AbstractAccessCheck_Base.LOG.error("Missing Group for '{}' on groupdependend Access on type '{}'", context.getPerson().getName(), type); } cmd.append("))"); } final Set<Long> idList = new HashSet<Long>(); ConnectionResource con = null; try { con = context.getConnectionResource(); Statement stmt = null; try { AbstractAccessCheck_Base.LOG.debug("Checking access with: {}", cmd); stmt = con.getConnection().createStatement(); final ResultSet rs = stmt.executeQuery(cmd.toString()); while (rs.next()) { idList.add(rs.getLong(1)); } rs.close(); } finally { if (stmt != null) { stmt.close(); } } con.commit(); } catch (final SQLException e) { AbstractAccessCheck_Base.LOG.error("sql statement '" + cmd.toString() + "' not executable!", e); } finally { if ((con != null) && con.isOpened()) { con.abort(); } for (final Object inst : _instances) { accessMap.put((Instance) inst, idList.contains(((Instance) inst).getId())); } } } else { final boolean access = checkAccess(_parameter, (Instance) _instances.get(0), _accessType); for (final Object inst : _instances) { accessMap.put((Instance) inst, access); } } return accessMap; } /** * Method that queries against the database. * @param _parameter Parameter as passed by the eFasp API * @param _context Context * @param _cmd cmd * @return true if access granted else false * @throws EFapsException on error */ protected boolean executeStatement(final Parameter _parameter, final Context _context, final StringBuilder _cmd) throws EFapsException { boolean hasAccess = false; ConnectionResource con = null; try { con = _context.getConnectionResource(); AbstractAccessCheck_Base.LOG.debug("Checking access with: {}", _cmd); Statement stmt = null; try { stmt = con.getConnection().createStatement(); final ResultSet rs = stmt.executeQuery(_cmd.toString()); if (rs.next()) { hasAccess = (rs.getLong(1) > 0) ? true : false; } rs.close(); } finally { if (stmt != null) { stmt.close(); } } con.commit(); } catch (final SQLException e) { AbstractAccessCheck_Base.LOG.error("sql statement '" + _cmd.toString() + "' not executable!", e); } finally { if ((con != null) && con.isOpened()) { con.abort(); } } return hasAccess; } }
src/main/efaps/ESJP/org/efaps/esjp/admin/access/SimpleAccessCheckOnType_Base.java
/* * Copyright 2003 - 2013 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev:1563 $ * Last Changed: $Date:2007-10-28 15:07:41 +0100 (So, 28 Okt 2007) $ * Last Changed By: $Author:tmo $ */ package org.efaps.esjp.admin.access; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.efaps.admin.EFapsSystemConfiguration; import org.efaps.admin.KernelSettings; import org.efaps.admin.access.AccessCache; import org.efaps.admin.access.AccessKey; import org.efaps.admin.access.AccessSet; import org.efaps.admin.access.AccessType; import org.efaps.admin.access.AccessTypeEnums; import org.efaps.admin.datamodel.Classification; import org.efaps.admin.datamodel.Type; import org.efaps.admin.event.Parameter; import org.efaps.admin.event.Parameter.ParameterValues; import org.efaps.admin.program.esjp.EFapsApplication; import org.efaps.admin.program.esjp.EFapsUUID; import org.efaps.admin.user.Role; import org.efaps.db.Context; import org.efaps.db.Instance; import org.efaps.db.transaction.ConnectionResource; import org.efaps.util.EFapsException; import org.infinispan.Cache; /** * This Class is used to check if a user can Access this Type.<br> * The method execute is called with the Instance and the Accesstype as * parameters. For the instance object it is checked if the current context user * has the access defined in the list of access types. * * @author The eFaps Team * @version $Id:SimpleAccessCheckOnType.java 1563 2007-10-28 14:07:41Z tmo $ */ @EFapsUUID("628a19f6-463f-415d-865b-ba72e303a507") @EFapsApplication("eFaps-Kernel") public abstract class SimpleAccessCheckOnType_Base extends AbstractAccessCheck { /** * {@inheritDoc} */ @Override protected boolean checkAccess(final Parameter _parameter, final Instance _instance, final AccessType _accessType) throws EFapsException { boolean ret = false; final Cache<AccessKey, Boolean> cache = AccessCache.getKeyCache(); final AccessKey accessKey = AccessKey.get(_instance, _accessType); final Boolean access = cache.get(accessKey); if (access == null) { ret = checkAccessOnDB(_parameter, _instance, _accessType); AbstractAccessCheck_Base.LOG.trace("access result :{} from DB for: {}", ret, _instance); cache.put(accessKey, ret); } else { ret = access; AbstractAccessCheck_Base.LOG.trace("access result :{} from Cache for: {}", ret, _instance); } return ret; } /** * Check for the instance object if the current context user has the access * defined in the list of access types against the eFaps DataBase. * * @param _parameter Parameter as passed by the eFaps API * @param _instance instance to check for access for * @param _accessType accesstyep to check the access for * @return true if access is granted, else false * @throws EFapsException on error */ protected boolean checkAccessOnDB(final Parameter _parameter, final Instance _instance, final AccessType _accessType) throws EFapsException { final Context context = Context.getThreadContext(); final StringBuilder cmd = new StringBuilder(); cmd.append("select count(*) from T_ACCESSSET2USER "); Type type; if (_parameter.get(ParameterValues.CLASS) instanceof Classification) { type = (Classification) _parameter.get(ParameterValues.CLASS); } else { type = _instance.getType(); } final Set<Long> users = new HashSet<Long>(); final Set<Role> localRoles = new HashSet<Role>(); boolean noCompCheck = false; if (type.isCheckStatus() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { cmd.append(" join T_ACCESSSET2STATUS on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2STATUS.ACCESSSET") .append(" join ").append(type.getMainTable().getSqlTable()) .append(" on ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getStatusAttribute().getSqlColNames().get(0)) .append(" = T_ACCESSSET2STATUS.ACCESSSTATUS"); } else if (type.isCompanyDependent() && type.getMainTable().getSqlColType() != null && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { // in case that it is companydependent but not status cmd.append(" join T_ACCESSSET2DMTYPE on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2DMTYPE.ACCESSSET ") .append(" join ").append(type.getMainTable().getSqlTable()) .append(" on ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getMainTable().getSqlColType()) .append(" = T_ACCESSSET2DMTYPE.DMTYPE "); } else { noCompCheck = true; } cmd.append(" where T_ACCESSSET2USER.ACCESSSET in (0"); for (final AccessSet accessSet : type.getAccessSets()) { if (accessSet.getAccessTypes().contains(_accessType)) { cmd.append(",").append(accessSet.getId()); users.addAll(accessSet.getUserIds()); } } cmd.append(") ").append("and T_ACCESSSET2USER.USERABSTRACT in (").append(context.getPersonId()); for (final Long roleId : context.getPerson().getRoles()) { if (users.contains(roleId)) { cmd.append(",").append(roleId); final Role role = Role.get(roleId); if (role.isLocal()) { localRoles.add(role); } } } cmd.append(")"); if (type.isCheckStatus() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".ID = ").append(_instance.getId()); } if (type.isCompanyDependent() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType())) { if (noCompCheck) { AbstractAccessCheck_Base.LOG.error("Cannot check for Company on type '{}'", type); } else { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getCompanyAttribute().getSqlColNames().get(0)).append(" in ("); boolean first = true; for (final Long compId : context.getPerson().getCompanies()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(compId); } cmd.append(")"); } } if (type.isGroupDependent() && !_accessType.equals(AccessTypeEnums.CREATE.getAccessType()) && !localRoles.isEmpty() && EFapsSystemConfiguration.get().getAttributeValueAsBoolean( KernelSettings.ACTIVATE_GROUPS)) { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getGroupAttribute().getSqlColNames().get(0)).append(" in (") .append(" select GROUPID from T_USERASSOC where ROLEID in ("); boolean first = true; for (final Role role : localRoles) { if (first) { first = false; } else { cmd.append(","); } cmd.append(role.getId()); } cmd.append(") and GROUPID in ("); first = true; for (final Long group : context.getPerson().getGroups()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(group); } if (first) { cmd.append("0"); AbstractAccessCheck_Base.LOG.error("Missing Group for '{}' on groupdependend Access on type '{}'", context.getPerson().getName(), type); } cmd.append("))"); } AbstractAccessCheck_Base.LOG.debug("cheking access with: {}", cmd); return executeStatement(_parameter, context, cmd); } /** * {@inheritDoc} */ @Override protected Map<Instance, Boolean> checkAccess(final Parameter _parameter, final List<?> _instances, final AccessType _accessType) throws EFapsException { final Map<Instance, Boolean> ret = new HashMap<Instance, Boolean>(); final Cache<AccessKey, Boolean> cache = AccessCache.getKeyCache(); final List<Instance> checkOnDB = new ArrayList<Instance>(); for (final Object instObj : _instances) { final AccessKey accessKey = AccessKey.get((Instance) instObj, _accessType); final Boolean access = cache.get(accessKey); if (access == null) { checkOnDB.add((Instance) instObj); } else { ret.put((Instance) instObj, access); } } AbstractAccessCheck_Base.LOG.trace("access result from Cache: {}", ret); if (!checkOnDB.isEmpty()) { final Map<Instance, Boolean> accessMapTmp = checkAccessOnDB(_parameter, checkOnDB, _accessType); for (final Entry<Instance, Boolean> entry : accessMapTmp.entrySet()) { final AccessKey accessKey = AccessKey.get(entry.getKey(), _accessType); cache.put(accessKey, entry.getValue()); } AbstractAccessCheck_Base.LOG.trace("access result from DB: {}", accessMapTmp); ret.putAll(accessMapTmp); } return ret; } /** * Method to check the access for a list of instances against the efaps DataBase. * * @param _parameter Parameter as passed by the eFaps API * @param _instances instances to be checked * @param _accessType type of access * @return map of access to boolean * @throws EFapsException on error */ protected Map<Instance, Boolean> checkAccessOnDB(final Parameter _parameter, final List<?> _instances, final AccessType _accessType) throws EFapsException { final Map<Instance, Boolean> accessMap = new HashMap<Instance, Boolean>(); final Context context = Context.getThreadContext(); final Type type = ((Instance) _instances.get(0)).getType(); if (type.isCheckStatus() || type.isCompanyDependent()) { final Set<Long> users = new HashSet<Long>(); final Set<Role> localRoles = new HashSet<Role>(); final StringBuilder cmd = new StringBuilder(); cmd.append("select ").append(type.getMainTable().getSqlTable()).append(".ID ") .append(" from T_ACCESSSET2USER ") .append(" join T_ACCESSSET2STATUS on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2STATUS.ACCESSSET"); boolean noCompCheck = false; if (type.isCheckStatus()) { cmd.append(" join ").append(type.getMainTable().getSqlTable()).append(" on ") .append(type.getMainTable().getSqlTable()).append(".") .append(type.getStatusAttribute().getSqlColNames().get(0)) .append(" = T_ACCESSSET2STATUS.ACCESSSTATUS"); } else if (type.isCompanyDependent() && type.getMainTable().getSqlColType() != null) { // in case that it is companydependent but not status cmd.append(" join T_ACCESSSET2DMTYPE on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2DMTYPE.ACCESSSET ") .append(" join ").append(type.getMainTable().getSqlTable()) .append(" on ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getMainTable().getSqlColType()) .append(" = T_ACCESSSET2DMTYPE.DMTYPE "); } else { noCompCheck = true; } cmd.append(" where T_ACCESSSET2USER.ACCESSSET in (0"); for (final AccessSet accessSet : type.getAccessSets()) { if (accessSet.getAccessTypes().contains(_accessType)) { cmd.append(",").append(accessSet.getId()); users.addAll(accessSet.getUserIds()); } } cmd.append(") ").append("and T_ACCESSSET2USER.USERABSTRACT in (").append(context.getPersonId()); for (final Long roleId : context.getPerson().getRoles()) { if (users.contains(roleId)) { cmd.append(",").append(roleId); final Role role = Role.get(roleId); if (role.isLocal()) { localRoles.add(role); } } } cmd.append(")"); if (type.isCompanyDependent()) { if (noCompCheck) { AbstractAccessCheck_Base.LOG.error("Cannot check for Company on type '{}'", type); } else { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getCompanyAttribute().getSqlColNames().get(0)).append(" in ("); boolean first = true; for (final Long compId : context.getPerson().getCompanies()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(compId); } cmd.append(")"); } } // add the check for groups if: the type is group depended, a local // role is defined for the user, the group mechanism is activated if (type.isGroupDependent() && !localRoles.isEmpty() && EFapsSystemConfiguration.get().getAttributeValueAsBoolean( KernelSettings.ACTIVATE_GROUPS)) { cmd.append(" and ").append(type.getMainTable().getSqlTable()).append(".") .append(type.getGroupAttribute().getSqlColNames().get(0)).append(" in (") .append(" select GROUPID from T_USERASSOC where ROLEID in ("); boolean first = true; for (final Role role : localRoles) { if (first) { first = false; } else { cmd.append(","); } cmd.append(role.getId()); } cmd.append(") and GROUPID in ("); first = true; for (final Long group : context.getPerson().getGroups()) { if (first) { first = false; } else { cmd.append(","); } cmd.append(group); } if (first) { cmd.append("0"); AbstractAccessCheck_Base.LOG.error("Missing Group for '{}' on groupdependend Access on type '{}'", context.getPerson().getName(), type); } cmd.append("))"); } final Set<Long> idList = new HashSet<Long>(); ConnectionResource con = null; try { con = context.getConnectionResource(); Statement stmt = null; try { AbstractAccessCheck_Base.LOG.debug("Checking access with: {}", cmd); stmt = con.getConnection().createStatement(); final ResultSet rs = stmt.executeQuery(cmd.toString()); while (rs.next()) { idList.add(rs.getLong(1)); } rs.close(); } finally { if (stmt != null) { stmt.close(); } } con.commit(); } catch (final SQLException e) { AbstractAccessCheck_Base.LOG.error("sql statement '" + cmd.toString() + "' not executable!", e); } finally { if ((con != null) && con.isOpened()) { con.abort(); } for (final Object inst : _instances) { accessMap.put((Instance) inst, idList.contains(((Instance) inst).getId())); } } } else { final boolean access = checkAccess(_parameter, (Instance) _instances.get(0), _accessType); for (final Object inst : _instances) { accessMap.put((Instance) inst, access); } } return accessMap; } /** * Method that queries against the database. * @param _parameter Parameter as passed by the eFasp API * @param _context Context * @param _cmd cmd * @return true if access granted else false * @throws EFapsException on error */ protected boolean executeStatement(final Parameter _parameter, final Context _context, final StringBuilder _cmd) throws EFapsException { boolean hasAccess = false; ConnectionResource con = null; try { con = _context.getConnectionResource(); AbstractAccessCheck_Base.LOG.debug("Checking access with: {}", _cmd); Statement stmt = null; try { stmt = con.getConnection().createStatement(); final ResultSet rs = stmt.executeQuery(_cmd.toString()); if (rs.next()) { hasAccess = (rs.getLong(1) > 0) ? true : false; } rs.close(); } finally { if (stmt != null) { stmt.close(); } } con.commit(); } catch (final SQLException e) { AbstractAccessCheck_Base.LOG.error("sql statement '" + _cmd.toString() + "' not executable!", e); } finally { if ((con != null) && con.isOpened()) { con.abort(); } } return hasAccess; } }
- Issue #38: The check for simple access does return wrong value if not status dependend closes #38
src/main/efaps/ESJP/org/efaps/esjp/admin/access/SimpleAccessCheckOnType_Base.java
- Issue #38: The check for simple access does return wrong value if not status dependend
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/admin/access/SimpleAccessCheckOnType_Base.java <ide> final Set<Role> localRoles = new HashSet<Role>(); <ide> final StringBuilder cmd = new StringBuilder(); <ide> cmd.append("select ").append(type.getMainTable().getSqlTable()).append(".ID ") <del> .append(" from T_ACCESSSET2USER ") <del> .append(" join T_ACCESSSET2STATUS on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2STATUS.ACCESSSET"); <add> .append(" from T_ACCESSSET2USER "); <ide> <ide> boolean noCompCheck = false; <ide> if (type.isCheckStatus()) { <del> cmd.append(" join ").append(type.getMainTable().getSqlTable()).append(" on ") <add> cmd.append(" join T_ACCESSSET2STATUS on T_ACCESSSET2USER.ACCESSSET = T_ACCESSSET2STATUS.ACCESSSET") <add> .append(" join ").append(type.getMainTable().getSqlTable()).append(" on ") <ide> .append(type.getMainTable().getSqlTable()).append(".") <ide> .append(type.getStatusAttribute().getSqlColNames().get(0)) <ide> .append(" = T_ACCESSSET2STATUS.ACCESSSTATUS");
JavaScript
apache-2.0
5e5410ea1ddd4d9357d8cf65dc925a403e7f0eea
0
Kurento/kurento-utils-js,Kurento/kurento-utils-js,Kurento/kurento-utils-js
/* * (C) Copyright 2014-2015 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ var freeice = require('freeice'); var inherits = require('inherits'); var EventEmitter = require('events').EventEmitter; var recursive = require('merge').recursive const MEDIA_CONSTRAINTS = { audio: true, video: { mandatory: { maxWidth: 640, maxFrameRate: 15, minFrameRate: 15 } } } function noop(error) { if (error) return console.trace(error) } function trackStop(track) { track.stop && track.stop() } function streamStop(stream) { stream.getTracks().forEach(trackStop) } /** * Wrapper object of an RTCPeerConnection. This object is aimed to simplify the * development of WebRTC-based applications. * * @constructor module:kurentoUtils.WebRtcPeer * * @param {String} mode Mode in which the PeerConnection will be configured. * Valid values are: 'recv', 'send', and 'sendRecv' * @param localVideo Video tag for the local stream * @param remoteVideo Video tag for the remote stream * @param {MediaStream} videoStream Stream to be used as primary source * (typically video and audio, or only video if combined with audioStream) for * localVideo and to be added as stream to the RTCPeerConnection * @param {MediaStream} audioStream Stream to be used as second source * (typically for audio) for localVideo and to be added as stream to the * RTCPeerConnection */ function WebRtcPeer(mode, options, callback) { if (!(this instanceof WebRtcPeer)) return new WebRtcPeer(mode, options, callback) WebRtcPeer.super_.call(this) if (options instanceof Function) { callback = options options = undefined } options = options || {} callback = (callback || noop).bind(this) var localVideo = options.localVideo; var remoteVideo = options.remoteVideo; var videoStream = options.videoStream; var audioStream = options.audioStream; var mediaConstraints = options.mediaConstraints; var connectionConstraints = options.connectionConstraints; var pc = options.peerConnection var sendSource = options.sendSource || 'webcam' var configuration = recursive({ iceServers: freeice() }, options.configuration); var onicecandidate = options.onicecandidate; if (onicecandidate) this.on('icecandidate', onicecandidate); var oncandidategatheringdone = options.oncandidategatheringdone; if (oncandidategatheringdone) this.on('candidategatheringdone', oncandidategatheringdone); // Init PeerConnection if (!pc) pc = new RTCPeerConnection(configuration); Object.defineProperty(this, 'peerConnection', { get: function () { return pc; } }); /** * @member {(external:ImageData|undefined)} currentFrame */ Object.defineProperty(this, 'currentFrame', { get: function () { // [ToDo] Find solution when we have a remote stream but we didn't set // a remoteVideo tag if (!remoteVideo) return; if (remoteVideo.readyState < remoteVideo.HAVE_CURRENT_DATA) throw new Error('No video stream data available') var canvas = document.createElement('canvas') canvas.width = remoteVideo.videoWidth canvas.height = remoteVideo.videoHeight canvas.getContext('2d').drawImage(remoteVideo, 0, 0) return canvas } }); var self = this; var candidategatheringdone = false pc.addEventListener('icecandidate', function (event) { var candidate = event.candidate if (candidate) { self.emit('icecandidate', candidate); candidategatheringdone = false } else if (!candidategatheringdone) { self.emit('candidategatheringdone'); candidategatheringdone = true } }); var candidatesQueue = [] /** * Callback function invoked when an ICE candidate is received. Developers are * expected to invoke this function in order to complete the SDP negotiation. * * @function module:kurentoUtils.WebRtcPeer.prototype.addIceCandidate * * @param iceCandidate - Literal object with the ICE candidate description * @param callback - Called when the ICE candidate has been added. */ this.addIceCandidate = function (iceCandidate, callback) { var candidate = new RTCIceCandidate(iceCandidate); console.log('ICE candidate received'); callback = (callback || noop).bind(this) switch (pc.signalingState) { case 'closed': Callback(new Error('PeerConnection object is closed')) break case 'stable': if (pc.remoteDescription) { pc.addIceCandidate(candidate, callback, callback); break; } default: candidatesQueue.push({ candidate: candidate, callback: callback }) } } pc.addEventListener('signalingstatechange', function () { if (this.signalingState == 'stable') while (candidatesQueue.length) { var entry = candidatesQueue.shift() this.addIceCandidate(entry.candidate, entry.callback, entry.callback); } }) this.generateOffer = function (callback) { callback = callback.bind(this) var constraints = recursive({ offerToReceiveAudio: (mode !== 'sendonly'), offerToReceiveVideo: (mode !== 'sendonly') }, connectionConstraints); console.log('constraints: ' + JSON.stringify(constraints)); pc.createOffer(function (offer) { console.log('Created SDP offer'); pc.setLocalDescription(offer, function () { console.log('Local description set', offer.sdp); callback(null, offer.sdp, self.processAnswer.bind(self)); }, callback); }, callback, constraints); } this.getLocalSessionDescriptor = function () { return pc.localDescription } this.getRemoteSessionDescriptor = function () { return pc.remoteDescription } function setRemoteVideo() { if (remoteVideo) { var stream = pc.getRemoteStreams()[0] var url = stream ? URL.createObjectURL(stream) : ""; remoteVideo.src = url; console.log('Remote URL:', url) } } /** * Callback function invoked when a SDP answer is received. Developers are * expected to invoke this function in order to complete the SDP negotiation. * * @function module:kurentoUtils.WebRtcPeer.prototype.processAnswer * * @param sdpAnswer - Description of sdpAnswer * @param callback - * Invoked after the SDP answer is processed, or there is an error. */ this.processAnswer = function (sdpAnswer, callback) { callback = (callback || noop).bind(this) var answer = new RTCSessionDescription({ type: 'answer', sdp: sdpAnswer, }); console.log('SDP answer received, setting remote description'); if (pc.signalingState == 'closed') return callback('PeerConnection is closed') pc.setRemoteDescription(answer, function () { setRemoteVideo() callback(); }, callback); } /** * Callback function invoked when a SDP offer is received. Developers are * expected to invoke this function in order to complete the SDP negotiation. * * @function module:kurentoUtils.WebRtcPeer.prototype.processOffer * * @param sdpOffer - Description of sdpOffer * @param callback - Called when the remote description has been set * successfully. */ this.processOffer = function (sdpOffer, callback) { callback = callback.bind(this) var offer = new RTCSessionDescription({ type: 'offer', sdp: sdpOffer, }); console.log('SDP offer received, setting remote description'); if (pc.signalingState == 'closed') return callback('PeerConnection is closed') pc.setRemoteDescription(offer, function () { setRemoteVideo() // Generate answer var constraints = recursive({ // offerToReceiveAudio: (mode !== 'sendonly'), // offerToReceiveVideo: (mode !== 'sendonly') }, connectionConstraints); console.log('constraints: ' + JSON.stringify(constraints)); pc.createAnswer(function (answer) { console.log('Created SDP answer'); pc.setLocalDescription(answer, function () { console.log('Local description set', answer.sdp); callback(null, answer.sdp); }, callback); }, callback, constraints); }, callback); } /** * This function creates the RTCPeerConnection object taking into account the * properties received in the constructor. It starts the SDP negotiation * process: generates the SDP offer and invokes the onsdpoffer callback. This * callback is expected to send the SDP offer, in order to obtain an SDP * answer from another peer. */ function start() { if (videoStream && localVideo) { localVideo.src = URL.createObjectURL(videoStream); localVideo.muted = true; } if (videoStream) pc.addStream(videoStream); if (audioStream) pc.addStream(audioStream); // [Hack] https://code.google.com/p/chromium/issues/detail?id=443558 if (mode == 'sendonly') mode = 'sendrecv'; // // Create the offer with the required constraints // self.generateOffer(callback) callback() } if (mode !== 'recvonly' && !videoStream && !audioStream) { function getMedia(constraints) { getUserMedia(recursive(MEDIA_CONSTRAINTS, constraints), function ( stream) { videoStream = stream; start() }, callback); } if (sendSource != 'webcam' && !mediaConstraints) getScreenConstraints(sendMode, function (error, constraints) { if (error) return callback(error) getMedia(constraints) }) else getMedia(mediaConstraints) } else { setTimeout(start, 0) } this.on('_dispose', function () { if (localVideo) localVideo.src = ''; if (remoteVideo) remoteVideo.src = ''; }) } inherits(WebRtcPeer, EventEmitter) Object.defineProperty(WebRtcPeer.prototype, 'enabled', { enumerable: true, get: function () { return this.audioEnabled && this.videoEnabled; }, set: function (value) { this.audioEnabled = this.videoEnabled = value } }) function createEnableDescriptor(type) { var method = 'get' + type + 'Tracks' return { enumerable: true, get: function () { // [ToDo] Should return undefined if not all tracks have the same value? if (!this.peerConnection) return; var streams = this.peerConnection.getLocalStreams(); if (!streams.length) return; for (var i = 0, stream; stream = streams[i]; i++) { var tracks = stream[method]() for (var j = 0, track; track = tracks[j]; j++) if (!track.enabled) return false; } return true; }, set: function (value) { function trackSetEnable(track) { track.enabled = value; } this.peerConnection.getLocalStreams().forEach(function (stream) { stream[method]().forEach(trackSetEnable) }) } } } Object.defineProperty(WebRtcPeer.prototype, 'audioEnabled', createEnableDescriptor('Audio')) Object.defineProperty(WebRtcPeer.prototype, 'videoEnabled', createEnableDescriptor('Video')) WebRtcPeer.prototype.getLocalStream = function (index) { if (this.peerConnection) return this.peerConnection.getLocalStreams()[index || 0] } WebRtcPeer.prototype.getRemoteStream = function (index) { if (this.peerConnection) return this.peerConnection.getRemoteStreams()[index || 0] } /** * @description This method frees the resources used by WebRtcPeer. * * @function module:kurentoUtils.WebRtcPeer.prototype.dispose */ WebRtcPeer.prototype.dispose = function () { console.log('Disposing WebRtcPeer'); var pc = this.peerConnection; if (pc) { if (pc.signalingState == 'closed') return pc.getLocalStreams().forEach(streamStop) // FIXME This is not yet implemented in firefox // if(videoStream) pc.removeStream(videoStream); // if(audioStream) pc.removeStream(audioStream); pc.close(); } this.emit('_dispose'); }; // // Specialized child classes // function WebRtcPeerRecvonly(options, callback) { if (!(this instanceof WebRtcPeerRecvonly)) return new WebRtcPeerRecvonly(options, callback) WebRtcPeerRecvonly.super_.call(this, 'recvonly', options, callback) } inherits(WebRtcPeerRecvonly, WebRtcPeer) function WebRtcPeerSendonly(options, callback) { if (!(this instanceof WebRtcPeerSendonly)) return new WebRtcPeerSendonly(options, callback) WebRtcPeerSendonly.super_.call(this, 'sendonly', options, callback) } inherits(WebRtcPeerSendonly, WebRtcPeer) function WebRtcPeerSendrecv(options, callback) { if (!(this instanceof WebRtcPeerSendrecv)) return new WebRtcPeerSendrecv(options, callback) WebRtcPeerSendrecv.super_.call(this, 'sendrecv', options, callback) } inherits(WebRtcPeerSendrecv, WebRtcPeer) exports.WebRtcPeerRecvonly = WebRtcPeerRecvonly; exports.WebRtcPeerSendonly = WebRtcPeerSendonly; exports.WebRtcPeerSendrecv = WebRtcPeerSendrecv;
lib/WebRtcPeer.js
/* * (C) Copyright 2014-2015 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ var freeice = require('freeice'); var inherits = require('inherits'); var EventEmitter = require('events').EventEmitter; var recursive = require('merge').recursive const MEDIA_CONSTRAINTS = { audio: true, video: { mandatory: { maxWidth: 640, maxFrameRate: 15, minFrameRate: 15 } } } function noop(error) { if (error) return console.trace(error) } function trackStop(track) { track.stop && track.stop() } function streamStop(stream) { stream.getTracks().forEach(trackStop) } /** * Wrapper object of an RTCPeerConnection. This object is aimed to simplify the * development of WebRTC-based applications. * * @constructor module:kurentoUtils.WebRtcPeer * * @param {String} mode Mode in which the PeerConnection will be configured. * Valid values are: 'recv', 'send', and 'sendRecv' * @param localVideo Video tag for the local stream * @param remoteVideo Video tag for the remote stream * @param {MediaStream} videoStream Stream to be used as primary source * (typically video and audio, or only video if combined with audioStream) for * localVideo and to be added as stream to the RTCPeerConnection * @param {MediaStream} audioStream Stream to be used as second source * (typically for audio) for localVideo and to be added as stream to the * RTCPeerConnection */ function WebRtcPeer(mode, options, callback) { if (!(this instanceof WebRtcPeer)) return new WebRtcPeer(mode, options, callback) WebRtcPeer.super_.call(this) if (options instanceof Function) { callback = options options = undefined } options = options || {} callback = (callback || noop).bind(this) var localVideo = options.localVideo; var remoteVideo = options.remoteVideo; var videoStream = options.videoStream; var audioStream = options.audioStream; var mediaConstraints = options.mediaConstraints; var connectionConstraints = options.connectionConstraints; var pc = options.peerConnection var sendSource = options.sendSource || 'webcam' var configuration = recursive({ iceServers: freeice() }, options.configuration); var onicecandidate = options.onicecandidate; if (onicecandidate) this.on('icecandidate', onicecandidate); var oncandidategatheringdone = options.oncandidategatheringdone; if (oncandidategatheringdone) this.on('candidategatheringdone', oncandidategatheringdone); // Init PeerConnection if (!pc) pc = new RTCPeerConnection(configuration); Object.defineProperty(this, 'peerConnection', { get: function () { return pc; } }); /** * @member {(external:ImageData|undefined)} currentFrame */ Object.defineProperty(this, 'currentFrame', { get: function () { // [ToDo] Find solution when we have a remote stream but we didn't set // a remoteVideo tag if (!remoteVideo) return; if (remoteVideo.readyState < remoteVideo.HAVE_CURRENT_DATA) throw new Error('No video stream data available') var canvas = document.createElement('canvas') canvas.width = remoteVideo.videoWidth canvas.height = remoteVideo.videoHeight canvas.getContext('2d').drawImage(remoteVideo, 0, 0) return canvas } }); var self = this; var candidategatheringdone = false pc.addEventListener('icecandidate', function (event) { var candidate = event.candidate if (candidate) { self.emit('icecandidate', candidate); candidategatheringdone = false } else if (!candidategatheringdone) { self.emit('candidategatheringdone'); candidategatheringdone = true } }); var candidatesQueue = [] /** * Callback function invoked when an ICE candidate is received. Developers are * expected to invoke this function in order to complete the SDP negotiation. * * @function module:kurentoUtils.WebRtcPeer.prototype.addIceCandidate * * @param iceCandidate - Literal object with the ICE candidate description * @param callback - Called when the ICE candidate has been added. */ this.addIceCandidate = function (iceCandidate, callback) { var candidate = new RTCIceCandidate(iceCandidate); console.log('ICE candidate received'); callback = (callback || noop).bind(this) switch (pc.signalingState) { case 'closed': Callback(new Error('PeerConnection object is closed')) break case 'stable': if (pc.remoteDescription) { pc.addIceCandidate(candidate, callback, callback); break; } default: candidatesQueue.push({ candidate: candidate, callback: callback }) } } pc.addEventListener('signalingstatechange', function () { if (this.signalingState == 'stable') while (candidatesQueue.length) { var entry = candidatesQueue.shift() this.addIceCandidate(entry.candidate, entry.callback, entry.callback); } }) this.generateOffer = function (callback) { callback = callback.bind(this) var constraints = recursive({ offerToReceiveAudio: (mode !== 'sendonly'), offerToReceiveVideo: (mode !== 'sendonly') }, connectionConstraints); console.log('constraints: ' + JSON.stringify(constraints)); pc.createOffer(function (offer) { console.log('Created SDP offer'); pc.setLocalDescription(offer, function () { console.log('Local description set', offer.sdp); callback(null, offer.sdp, self.processAnswer.bind(self)); }, callback); }, callback, constraints); } this.getLocalSessionDescriptor = function () { return pc.localDescription } this.getRemoteSessionDescriptor = function () { return pc.remoteDescription } function setRemoteVideo() { if (remoteVideo) { var stream = pc.getRemoteStreams()[0] var url = stream ? URL.createObjectURL(stream) : ""; remoteVideo.src = url; console.log('Remote URL:', url) } } /** * Callback function invoked when a SDP answer is received. Developers are * expected to invoke this function in order to complete the SDP negotiation. * * @function module:kurentoUtils.WebRtcPeer.prototype.processAnswer * * @param sdpAnswer - Description of sdpAnswer * @param callback - * Invoked after the SDP answer is processed, or there is an error. */ this.processAnswer = function (sdpAnswer, callback) { callback = (callback || noop).bind(this) var answer = new RTCSessionDescription({ type: 'answer', sdp: sdpAnswer, }); console.log('SDP answer received, setting remote description'); if (pc.signalingState == 'closed') return callback('PeerConnection is closed') pc.setRemoteDescription(answer, function () { setRemoteVideo() callback(); }, callback); } /** * Callback function invoked when a SDP offer is received. Developers are * expected to invoke this function in order to complete the SDP negotiation. * * @function module:kurentoUtils.WebRtcPeer.prototype.processOffer * * @param sdpOffer - Description of sdpOffer * @param callback - Called when the remote description has been set * successfully. */ this.processOffer = function (sdpOffer, callback) { callback = callback.bind(this) var offer = new RTCSessionDescription({ type: 'offer', sdp: sdpOffer, }); console.log('SDP offer received, setting remote description'); if (pc.signalingState == 'closed') return callback('PeerConnection is closed') pc.setRemoteDescription(offer, function () { setRemoteVideo() // Generate answer var constraints = recursive({ offerToReceiveAudio: (mode !== 'sendonly'), offerToReceiveVideo: (mode !== 'sendonly') }, connectionConstraints); console.log('constraints: ' + JSON.stringify(constraints)); pc.createAnswer(function (answer) { console.log('Created SDP answer'); pc.setLocalDescription(answer, function () { console.log('Local description set', answer.sdp); callback(null, answer.sdp); }, callback); }, callback, constraints); }, callback); } /** * This function creates the RTCPeerConnection object taking into account the * properties received in the constructor. It starts the SDP negotiation * process: generates the SDP offer and invokes the onsdpoffer callback. This * callback is expected to send the SDP offer, in order to obtain an SDP * answer from another peer. */ function start() { if (videoStream && localVideo) { localVideo.src = URL.createObjectURL(videoStream); localVideo.muted = true; } if (videoStream) pc.addStream(videoStream); if (audioStream) pc.addStream(audioStream); // [Hack] https://code.google.com/p/chromium/issues/detail?id=443558 if (mode == 'sendonly') mode = 'sendrecv'; // // Create the offer with the required constraints // self.generateOffer(callback) callback() } if (mode !== 'recvonly' && !videoStream && !audioStream) { function getMedia(constraints) { getUserMedia(recursive(MEDIA_CONSTRAINTS, constraints), function ( stream) { videoStream = stream; start() }, callback); } if (sendSource != 'webcam' && !mediaConstraints) getScreenConstraints(sendMode, function (error, constraints) { if (error) return callback(error) getMedia(constraints) }) else getMedia(mediaConstraints) } else { setTimeout(start, 0) } this.on('_dispose', function () { if (localVideo) localVideo.src = ''; if (remoteVideo) remoteVideo.src = ''; }) } inherits(WebRtcPeer, EventEmitter) Object.defineProperty(WebRtcPeer.prototype, 'enabled', { enumerable: true, get: function () { return this.audioEnabled && this.videoEnabled; }, set: function (value) { this.audioEnabled = this.videoEnabled = value } }) function createEnableDescriptor(type) { var method = 'get' + type + 'Tracks' return { enumerable: true, get: function () { // [ToDo] Should return undefined if not all tracks have the same value? if (!this.peerConnection) return; var streams = this.peerConnection.getLocalStreams(); if (!streams.length) return; for (var i = 0, stream; stream = streams[i]; i++) { var tracks = stream[method]() for (var j = 0, track; track = tracks[j]; j++) if (!track.enabled) return false; } return true; }, set: function (value) { function trackSetEnable(track) { track.enabled = value; } this.peerConnection.getLocalStreams().forEach(function (stream) { stream[method]().forEach(trackSetEnable) }) } } } Object.defineProperty(WebRtcPeer.prototype, 'audioEnabled', createEnableDescriptor('Audio')) Object.defineProperty(WebRtcPeer.prototype, 'videoEnabled', createEnableDescriptor('Video')) WebRtcPeer.prototype.getLocalStream = function (index) { if (this.peerConnection) return this.peerConnection.getLocalStreams()[index || 0] } WebRtcPeer.prototype.getRemoteStream = function (index) { if (this.peerConnection) return this.peerConnection.getRemoteStreams()[index || 0] } /** * @description This method frees the resources used by WebRtcPeer. * * @function module:kurentoUtils.WebRtcPeer.prototype.dispose */ WebRtcPeer.prototype.dispose = function () { console.log('Disposing WebRtcPeer'); var pc = this.peerConnection; if (pc) { if (pc.signalingState == 'closed') return pc.getLocalStreams().forEach(streamStop) // FIXME This is not yet implemented in firefox // if(videoStream) pc.removeStream(videoStream); // if(audioStream) pc.removeStream(audioStream); pc.close(); } this.emit('_dispose'); }; // // Specialized child classes // function WebRtcPeerRecvonly(options, callback) { if (!(this instanceof WebRtcPeerRecvonly)) return new WebRtcPeerRecvonly(options, callback) WebRtcPeerRecvonly.super_.call(this, 'recvonly', options, callback) } inherits(WebRtcPeerRecvonly, WebRtcPeer) function WebRtcPeerSendonly(options, callback) { if (!(this instanceof WebRtcPeerSendonly)) return new WebRtcPeerSendonly(options, callback) WebRtcPeerSendonly.super_.call(this, 'sendonly', options, callback) } inherits(WebRtcPeerSendonly, WebRtcPeer) function WebRtcPeerSendrecv(options, callback) { if (!(this instanceof WebRtcPeerSendrecv)) return new WebRtcPeerSendrecv(options, callback) WebRtcPeerSendrecv.super_.call(this, 'sendrecv', options, callback) } inherits(WebRtcPeerSendrecv, WebRtcPeer) exports.WebRtcPeerRecvonly = WebRtcPeerRecvonly; exports.WebRtcPeerSendonly = WebRtcPeerSendonly; exports.WebRtcPeerSendrecv = WebRtcPeerSendrecv;
Don't use offerToReceive(Audio|Video) on createAnswer() Change-Id: I72845fae896911762e892c7ed6461e1c4ef7191b
lib/WebRtcPeer.js
Don't use offerToReceive(Audio|Video) on createAnswer()
<ide><path>ib/WebRtcPeer.js <ide> // Generate answer <ide> <ide> var constraints = recursive({ <del> offerToReceiveAudio: (mode !== 'sendonly'), <del> offerToReceiveVideo: (mode !== 'sendonly') <add> // offerToReceiveAudio: (mode !== 'sendonly'), <add> // offerToReceiveVideo: (mode !== 'sendonly') <ide> }, connectionConstraints); <ide> <ide> console.log('constraints: ' + JSON.stringify(constraints));
Java
apache-2.0
23789171ab4702d68235d5a6fc2a28a1ea2209cc
0
mureinik/commons-lang,rikles/commons-lang,mureinik/commons-lang,rikles/commons-lang,rikles/commons-lang,mureinik/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,anzhdanov/seeding-realistic-concurrency-bugs,anzhdanov/seeding-realistic-concurrency-bugs
/* * Copyright 2002-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.lang.builder.BuilderTestSuite; import org.apache.commons.lang.enums.EnumTestSuite; import org.apache.commons.lang.exception.ExceptionTestSuite; import org.apache.commons.lang.math.MathTestSuite; import org.apache.commons.lang.mutable.MutableTestSuite; import org.apache.commons.lang.text.TextTestSuite; import org.apache.commons.lang.time.TimeTestSuite; /** * Test suite for [lang]. * * @author Stephen Colebourne * @version $Id$ */ public class AllLangTestSuite extends TestCase { /** * Construct a new instance. */ public AllLangTestSuite(String name) { super(name); } /** * Command-line interface. */ public static void main(String[] args) { TestRunner.run(suite()); } /** * Get the suite of tests */ public static Test suite() { TestSuite suite = new TestSuite(); suite.setName("Commons-Lang (all) Tests"); suite.addTest(LangTestSuite.suite()); suite.addTest(BuilderTestSuite.suite()); suite.addTest(EnumTestSuite.suite()); suite.addTest(org.apache.commons.lang.enum.EnumTestSuite.suite()); suite.addTest(ExceptionTestSuite.suite()); suite.addTest(MathTestSuite.suite()); suite.addTest(MutableTestSuite.suite()); suite.addTest(TextTestSuite.suite()); suite.addTest(TimeTestSuite.suite()); return suite; } }
src/test/org/apache/commons/lang/AllLangTestSuite.java
/* * Copyright 2002-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.commons.lang.builder.BuilderTestSuite; import org.apache.commons.lang.enums.EnumTestSuite; import org.apache.commons.lang.exception.ExceptionTestSuite; import org.apache.commons.lang.math.MathTestSuite; import org.apache.commons.lang.mutable.MutableTestSuite; //import org.apache.commons.lang.text.TextTestSuite; import org.apache.commons.lang.time.TimeTestSuite; /** * Test suite for [lang]. * * @author Stephen Colebourne * @version $Id$ */ public class AllLangTestSuite extends TestCase { /** * Construct a new instance. */ public AllLangTestSuite(String name) { super(name); } /** * Command-line interface. */ public static void main(String[] args) { TestRunner.run(suite()); } /** * Get the suite of tests */ public static Test suite() { TestSuite suite = new TestSuite(); suite.setName("Commons-Lang (all) Tests"); suite.addTest(LangTestSuite.suite()); suite.addTest(BuilderTestSuite.suite()); suite.addTest(EnumTestSuite.suite()); suite.addTest(org.apache.commons.lang.enum.EnumTestSuite.suite()); suite.addTest(ExceptionTestSuite.suite()); suite.addTest(MathTestSuite.suite()); suite.addTest(MutableTestSuite.suite()); // suite.addTest(TextTestSuite.suite()); suite.addTest(TimeTestSuite.suite()); return suite; } }
Add text package tests back into commons-lang git-svn-id: d201ecbade8cc7da50e7bffa1d709f7a0d92be7d@219114 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/commons/lang/AllLangTestSuite.java
Add text package tests back into commons-lang
<ide><path>rc/test/org/apache/commons/lang/AllLangTestSuite.java <ide> import org.apache.commons.lang.exception.ExceptionTestSuite; <ide> import org.apache.commons.lang.math.MathTestSuite; <ide> import org.apache.commons.lang.mutable.MutableTestSuite; <del>//import org.apache.commons.lang.text.TextTestSuite; <add>import org.apache.commons.lang.text.TextTestSuite; <ide> import org.apache.commons.lang.time.TimeTestSuite; <ide> <ide> /** <ide> suite.addTest(ExceptionTestSuite.suite()); <ide> suite.addTest(MathTestSuite.suite()); <ide> suite.addTest(MutableTestSuite.suite()); <del>// suite.addTest(TextTestSuite.suite()); <add> suite.addTest(TextTestSuite.suite()); <ide> suite.addTest(TimeTestSuite.suite()); <ide> return suite; <ide> }
JavaScript
unlicense
e203235a1730cc9a15f049ce5e94f9f266010f87
0
twolfson/google-music.js
// Load in dependencies var expect = require('chai').expect; var browserUtils = require('./utils/browser'); var browserMusicUtils = require('./utils/browser-music'); // Start our tests describe('A Google Music instance playing no music', function () { browserUtils.openMusic({ killBrowser: false, url: 'https://play.google.com/music/listen#/album//this-is-an-album-artist/this-is-an-album' }); // TODO: This behavior doesn't currently exist =( it.skip('has no artist/track info', function () { // Placeholder for linter }); describe('when we are playing music', function () { browserUtils.execute(function setupSongWatcher () { window.GoogleMusicApp = { notifySong: function saveSong (title, artist, album, art, duration) { window.song = { title: title, artist: artist, album: album, art: art, duration: duration }; } }; }); browserUtils.execute(function playViaApi () { window.MusicAPI.Playback.playPause(); }); browserMusicUtils.waitForPlaybackStart(); browserUtils.execute(function playViaApi () { return window.song; }); it('has the artist/track info', function () { expect(this.result).to.have.property('title', 'this-is-a-name'); expect(this.result).to.have.property('artist', 'this-is-a-artist'); expect(this.result).to.have.property('album', 'this-is-a-album'); expect(this.result).to.have.property('art'); expect(this.result.art).to.have.match(/^https?:\/\//); expect(this.result).to.have.property('duration'); expect(this.result.duration).to.be.a('number'); }); }); });
test/track-info.js
// Load in dependencies var expect = require('chai').expect; var browserUtils = require('./utils/browser'); var browserMusicUtils = require('./utils/browser-music'); // Start our tests describe('A Google Music instance playing no music', function () { browserUtils.openMusic({ killBrowser: false, url: 'https://play.google.com/music/listen#/album//this-is-an-album-artist/this-is-an-album' }); // TODO: This behavior doesn't currently exist =( it.skip('has no artist/track info', function () { // Placeholder for linter }); describe('when we are playing music', function () { browserUtils.execute(function setupPlaybackWatcher () { window.GoogleMusicApp = { playbackChanged: function saveSong (title, artist, album, art, duration) { window.song = { title: title, artist: artist, album: album, art: art, duration: duration }; } }; }); browserUtils.execute(function playViaApi () { window.MusicAPI.Playback.playPause(); }); browserMusicUtils.waitForPlaybackStart(); browserUtils.execute(function playViaApi () { return window.song; }); it('has the artist/track info', function () { expect(this.song).to.have.property('title', 'this-is-a-title'); expect(this.song).to.have.property('artist', 'this-is-a-artist'); expect(this.song).to.have.property('album', 'this-is-a-album'); expect(this.song).to.have.property('art'); expect(this.song.art).to.have.match(/^https?:\/\//); expect(this.song).to.have.property('duration'); expect(this.song.duration).to.be.a('number'); }); }); });
Fixed up test to green
test/track-info.js
Fixed up test to green
<ide><path>est/track-info.js <ide> }); <ide> <ide> describe('when we are playing music', function () { <del> browserUtils.execute(function setupPlaybackWatcher () { <add> browserUtils.execute(function setupSongWatcher () { <ide> window.GoogleMusicApp = { <del> playbackChanged: function saveSong (title, artist, album, art, duration) { <add> notifySong: function saveSong (title, artist, album, art, duration) { <ide> window.song = { <ide> title: title, <ide> artist: artist, <ide> }); <ide> <ide> it('has the artist/track info', function () { <del> expect(this.song).to.have.property('title', 'this-is-a-title'); <del> expect(this.song).to.have.property('artist', 'this-is-a-artist'); <del> expect(this.song).to.have.property('album', 'this-is-a-album'); <del> expect(this.song).to.have.property('art'); <del> expect(this.song.art).to.have.match(/^https?:\/\//); <del> expect(this.song).to.have.property('duration'); <del> expect(this.song.duration).to.be.a('number'); <add> expect(this.result).to.have.property('title', 'this-is-a-name'); <add> expect(this.result).to.have.property('artist', 'this-is-a-artist'); <add> expect(this.result).to.have.property('album', 'this-is-a-album'); <add> expect(this.result).to.have.property('art'); <add> expect(this.result.art).to.have.match(/^https?:\/\//); <add> expect(this.result).to.have.property('duration'); <add> expect(this.result.duration).to.be.a('number'); <ide> }); <ide> }); <ide> });
Java
apache-2.0
d3256db8e842c0f9dd0d5e838552fc5e80706836
0
Erudika/para,Erudika/para
/* * Copyright 2013-2022 Erudika. https://erudika.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.core.utils; import com.erudika.para.core.annotations.Documented; import com.fasterxml.jackson.core.JsonProcessingException; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigValue; import com.typesafe.config.ConfigValueFactory; import com.typesafe.config.ConfigValueType; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.nio.file.Paths; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class loads configuration settings from a file and sets defaults. * @author Alex Bogdanovski [[email protected]] */ public abstract class Config { private static final Logger logger = LoggerFactory.getLogger(Config.class); private com.typesafe.config.Config config; private Map<String, String> sortedConfigKeys; // config key => category private List<Documented> annotatedMethods; // GLOBAL SETTINGS /** {@value #PARA}. */ public static final String PARA = "para"; /** {@value #_TYPE}. */ public static final String _TYPE = "type"; /** {@value #_APPID}. */ public static final String _APPID = "appid"; /** {@value #_CREATORID}. */ public static final String _CREATORID = "creatorid"; /** {@value #_ID}. */ public static final String _ID = "id"; /** {@value #_IDENTIFIER}. */ public static final String _IDENTIFIER = "identifier"; /** {@value #_KEY}. */ public static final String _KEY = "key"; /** {@value #_NAME}. */ public static final String _NAME = "name"; /** {@value #_PARENTID}. */ public static final String _PARENTID = "parentid"; /** {@value #_PASSWORD}. */ public static final String _PASSWORD = "password"; /** {@value #_RESET_TOKEN}. */ public static final String _RESET_TOKEN = "token"; /** {@value #_EMAIL_TOKEN}. */ public static final String _EMAIL_TOKEN = "etoken"; /** {@value #_TIMESTAMP}. */ public static final String _TIMESTAMP = "timestamp"; /** {@value #_UPDATED}. */ public static final String _UPDATED = "updated"; /** {@value #_TAGS}. */ public static final String _TAGS = "tags"; /** {@value #_EMAIL}. */ public static final String _EMAIL = "email"; /** {@value #_GROUPS}. */ public static final String _GROUPS = "groups"; /** {@value #_VERSION}. */ public static final String _VERSION = "version"; /** {@value #_PROPERTIES}. */ public static final String _PROPERTIES = "properties"; /** * USER IDENTIFIER PREFIXES */ /** {@value #DEFAULT_LIMIT}. */ public static final int DEFAULT_LIMIT = 10000; /** Facebook prefix - defaults to 'fb:'. */ public static final String FB_PREFIX = "fb:"; /** Google prefix - defaults to 'gp:'. */ public static final String GPLUS_PREFIX = "gp:"; /** LinkedIn prefix - defaults to 'in:'. */ public static final String LINKEDIN_PREFIX = "in:"; /** Twitter prefix - defaults to 'tw:'. */ public static final String TWITTER_PREFIX = "tw:"; /** GitHub prefix - defaults to 'gh:'. */ public static final String GITHUB_PREFIX = "gh:"; /** Microsoft prefix - defaults to 'ms:'. */ public static final String MICROSOFT_PREFIX = "ms:"; /** Slack prefix - defaults to 'sl:'. */ public static final String SLACK_PREFIX = "sl:"; /** Mattermost prefix - defaults to 'mm:'. */ public static final String MATTERMOST_PREFIX = "mm:"; /** Amazon prefix - defaults to 'az:'. */ public static final String AMAZON_PREFIX = "az:"; /** OAuth2 generic prefix - defaults to 'oa2:'. */ public static final String OAUTH2_PREFIX = "oa2:"; /** OAuth2 second generic prefix - defaults to 'oa2second:'. */ public static final String OAUTH2_SECOND_PREFIX = "oa2second:"; /** OAuth2 third generic prefix - defaults to 'oa2third:'. */ public static final String OAUTH2_THIRD_PREFIX = "oa2third:"; /** LDAP prefix - defaults to 'ldap:'. */ public static final String LDAP_PREFIX = "ldap:"; /** SAML prefix - defaults to 'saml:'. */ public static final String SAML_PREFIX = "saml:"; /** * The root prefix of the configuration property names, e.g. "para". * @return the root prefix for all config property keys. */ public abstract String getConfigRootPrefix(); /** * The fallback configuration, which will be used if the default cannot be loaded. * @return a config object, defaults to {@link com.typesafe.config.ConfigFactory#empty()}. */ protected com.typesafe.config.Config getFallbackConfig() { return com.typesafe.config.ConfigFactory.empty(); } /** * A set of keys to exclude from the rendered config string. * @return a set of keys */ protected Set<String> getKeysExcludedFromRendering() { return Collections.emptySet(); } /** * Header string to append to the start of the rendered config. * @return any string */ protected String getRenderedHeader() { return ""; } /** * Footer string to append to the end of the rendered config. * @return any string */ protected String getRenderedFooter() { return ""; } /** * Initializes the configuration class by loading the configuration file. * @param conf overrides the default configuration */ protected final void init(com.typesafe.config.Config conf) { try { config = ConfigFactory.load().getConfig(getConfigRootPrefix()).withFallback(getFallbackConfig()); if (conf != null) { config = conf.withFallback(config); } getSortedConfigKeys(); } catch (Exception ex) { logger.warn("Failed to load configuration file 'application.(conf|json|properties)' for namespace '{}' - {}", getConfigRootPrefix(), ex.getMessage()); config = getFallbackConfig(); } } /** * Returns the boolean value of a configuration parameter. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public boolean getConfigBoolean(String key, boolean defaultValue) { return Boolean.parseBoolean(getConfigParam(key, Boolean.toString(defaultValue))); } /** * Returns the integer value of a configuration parameter. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public int getConfigInt(String key, int defaultValue) { return NumberUtils.toInt(getConfigParam(key, Integer.toString(defaultValue))); } /** * Returns the double value of a configuration parameter. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public double getConfigDouble(String key, double defaultValue) { return NumberUtils.toDouble(getConfigParam(key, Double.toString(defaultValue))); } /** * Returns the value of a configuration parameter or its default value. * {@link System#getProperty(java.lang.String)} has precedence. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public String getConfigParam(String key, String defaultValue) { if (config == null) { init(null); } if (StringUtils.isBlank(key)) { return defaultValue; } String keyVar = key.replaceAll("\\.", "_"); String env = System.getenv(keyVar) == null ? System.getenv(getConfigRootPrefix() + "_" + keyVar) : System.getenv(keyVar); String sys = System.getProperty(key, System.getProperty(getConfigRootPrefix() + "." + key)); if (!StringUtils.isBlank(sys)) { return sys; } else if (!StringUtils.isBlank(env)) { return env; } else { return (!StringUtils.isBlank(key) && config.hasPath(key)) ? config.getAnyRef(key).toString() : defaultValue; } } /** * @see #getConfigParam(java.lang.String, java.lang.String) * @param key key * @param defaultValue value * @param type type * @return object */ public Object getConfigParam(String key, String defaultValue, ConfigValueType type) { try { switch (type) { case STRING: return getConfigParam(key, defaultValue); case BOOLEAN: return Boolean.parseBoolean(getConfigParam(key, defaultValue)); case NUMBER: return NumberFormat.getInstance().parse(getConfigParam(key, defaultValue)); case LIST: String arr = getConfigParam(key, defaultValue); arr = StringUtils.remove(arr, "]"); arr = StringUtils.remove(arr, "["); arr = StringUtils.remove(arr, "\""); arr = StringUtils.remove(arr, "\""); List<Object> list = new ArrayList<>(); for (String str : arr.split("\\s,\\s")) { if (NumberUtils.isParsable(str)) { list.add(NumberFormat.getInstance().parse(str)); } else { list.add(str); } } return list; default: return getConfigParam(key, defaultValue); //case OBJECT: } } catch (Exception ex) { logger.error(null, ex); } return getConfigParam(key, defaultValue); } /** * Returns the Config object. * @return the config object */ public com.typesafe.config.Config getConfig() { if (config == null) { init(null); } return config; } /** * Constructs a sorted set of configuration keys. * Heavily relies on the {@link Documented} annotation for sort order. * @return a set of map of config keys, without the root prefix (path), to config categories. */ public Map<String, String> getSortedConfigKeys() { if (sortedConfigKeys == null || sortedConfigKeys.isEmpty()) { annotatedMethods = Arrays.stream(this.getClass().getMethods()). filter(m -> m.isAnnotationPresent(Documented.class)). map(m -> m.getAnnotation(Documented.class)). filter(m -> !StringUtils.isBlank(m.identifier())). sorted((a1, a2) -> Integer.compare(a1.position(), a2.position())). collect(Collectors.toList()); sortedConfigKeys = annotatedMethods.stream(). collect(Collectors.toMap(a -> a.identifier(), a -> a.category(), (u, v) -> u, LinkedHashMap::new)); } return sortedConfigKeys; } /** * Stores all available configuration to a file, overwriting the existing one. * In case of HOCON, the commented lines are collected from existing file and * appended at the end. */ public void store() { if (!getConfigBoolean("store_config_locally", true)) { return; } String confFile = Paths.get(System.getProperty("config.file", "application.conf")).toAbsolutePath().toString(); boolean isJsonFile = confFile.equalsIgnoreCase(".json"); File conf = new File(confFile); if (!conf.exists() || conf.canWrite()) { try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(conf)); ByteArrayInputStream data = new ByteArrayInputStream( render(isJsonFile, getRenderedHeader(), getRenderedFooter()).getBytes("utf-8"))) { int read; byte[] bytes = new byte[1024]; while ((read = data.read(bytes)) != -1) { bos.write(bytes, 0, read); } logger.info("Configuration stored successfully in {}", confFile); } catch (Exception e) { logger.error(null, e); } } else { logger.warn("Failed to write configuration file {} to disk - check permissions.", confFile); } } /** * @see #render(boolean, java.lang.String, java.lang.String) * @param asJson if true, a JSON object will be rendered, otherwise the HOCON format is used * @return config as string */ public String render(boolean asJson) { return render(asJson, "", ""); } /** * * Renders the current configuration as a String, taking into account system properties and ENV precedence ordering. * @param asJson if true, a JSON object will be rendered, otherwise the HOCON format is used * @param hoconHeader file header * @param hoconFooter file footer * @return config as string */ public String render(boolean asJson, String hoconHeader, String hoconFooter) { Map<String, Object> configMap = new LinkedHashMap<>(); if (asJson) { for (String key : getSortedConfigKeys().keySet()) { configMap.put(getConfigRootPrefix() + "." + key, null); } for (Map.Entry<String, ConfigValue> entry : getConfig().entrySet()) { if (!getKeysExcludedFromRendering().contains(entry.getKey())) { configMap.put(getConfigRootPrefix() + "." + entry.getKey(), ConfigValueFactory. fromAnyRef(getConfigParam(entry.getKey(), "", entry.getValue().valueType())).unwrapped()); } } String conf = "{}"; try { conf = ParaObjectUtils.getJsonWriter().writeValueAsString(configMap); } catch (JsonProcessingException ex) { logger.error(null, ex); } return conf; } else { for (String key : getSortedConfigKeys().keySet()) { configMap.put(key, null); } for (Map.Entry<String, ConfigValue> entry : getConfig().entrySet()) { if (!getKeysExcludedFromRendering().contains(entry.getKey())) { configMap.put(entry.getKey(), ConfigValueFactory. fromAnyRef(getConfigParam(entry.getKey(), "", entry.getValue().valueType())). render(ConfigRenderOptions.concise().setComments(false).setOriginComments(false))); } } String category = ""; StringBuilder sb = new StringBuilder(hoconHeader); if (!StringUtils.endsWith(hoconHeader, "\n")) { sb.append("\n"); } for (Map.Entry<String, Object> entry : configMap.entrySet()) { if (entry.getValue() != null) { String cat = getSortedConfigKeys().get(entry.getKey()); if (!StringUtils.isBlank(cat) && !category.equalsIgnoreCase(cat)) { // print category header if (!category.isEmpty()) { sb.append("\n"); } category = getSortedConfigKeys().get(entry.getKey()); sb.append("############# ").append(category.toUpperCase()).append(" #############\n\n"); } sb.append(getConfigRootPrefix()).append(".").append(entry.getKey()). append(" = ").append(entry.getValue()).append("\n"); } } sb.append("\n").append(hoconFooter).append("\n"); return sb.toString(); } } public String renderConfigDocumentation(String format, boolean groupByCategory) { Map<String, Documented> configMap = annotatedMethods.stream(). collect(Collectors.toMap(a -> a.identifier(), a -> a, (u, v) -> u, LinkedHashMap::new)); String category = ""; StringBuilder sb = new StringBuilder(); Map<String, Map<String, Map<String, String>>> jsonMapByCat = new LinkedHashMap<>(); Map<String, Map<String, String>> jsonMap = new LinkedHashMap<>(); if (!groupByCategory && "markdown".equalsIgnoreCase(format)) { sb.append("| Property key & Description | Default Value | Type |\n"); sb.append("| --- | --- | --- |\n"); } for (Map.Entry<String, Documented> entry : configMap.entrySet()) { if (!getKeysExcludedFromRendering().contains(entry.getKey())) { if (groupByCategory) { category = renderCategoryHeader(format, category, entry, jsonMapByCat, sb); } renderConfigDescription(format, category, entry, jsonMapByCat, jsonMap, groupByCategory, sb); } } if (StringUtils.isBlank(format) || "json".equalsIgnoreCase(format)) { try { return ParaObjectUtils.getJsonWriter().writeValueAsString(jsonMapByCat); } catch (JsonProcessingException ex) { logger.error(null, ex); } } return sb.toString(); } private String renderCategoryHeader(String format, String category, Map.Entry<String, Documented> entry, Map<String, Map<String, Map<String, String>>> jsonMapByCat, StringBuilder sb) { String cat = getSortedConfigKeys().get(entry.getKey()); if (!StringUtils.isBlank(cat) && !category.equalsIgnoreCase(cat)) { category = getSortedConfigKeys().getOrDefault(entry.getKey(), ""); switch (StringUtils.trimToEmpty(format)) { case "markdown": if (!category.isEmpty()) { sb.append("\n"); } sb.append("## ").append(StringUtils.capitalize(category)).append("\n\n"); sb.append("| Property key & Description | Default Value | Type |\n"); sb.append("| --- | --- | --- |\n"); break; case "hocon": if (!category.isEmpty()) { sb.append("\n"); } sb.append("############# ").append(category.toUpperCase()).append(" #############\n\n"); break; default: jsonMapByCat.put(category, new LinkedHashMap<>()); } } return category; } private void renderConfigDescription(String format, String category, Map.Entry<String, Documented> entry, Map<String, Map<String, Map<String, String>>> jsonMapByCat, Map<String, Map<String, String>> jsonMap, boolean groupByCategory, StringBuilder sb) { switch (StringUtils.trimToEmpty(format)) { case "markdown": String tags = Arrays.stream(entry.getValue().tags()). map(t -> " <kbd>" + t + "</kbd>").collect(Collectors.joining()); sb.append("|`").append(getConfigRootPrefix()).append(".").append(entry.getKey()).append("`"). append(tags).append("<br>").append(entry.getValue().description()).append(" | `"). append(Optional.ofNullable(StringUtils.trimToNull(entry.getValue().value())).orElse(" ")). append("` | `").append(entry.getValue().type().getSimpleName()).append("`|\n"); break; case "hocon": sb.append("# ").append(entry.getValue().description()); sb.append("[type: ").append(entry.getValue().type().getSimpleName()).append("]\n"); sb.append(getConfigRootPrefix()).append(".").append(entry.getKey()).append(" = "). append(entry.getValue().value()).append("\n"); break; default: Map<String, String> description = new HashMap<String, String>(); description.put("description", entry.getValue().description()); description.put("defaultValue", entry.getValue().value()); description.put("type", entry.getValue().type().getSimpleName()); if (groupByCategory) { jsonMapByCat.get(category).put(getConfigRootPrefix() + "." + entry.getKey(), description); } else { jsonMap.put(getConfigRootPrefix() + "." + entry.getKey(), description); } } } }
para-core/src/main/java/com/erudika/para/core/utils/Config.java
/* * Copyright 2013-2022 Erudika. https://erudika.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For issues and patches go to: https://github.com/erudika */ package com.erudika.para.core.utils; import com.erudika.para.core.annotations.Documented; import com.fasterxml.jackson.core.JsonProcessingException; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigValue; import com.typesafe.config.ConfigValueFactory; import com.typesafe.config.ConfigValueType; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.nio.file.Paths; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class loads configuration settings from a file and sets defaults. * @author Alex Bogdanovski [[email protected]] */ public abstract class Config { private static final Logger logger = LoggerFactory.getLogger(Config.class); private com.typesafe.config.Config config; private Map<String, String> sortedConfigKeys; // config key => category private List<Documented> annotatedMethods; // GLOBAL SETTINGS /** {@value #PARA}. */ public static final String PARA = "para"; /** {@value #_TYPE}. */ public static final String _TYPE = "type"; /** {@value #_APPID}. */ public static final String _APPID = "appid"; /** {@value #_CREATORID}. */ public static final String _CREATORID = "creatorid"; /** {@value #_ID}. */ public static final String _ID = "id"; /** {@value #_IDENTIFIER}. */ public static final String _IDENTIFIER = "identifier"; /** {@value #_KEY}. */ public static final String _KEY = "key"; /** {@value #_NAME}. */ public static final String _NAME = "name"; /** {@value #_PARENTID}. */ public static final String _PARENTID = "parentid"; /** {@value #_PASSWORD}. */ public static final String _PASSWORD = "password"; /** {@value #_RESET_TOKEN}. */ public static final String _RESET_TOKEN = "token"; /** {@value #_EMAIL_TOKEN}. */ public static final String _EMAIL_TOKEN = "etoken"; /** {@value #_TIMESTAMP}. */ public static final String _TIMESTAMP = "timestamp"; /** {@value #_UPDATED}. */ public static final String _UPDATED = "updated"; /** {@value #_TAGS}. */ public static final String _TAGS = "tags"; /** {@value #_EMAIL}. */ public static final String _EMAIL = "email"; /** {@value #_GROUPS}. */ public static final String _GROUPS = "groups"; /** {@value #_VERSION}. */ public static final String _VERSION = "version"; /** {@value #_PROPERTIES}. */ public static final String _PROPERTIES = "properties"; /** * USER IDENTIFIER PREFIXES */ /** {@value #DEFAULT_LIMIT}. */ public static final int DEFAULT_LIMIT = 10000; /** Facebook prefix - defaults to 'fb:'. */ public static final String FB_PREFIX = "fb:"; /** Google prefix - defaults to 'gp:'. */ public static final String GPLUS_PREFIX = "gp:"; /** LinkedIn prefix - defaults to 'in:'. */ public static final String LINKEDIN_PREFIX = "in:"; /** Twitter prefix - defaults to 'tw:'. */ public static final String TWITTER_PREFIX = "tw:"; /** GitHub prefix - defaults to 'gh:'. */ public static final String GITHUB_PREFIX = "gh:"; /** Microsoft prefix - defaults to 'ms:'. */ public static final String MICROSOFT_PREFIX = "ms:"; /** Slack prefix - defaults to 'sl:'. */ public static final String SLACK_PREFIX = "sl:"; /** Mattermost prefix - defaults to 'mm:'. */ public static final String MATTERMOST_PREFIX = "mm:"; /** Amazon prefix - defaults to 'az:'. */ public static final String AMAZON_PREFIX = "az:"; /** OAuth2 generic prefix - defaults to 'oa2:'. */ public static final String OAUTH2_PREFIX = "oa2:"; /** OAuth2 second generic prefix - defaults to 'oa2second:'. */ public static final String OAUTH2_SECOND_PREFIX = "oa2second:"; /** OAuth2 third generic prefix - defaults to 'oa2third:'. */ public static final String OAUTH2_THIRD_PREFIX = "oa2third:"; /** LDAP prefix - defaults to 'ldap:'. */ public static final String LDAP_PREFIX = "ldap:"; /** SAML prefix - defaults to 'saml:'. */ public static final String SAML_PREFIX = "saml:"; /** * The root prefix of the configuration property names, e.g. "para". * @return the root prefix for all config property keys. */ public abstract String getConfigRootPrefix(); /** * The fallback configuration, which will be used if the default cannot be loaded. * @return a config object, defaults to {@link com.typesafe.config.ConfigFactory#empty()}. */ protected com.typesafe.config.Config getFallbackConfig() { return com.typesafe.config.ConfigFactory.empty(); } /** * A set of keys to exclude from the rendered config string. * @return a set of keys */ protected Set<String> getKeysExcludedFromRendering() { return Collections.emptySet(); } /** * Header string to append to the start of the rendered config. * @return any string */ protected String getRenderedHeader() { return ""; } /** * Footer string to append to the end of the rendered config. * @return any string */ protected String getRenderedFooter() { return ""; } /** * Initializes the configuration class by loading the configuration file. * @param conf overrides the default configuration */ protected final void init(com.typesafe.config.Config conf) { try { config = ConfigFactory.load().getConfig(getConfigRootPrefix()).withFallback(getFallbackConfig()); if (conf != null) { config = conf.withFallback(config); } getSortedConfigKeys(); } catch (Exception ex) { logger.warn("Failed to load configuration file 'application.(conf|json|properties)' for namespace '{}' - {}", getConfigRootPrefix(), ex.getMessage()); config = getFallbackConfig(); } } /** * Returns the boolean value of a configuration parameter. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public boolean getConfigBoolean(String key, boolean defaultValue) { return Boolean.parseBoolean(getConfigParam(key, Boolean.toString(defaultValue))); } /** * Returns the integer value of a configuration parameter. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public int getConfigInt(String key, int defaultValue) { return NumberUtils.toInt(getConfigParam(key, Integer.toString(defaultValue))); } /** * Returns the double value of a configuration parameter. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public double getConfigDouble(String key, double defaultValue) { return NumberUtils.toDouble(getConfigParam(key, Double.toString(defaultValue))); } /** * Returns the value of a configuration parameter or its default value. * {@link System#getProperty(java.lang.String)} has precedence. * @param key the param key * @param defaultValue the default param value * @return the value of a param */ public String getConfigParam(String key, String defaultValue) { if (config == null) { init(null); } if (StringUtils.isBlank(key)) { return defaultValue; } String keyVar = key.replaceAll("\\.", "_"); String env = System.getenv(keyVar) == null ? System.getenv(getConfigRootPrefix() + "_" + keyVar) : System.getenv(keyVar); String sys = System.getProperty(key, System.getProperty(getConfigRootPrefix() + "." + key)); if (!StringUtils.isBlank(sys)) { return sys; } else if (!StringUtils.isBlank(env)) { return env; } else { return (!StringUtils.isBlank(key) && config.hasPath(key)) ? config.getAnyRef(key).toString() : defaultValue; } } /** * @see #getConfigParam(java.lang.String, java.lang.String) * @param key key * @param defaultValue value * @param type type * @return object */ public Object getConfigParam(String key, String defaultValue, ConfigValueType type) { try { switch (type) { case STRING: return getConfigParam(key, defaultValue); case BOOLEAN: return Boolean.parseBoolean(getConfigParam(key, defaultValue)); case NUMBER: return NumberFormat.getInstance().parse(getConfigParam(key, defaultValue)); case LIST: String arr = getConfigParam(key, defaultValue); arr = StringUtils.remove(arr, "]"); arr = StringUtils.remove(arr, "["); arr = StringUtils.remove(arr, "\""); arr = StringUtils.remove(arr, "\""); List<Object> list = new ArrayList<>(); for (String str : arr.split("\\s,\\s")) { if (NumberUtils.isParsable(str)) { list.add(NumberFormat.getInstance().parse(str)); } else { list.add(str); } } return list; default: return getConfigParam(key, defaultValue); //case OBJECT: } } catch (Exception ex) { logger.error(null, ex); } return getConfigParam(key, defaultValue); } /** * Returns the Config object. * @return the config object */ public com.typesafe.config.Config getConfig() { if (config == null) { init(null); } return config; } /** * Constructs a sorted set of configuration keys. * Heavily relies on the {@link Documented} annotation for sort order. * @return a set of map of config keys, without the root prefix (path), to config categories. */ public Map<String, String> getSortedConfigKeys() { if (sortedConfigKeys == null || sortedConfigKeys.isEmpty()) { annotatedMethods = Arrays.stream(this.getClass().getMethods()). filter(m -> m.isAnnotationPresent(Documented.class)). map(m -> m.getAnnotation(Documented.class)). filter(m -> !StringUtils.isBlank(m.identifier())). sorted((a1, a2) -> Integer.compare(a1.position(), a2.position())). collect(Collectors.toList()); sortedConfigKeys = annotatedMethods.stream(). collect(Collectors.toMap(a -> a.identifier(), a -> a.category(), (u, v) -> u, LinkedHashMap::new)); } return sortedConfigKeys; } /** * Stores all available configuration to a file, overwriting the existing one. * In case of HOCON, the commented lines are collected from existing file and * appended at the end. */ public void store() { if (!getConfigBoolean("store_config_locally", true)) { return; } String confFile = Paths.get(System.getProperty("config.file", "application.conf")).toAbsolutePath().toString(); boolean isJsonFile = confFile.equalsIgnoreCase(".json"); File conf = new File(confFile); if (!conf.exists() || conf.canWrite()) { try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(conf)); ByteArrayInputStream data = new ByteArrayInputStream( render(isJsonFile, getRenderedHeader(), getRenderedFooter()).getBytes("utf-8"))) { int read; byte[] bytes = new byte[1024]; while ((read = data.read(bytes)) != -1) { bos.write(bytes, 0, read); } logger.info("Configuration stored successfully in {}", confFile); } catch (Exception e) { logger.error(null, e); } } else { logger.warn("Failed to write configuration file {} to disk - check permissions.", confFile); } } /** * @see #render(boolean, java.lang.String, java.lang.String) * @param asJson if true, a JSON object will be rendered, otherwise the HOCON format is used * @return config as string */ public String render(boolean asJson) { return render(asJson, "", ""); } /** * * Renders the current configuration as a String, taking into account system properties and ENV precedence ordering. * @param asJson if true, a JSON object will be rendered, otherwise the HOCON format is used * @param hoconHeader file header * @param hoconFooter file footer * @return config as string */ public String render(boolean asJson, String hoconHeader, String hoconFooter) { Map<String, Object> configMap = new LinkedHashMap<>(); if (asJson) { for (String key : getSortedConfigKeys().keySet()) { configMap.put(getConfigRootPrefix() + "." + key, null); } for (Map.Entry<String, ConfigValue> entry : getConfig().entrySet()) { if (!getKeysExcludedFromRendering().contains(entry.getKey())) { configMap.put(getConfigRootPrefix() + "." + entry.getKey(), ConfigValueFactory. fromAnyRef(getConfigParam(entry.getKey(), "", entry.getValue().valueType())).unwrapped()); } } String conf = "{}"; try { conf = ParaObjectUtils.getJsonWriter().writeValueAsString(configMap); } catch (JsonProcessingException ex) { logger.error(null, ex); } return conf; } else { for (String key : getSortedConfigKeys().keySet()) { configMap.put(key, null); } for (Map.Entry<String, ConfigValue> entry : getConfig().entrySet()) { if (!getKeysExcludedFromRendering().contains(entry.getKey())) { configMap.put(entry.getKey(), ConfigValueFactory. fromAnyRef(getConfigParam(entry.getKey(), "", entry.getValue().valueType())). render(ConfigRenderOptions.concise().setComments(false).setOriginComments(false))); } } String category = ""; StringBuilder sb = new StringBuilder(hoconHeader); if (!StringUtils.endsWith(hoconHeader, "\n")) { sb.append("\n"); } for (Map.Entry<String, Object> entry : configMap.entrySet()) { if (entry.getValue() != null) { String cat = getSortedConfigKeys().get(entry.getKey()); if (!StringUtils.isBlank(cat) && !category.equalsIgnoreCase(cat)) { // print category header if (!category.isEmpty()) { sb.append("\n"); } category = getSortedConfigKeys().get(entry.getKey()); sb.append("############# ").append(category.toUpperCase()).append(" #############\n\n"); } sb.append(getConfigRootPrefix()).append(".").append(entry.getKey()). append(" = ").append(entry.getValue()).append("\n"); } } sb.append("\n").append(hoconFooter).append("\n"); return sb.toString(); } } public String renderConfigDocumentation(String format, boolean groupByCategory) { Map<String, Documented> configMap = annotatedMethods.stream(). collect(Collectors.toMap(a -> a.identifier(), a -> a, (u, v) -> u, LinkedHashMap::new)); String category = ""; StringBuilder sb = new StringBuilder(); Map<String, Map<String, Map<String, String>>> jsonMapByCat = new LinkedHashMap<>(); Map<String, Map<String, String>> jsonMap = new LinkedHashMap<>(); if (!groupByCategory && "markdown".equalsIgnoreCase(format)) { sb.append("| Property key | Description | Default value | Type |\n"); sb.append("| --- | --- | --- | --- |\n"); } for (Map.Entry<String, Documented> entry : configMap.entrySet()) { if (!getKeysExcludedFromRendering().contains(entry.getKey())) { if (groupByCategory) { renderCategoryHeader(format, category, entry, jsonMapByCat, sb); } renderConfigDescription(format, category, entry, jsonMapByCat, jsonMap, groupByCategory, sb); } } if (StringUtils.isBlank(format) || "json".equalsIgnoreCase(format)) { try { return ParaObjectUtils.getJsonWriter().writeValueAsString(jsonMapByCat); } catch (JsonProcessingException ex) { logger.error(null, ex); } } return sb.toString(); } private void renderCategoryHeader(String format, String category, Map.Entry<String, Documented> entry, Map<String, Map<String, Map<String, String>>> jsonMapByCat, StringBuilder sb) { String cat = getSortedConfigKeys().get(entry.getKey()); if (!StringUtils.isBlank(cat) && !category.equalsIgnoreCase(cat)) { category = getSortedConfigKeys().get(entry.getKey()); switch (format) { case "markdown": if (!category.isEmpty()) { sb.append("\n"); } sb.append("## ").append(StringUtils.capitalize(category)).append("\n\n"); sb.append("| Property key | Description | Default value | Type |\n"); sb.append("| --- | --- | --- | --- |\n"); break; case "hocon": if (!category.isEmpty()) { sb.append("\n"); } sb.append("############# ").append(category.toUpperCase()).append(" #############\n\n"); break; default: jsonMapByCat.put(category, new LinkedHashMap<>()); } } } private void renderConfigDescription(String format, String category, Map.Entry<String, Documented> entry, Map<String, Map<String, Map<String, String>>> jsonMapByCat, Map<String, Map<String, String>> jsonMap, boolean groupByCategory, StringBuilder sb) { switch (format) { case "markdown": sb.append("|`").append(getConfigRootPrefix()).append(".").append(entry.getKey()).append("` | "). append(entry.getValue().description()).append(" | `"). append(entry.getValue().value()).append("` | `"). append(entry.getValue().type().getSimpleName()).append("`|\n"); break; case "hocon": sb.append("# ").append(entry.getValue().description()); sb.append("[type: ").append(entry.getValue().type().getSimpleName()).append("]\n"); sb.append(getConfigRootPrefix()).append(".").append(entry.getKey()).append(" = "). append(entry.getValue().value()).append("\n"); break; default: Map<String, String> description = new HashMap<String, String>(); description.put("description", entry.getValue().description()); description.put("defaultValue", entry.getValue().value()); description.put("type", entry.getValue().type().getSimpleName()); if (groupByCategory) { jsonMapByCat.get(category).put(getConfigRootPrefix() + "." + entry.getKey(), description); } else { jsonMap.put(getConfigRootPrefix() + "." + entry.getKey(), description); } } } }
fixed configuration rendenring methods
para-core/src/main/java/com/erudika/para/core/utils/Config.java
fixed configuration rendenring methods
<ide><path>ara-core/src/main/java/com/erudika/para/core/utils/Config.java <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Optional; <ide> import java.util.Set; <ide> import java.util.stream.Collectors; <ide> import org.apache.commons.lang3.StringUtils; <ide> Map<String, Map<String, String>> jsonMap = new LinkedHashMap<>(); <ide> <ide> if (!groupByCategory && "markdown".equalsIgnoreCase(format)) { <del> sb.append("| Property key | Description | Default value | Type |\n"); <del> sb.append("| --- | --- | --- | --- |\n"); <add> sb.append("| Property key & Description | Default Value | Type |\n"); <add> sb.append("| --- | --- | --- |\n"); <ide> } <ide> <ide> for (Map.Entry<String, Documented> entry : configMap.entrySet()) { <ide> if (!getKeysExcludedFromRendering().contains(entry.getKey())) { <ide> if (groupByCategory) { <del> renderCategoryHeader(format, category, entry, jsonMapByCat, sb); <add> category = renderCategoryHeader(format, category, entry, jsonMapByCat, sb); <ide> } <ide> renderConfigDescription(format, category, entry, jsonMapByCat, jsonMap, groupByCategory, sb); <ide> } <ide> return sb.toString(); <ide> } <ide> <del> private void renderCategoryHeader(String format, String category, Map.Entry<String, Documented> entry, <add> private String renderCategoryHeader(String format, String category, Map.Entry<String, Documented> entry, <ide> Map<String, Map<String, Map<String, String>>> jsonMapByCat, StringBuilder sb) { <ide> String cat = getSortedConfigKeys().get(entry.getKey()); <ide> if (!StringUtils.isBlank(cat) && !category.equalsIgnoreCase(cat)) { <del> category = getSortedConfigKeys().get(entry.getKey()); <del> switch (format) { <add> category = getSortedConfigKeys().getOrDefault(entry.getKey(), ""); <add> switch (StringUtils.trimToEmpty(format)) { <ide> case "markdown": <ide> if (!category.isEmpty()) { <ide> sb.append("\n"); <ide> } <ide> sb.append("## ").append(StringUtils.capitalize(category)).append("\n\n"); <del> sb.append("| Property key | Description | Default value | Type |\n"); <del> sb.append("| --- | --- | --- | --- |\n"); <add> sb.append("| Property key & Description | Default Value | Type |\n"); <add> sb.append("| --- | --- | --- |\n"); <ide> break; <ide> case "hocon": <ide> if (!category.isEmpty()) { <ide> jsonMapByCat.put(category, new LinkedHashMap<>()); <ide> } <ide> } <add> return category; <ide> } <ide> <ide> private void renderConfigDescription(String format, String category, Map.Entry<String, Documented> entry, <ide> Map<String, Map<String, Map<String, String>>> jsonMapByCat, Map<String, Map<String, String>> jsonMap, <ide> boolean groupByCategory, StringBuilder sb) { <del> switch (format) { <add> switch (StringUtils.trimToEmpty(format)) { <ide> case "markdown": <del> sb.append("|`").append(getConfigRootPrefix()).append(".").append(entry.getKey()).append("` | "). <del> append(entry.getValue().description()).append(" | `"). <del> append(entry.getValue().value()).append("` | `"). <del> append(entry.getValue().type().getSimpleName()).append("`|\n"); <add> String tags = Arrays.stream(entry.getValue().tags()). <add> map(t -> " <kbd>" + t + "</kbd>").collect(Collectors.joining()); <add> sb.append("|`").append(getConfigRootPrefix()).append(".").append(entry.getKey()).append("`"). <add> append(tags).append("<br>").append(entry.getValue().description()).append(" | `"). <add> append(Optional.ofNullable(StringUtils.trimToNull(entry.getValue().value())).orElse(" ")). <add> append("` | `").append(entry.getValue().type().getSimpleName()).append("`|\n"); <ide> break; <ide> case "hocon": <ide> sb.append("# ").append(entry.getValue().description());
Java
apache-2.0
52288b2be4ef4127782b6d634286bc7b24ef425b
0
airlift/aircompressor,dain/aircompressor
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.airlift.compress; import com.facebook.presto.hadoop.HadoopNative; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionOutputStream; import org.apache.hadoop.io.compress.SnappyCodec; import org.openjdk.jmh.annotations.AuxCounters; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.util.Statistics; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.TimeUnit; @State(Scope.Thread) @OutputTimeUnit(TimeUnit.SECONDS) @Measurement(iterations = 10) @Warmup(iterations = 5) @Fork(3) public class DecompressBenchmark { static { PrintStream err = System.err; try { System.setErr(new PrintStream(ByteStreams.nullOutputStream())); HadoopNative.requireHadoopNative(); } finally { System.setErr(err); } } private static final Configuration HADOOP_CONF = new Configuration(); private byte[] data; private byte[] uncompressedBytes; private HadoopSnappyCodec airliftSnappyCodec; private SnappyCodec hadoopSnappyCodec; private byte[] blockCompressedSnappy; private byte[] streamCompressedAirliftSnappy; private byte[] streamCompressedHadoopSnappy; @Setup public void prepare() throws IOException { data = getUncompressedData(); uncompressedBytes = new byte[data.length]; blockCompressedSnappy = compressBlockSnappy(data); airliftSnappyCodec = new HadoopSnappyCodec(); streamCompressedAirliftSnappy = compressHadoopStream(airliftSnappyCodec, data, 0, data.length); hadoopSnappyCodec = new SnappyCodec(); hadoopSnappyCodec.setConf(HADOOP_CONF); streamCompressedHadoopSnappy = compressHadoopStream(hadoopSnappyCodec, data, 0, data.length); } /** * DO NOT call this from prepare! * Verify the implementations are working. This executes all implementation code, * which can cause some implementations (e.g. Hadoop) to become highly virtualized * and thus slow. */ public void verify() throws IOException { Arrays.fill(uncompressedBytes, (byte) 0); blockAirliftSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } Arrays.fill(uncompressedBytes, (byte) 0); blockXerialSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } Arrays.fill(uncompressedBytes, (byte) 0); streamAirliftSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } Arrays.fill(uncompressedBytes, (byte) 0); streamHadoopSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } } private static byte[] getUncompressedData() throws IOException { return Files.toByteArray(new File("testdata/html")); } @Benchmark public int blockAirliftSnappy(BytesCounter counter) { int read = Snappy.uncompress(blockCompressedSnappy, 0, blockCompressedSnappy.length, uncompressedBytes, 0); counter.add(uncompressedBytes.length); return read; } @Benchmark public int blockXerialSnappy(BytesCounter counter) throws IOException { int read = org.xerial.snappy.Snappy.uncompress(blockCompressedSnappy, 0, blockCompressedSnappy.length, uncompressedBytes, 0); counter.add(uncompressedBytes.length); return read; } @Benchmark public int streamAirliftSnappy(BytesCounter counter) throws IOException { return streamHadoop(counter, airliftSnappyCodec, streamCompressedAirliftSnappy); } @Benchmark public int streamHadoopSnappy(BytesCounter counter) throws IOException { return streamHadoop(counter, hadoopSnappyCodec, streamCompressedHadoopSnappy); } private int streamHadoop(BytesCounter counter, CompressionCodec codec, byte[] compressed) throws IOException { InputStream in = codec.createInputStream(new ByteArrayInputStream(compressed)); int decompressedOffset = 0; while (decompressedOffset < uncompressedBytes.length) { decompressedOffset += in.read(uncompressedBytes, decompressedOffset, uncompressedBytes.length - decompressedOffset); } counter.add(uncompressedBytes.length); return decompressedOffset; } @AuxCounters @State(Scope.Thread) public static class BytesCounter { private long bytes; @Setup(Level.Iteration) public void reset() { bytes = 0; } public void add(long bytes) { this.bytes += bytes; } public long getBytes() { return bytes; } } public static void main(String[] args) throws Exception { DecompressBenchmark verifyDecompressor = new DecompressBenchmark(); verifyDecompressor.prepare(); verifyDecompressor.verify(); Options opt = new OptionsBuilder() // .outputFormat(OutputFormatType.Silent) .include(".*" + DecompressBenchmark.class.getSimpleName() + ".*") // .forks(1) // .warmupIterations(5) // .measurementIterations(10) .build(); Collection<RunResult> results = new Runner(opt).run(); for (RunResult result : results) { Statistics stats = result.getSecondaryResults().get("getBytes").getStatistics(); System.out.printf(" %-14s %10s ± %10s (%5.2f%%) (N = %d, \u03B1 = 99.9%%)\n", result.getPrimaryResult().getLabel(), Util.toHumanReadableSpeed((long) stats.getMean()), Util.toHumanReadableSpeed((long) stats.getMeanErrorAt(0.999)), stats.getMeanErrorAt(0.999) * 100 / stats.getMean(), stats.getN()); } System.out.println(); } private static byte[] compressBlockSnappy(byte[] uncompressed) throws IOException { return Snappy.compress(uncompressed); } private static byte[] compressHadoopStream(CompressionCodec codec, byte[] uncompressed, int offset, int length) throws IOException { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); CompressionOutputStream out = codec.createOutputStream(buffer); ByteStreams.copy(new ByteArrayInputStream(uncompressed, offset, length), out); out.close(); return buffer.toByteArray(); } }
src/test/java/io/airlift/compress/DecompressBenchmark.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.airlift.compress; import com.facebook.presto.hadoop.HadoopNative; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionOutputStream; import org.apache.hadoop.io.compress.SnappyCodec; import org.openjdk.jmh.annotations.AuxCounters; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.util.Statistics; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.TimeUnit; @State(Scope.Thread) @OutputTimeUnit(TimeUnit.SECONDS) @Measurement(iterations = 10) @Warmup(iterations = 5) @Fork(3) public class DecompressBenchmark { static { PrintStream err = System.err; try { System.setErr(new PrintStream(ByteStreams.nullOutputStream())); HadoopNative.requireHadoopNative(); } finally { System.setErr(err); } } private static final Configuration HADOOP_CONF = new Configuration(); private byte[] data; private byte[] uncompressedBytes; private HadoopSnappyCodec airliftSnappyCodec; private SnappyCodec hadoopSnappyCodec; private byte[] blockCompressedSnappy; private byte[] streamCompressedAirliftSnappy; private byte[] streamCompressedHadoopSnappy; @Setup public void prepare() throws IOException { data = getUncompressedData(); uncompressedBytes = new byte[data.length]; blockCompressedSnappy = compressBlockSnappy(data); Arrays.fill(uncompressedBytes, (byte) 0); blockAirliftSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } Arrays.fill(uncompressedBytes, (byte) 0); blockXerialSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } airliftSnappyCodec = new HadoopSnappyCodec(); streamCompressedAirliftSnappy = compressHadoopStream(airliftSnappyCodec, data, 0, data.length); Arrays.fill(uncompressedBytes, (byte) 0); streamAirliftSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } hadoopSnappyCodec = new SnappyCodec(); hadoopSnappyCodec.setConf(HADOOP_CONF); streamCompressedHadoopSnappy = compressHadoopStream(hadoopSnappyCodec, data, 0, data.length); Arrays.fill(uncompressedBytes, (byte) 0); streamHadoopSnappy(new BytesCounter()); if (!Arrays.equals(data, uncompressedBytes)) { throw new IllegalStateException("broken decompressor"); } } private static byte[] getUncompressedData() throws IOException { return Files.toByteArray(new File("testdata/html")); } @Benchmark public int blockAirliftSnappy(BytesCounter counter) { int read = Snappy.uncompress(blockCompressedSnappy, 0, blockCompressedSnappy.length, uncompressedBytes, 0); counter.add(uncompressedBytes.length); return read; } @Benchmark public int blockXerialSnappy(BytesCounter counter) throws IOException { int read = org.xerial.snappy.Snappy.uncompress(blockCompressedSnappy, 0, blockCompressedSnappy.length, uncompressedBytes, 0); counter.add(uncompressedBytes.length); return read; } @Benchmark public int streamAirliftSnappy(BytesCounter counter) throws IOException { InputStream in = airliftSnappyCodec.createInputStream(new ByteArrayInputStream(streamCompressedAirliftSnappy)); int decompressedOffset = 0; while (decompressedOffset < uncompressedBytes.length) { decompressedOffset += in.read(uncompressedBytes, decompressedOffset, uncompressedBytes.length - decompressedOffset); } counter.add(uncompressedBytes.length); return decompressedOffset; } @Benchmark public int streamHadoopSnappy(BytesCounter counter) throws IOException { InputStream in = hadoopSnappyCodec.createInputStream(new ByteArrayInputStream(streamCompressedHadoopSnappy)); int decompressedOffset = 0; while (decompressedOffset < uncompressedBytes.length) { decompressedOffset += in.read(uncompressedBytes, decompressedOffset, uncompressedBytes.length - decompressedOffset); } counter.add(uncompressedBytes.length); return decompressedOffset; } @AuxCounters @State(Scope.Thread) public static class BytesCounter { private long bytes; @Setup(Level.Iteration) public void reset() { bytes = 0; } public void add(long bytes) { this.bytes += bytes; } public long getBytes() { return bytes; } } public static void main(String[] args) throws Exception { new DecompressBenchmark().prepare(); Options opt = new OptionsBuilder() // .outputFormat(OutputFormatType.Silent) .include(".*" + DecompressBenchmark.class.getSimpleName() + ".*") // .forks(1) // .warmupIterations(5) // .measurementIterations(10) .build(); Collection<RunResult> results = new Runner(opt).run(); for (RunResult result : results) { Statistics stats = result.getSecondaryResults().get("getBytes").getStatistics(); System.out.printf(" %-14s %10s ± %10s (%5.2f%%) (N = %d, \u03B1 = 99.9%%)\n", result.getPrimaryResult().getLabel(), Util.toHumanReadableSpeed((long) stats.getMean()), Util.toHumanReadableSpeed((long) stats.getMeanErrorAt(0.999)), stats.getMeanErrorAt(0.999) * 100 / stats.getMean(), stats.getN()); } System.out.println(); } private static byte[] compressBlockSnappy(byte[] uncompressed) throws IOException { return Snappy.compress(uncompressed); } private static byte[] compressHadoopStream(CompressionCodec codec, byte[] uncompressed, int offset, int length) throws IOException { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); CompressionOutputStream out = codec.createOutputStream(buffer); ByteStreams.copy(new ByteArrayInputStream(uncompressed, offset, length), out); out.close(); return buffer.toByteArray(); } }
Separate benchmark verify from prepare
src/test/java/io/airlift/compress/DecompressBenchmark.java
Separate benchmark verify from prepare
<ide><path>rc/test/java/io/airlift/compress/DecompressBenchmark.java <ide> <ide> blockCompressedSnappy = compressBlockSnappy(data); <ide> <del> Arrays.fill(uncompressedBytes, (byte) 0); <del> blockAirliftSnappy(new BytesCounter()); <del> if (!Arrays.equals(data, uncompressedBytes)) { <del> throw new IllegalStateException("broken decompressor"); <del> } <del> <del> Arrays.fill(uncompressedBytes, (byte) 0); <del> blockXerialSnappy(new BytesCounter()); <del> if (!Arrays.equals(data, uncompressedBytes)) { <del> throw new IllegalStateException("broken decompressor"); <del> } <del> <ide> airliftSnappyCodec = new HadoopSnappyCodec(); <ide> streamCompressedAirliftSnappy = compressHadoopStream(airliftSnappyCodec, data, 0, data.length); <del> Arrays.fill(uncompressedBytes, (byte) 0); <del> streamAirliftSnappy(new BytesCounter()); <del> if (!Arrays.equals(data, uncompressedBytes)) { <del> throw new IllegalStateException("broken decompressor"); <del> } <ide> <ide> hadoopSnappyCodec = new SnappyCodec(); <ide> hadoopSnappyCodec.setConf(HADOOP_CONF); <ide> streamCompressedHadoopSnappy = compressHadoopStream(hadoopSnappyCodec, data, 0, data.length); <add> } <add> <add> /** <add> * DO NOT call this from prepare! <add> * Verify the implementations are working. This executes all implementation code, <add> * which can cause some implementations (e.g. Hadoop) to become highly virtualized <add> * and thus slow. <add> */ <add> public void verify() <add> throws IOException <add> { <add> Arrays.fill(uncompressedBytes, (byte) 0); <add> blockAirliftSnappy(new BytesCounter()); <add> if (!Arrays.equals(data, uncompressedBytes)) { <add> throw new IllegalStateException("broken decompressor"); <add> } <add> <add> Arrays.fill(uncompressedBytes, (byte) 0); <add> blockXerialSnappy(new BytesCounter()); <add> if (!Arrays.equals(data, uncompressedBytes)) { <add> throw new IllegalStateException("broken decompressor"); <add> } <add> <add> Arrays.fill(uncompressedBytes, (byte) 0); <add> streamAirliftSnappy(new BytesCounter()); <add> if (!Arrays.equals(data, uncompressedBytes)) { <add> throw new IllegalStateException("broken decompressor"); <add> } <add> <ide> Arrays.fill(uncompressedBytes, (byte) 0); <ide> streamHadoopSnappy(new BytesCounter()); <ide> if (!Arrays.equals(data, uncompressedBytes)) { <ide> public int streamAirliftSnappy(BytesCounter counter) <ide> throws IOException <ide> { <del> InputStream in = airliftSnappyCodec.createInputStream(new ByteArrayInputStream(streamCompressedAirliftSnappy)); <del> <del> int decompressedOffset = 0; <del> while (decompressedOffset < uncompressedBytes.length) { <del> decompressedOffset += in.read(uncompressedBytes, decompressedOffset, uncompressedBytes.length - decompressedOffset); <del> } <del> <del> counter.add(uncompressedBytes.length); <del> return decompressedOffset; <add> return streamHadoop(counter, airliftSnappyCodec, streamCompressedAirliftSnappy); <ide> } <ide> <ide> @Benchmark <ide> public int streamHadoopSnappy(BytesCounter counter) <ide> throws IOException <ide> { <del> InputStream in = hadoopSnappyCodec.createInputStream(new ByteArrayInputStream(streamCompressedHadoopSnappy)); <add> return streamHadoop(counter, hadoopSnappyCodec, streamCompressedHadoopSnappy); <add> } <add> <add> private int streamHadoop(BytesCounter counter, CompressionCodec codec, byte[] compressed) <add> throws IOException <add> { <add> InputStream in = codec.createInputStream(new ByteArrayInputStream(compressed)); <ide> <ide> int decompressedOffset = 0; <ide> while (decompressedOffset < uncompressedBytes.length) { <ide> public static void main(String[] args) <ide> throws Exception <ide> { <del> new DecompressBenchmark().prepare(); <add> DecompressBenchmark verifyDecompressor = new DecompressBenchmark(); <add> verifyDecompressor.prepare(); <add> verifyDecompressor.verify(); <ide> <ide> Options opt = new OptionsBuilder() <ide> // .outputFormat(OutputFormatType.Silent)
Java
mit
b858f08485b28460f262b32d74aa4a37fa471057
0
ljfa-ag/TNTUtils
package ljfa.tntutils; import java.io.File; import java.util.HashSet; import java.util.Set; import ljfa.tntutils.exception.InvalidConfigValueException; import ljfa.tntutils.util.LogHelper; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class Config { public static Configuration conf; public static final String CAT_GENERAL = "general"; public static final String CAT_BLOCKDMG = "block_damage"; public static final String CAT_ENTDMG = "entity_damage"; public static boolean explosionCommand; public static float sizeMultiplier; public static float dropChanceModifier; public static boolean disableExplosions; public static boolean preventChainExpl; public static boolean disableTNT; public static boolean disableTNTMinecart; public static boolean disableBlockDamage; public static boolean disableCreeperBlockDamage; public static String[] blacklistArray; public static Set<Block> blacklist = null; public static boolean blacklistActive = false; public static boolean spareTileEntities; public static boolean disableEntityDamage; public static boolean disablePlayerDamage; public static boolean disableNPCDamage; public static void loadConfig(File file) { if(conf == null) conf = new Configuration(file); conf.load(); loadValues(); FMLCommonHandler.instance().bus().register(new ChangeHandler()); } public static void loadValues() { explosionCommand = conf.get(CAT_GENERAL, "addExplosionCommand", true, "Adds the \"/explosion\" command").setRequiresMcRestart(true).getBoolean(); sizeMultiplier = (float)conf.get(CAT_GENERAL, "sizeMultiplier", 1.0, "Multiplies the size of all explosions by this", 0.0, 50.0).getDouble(); /*dropChanceModifier = (float)conf.get(CAT_GENERAL, "dropChanceIncrease", 0.0, "Increases the chance that explosions will drop destroyed blocks as items\n" + "0 = Vanilla behavior, 1 = always drop items.\n" + "Only affects explosions of size <= 10 since a large number of dropped items can cause lag.", 0.0, 1.0).getDouble();*/ disableExplosions = conf.get(CAT_GENERAL, "disableExplosions", false, "Entirely disables all effects from explosions").getBoolean(); preventChainExpl = conf.get(CAT_GENERAL, "preventChainExplosions", false, "Prevents explosions from triggering TNT and thus disables chain explosions").setRequiresMcRestart(true).getBoolean(); disableTNT = conf.get(CAT_GENERAL, "disableTNT", false, "Disables TNT explosions").setRequiresMcRestart(true).getBoolean(); disableTNTMinecart = conf.get(CAT_GENERAL, "disableTNTMinecart", false, "Disables the placement of TNT minecarts").setRequiresMcRestart(true).getBoolean(); //---------------- disableBlockDamage = conf.get(CAT_BLOCKDMG, "disableBlockDamage", false, "Disables all block damage from explosions").getBoolean(); disableCreeperBlockDamage = conf.get(CAT_BLOCKDMG, "disableCreeperBlockDamage", false, "\"Environmentally Friendly Creepers\": Makes creepers not destroy blocks").getBoolean(); blacklistArray = conf.get(CAT_BLOCKDMG, "destructionBlacklist", new String[0], "A list of blocks that will never be destroyed by explosions").getStringList(); spareTileEntities = conf.get(CAT_BLOCKDMG, "disableTileEntityDamage", false, "Makes explosions not destroy tile entities").getBoolean(); //---------------- disableEntityDamage = conf.get(CAT_ENTDMG, "disableEntityDamage", false, "Disables explosion damage to all entities (also includes items, minecarts etc.)").getBoolean(); disablePlayerDamage = conf.get(CAT_ENTDMG, "disablePlayerDamage", false, "Disables explosion damage to players").getBoolean(); disableNPCDamage = conf.get(CAT_ENTDMG, "disableNPCDamage", false, "Disables explosion damage to animals and mobs").getBoolean(); //---------------- if(conf.hasChanged()) conf.save(); } public static void createBlacklistSet() { blacklist = new HashSet<Block>(); for(String name: blacklistArray) { Block block = (Block)Block.blockRegistry.getObject(name); if(block == Blocks.air || block == null) { throw new InvalidConfigValueException("Invalid blacklist entry: " + name); } else { blacklist.add(block); LogHelper.debug("Added block to blacklist: %s", name); } } blacklistActive = blacklist.size() != 0; } /** Reloads the config values upon change */ public static class ChangeHandler { @SubscribeEvent public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { if(event.modID.equals(Reference.MODID)) { loadValues(); createBlacklistSet(); } } } }
src/main/java/ljfa/tntutils/Config.java
package ljfa.tntutils; import java.io.File; import java.util.HashSet; import java.util.Set; import ljfa.tntutils.exception.InvalidConfigValueException; import ljfa.tntutils.util.LogHelper; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class Config { public static Configuration conf; public static final String CAT_GENERAL = "general"; public static final String CAT_BLOCKDMG = "block_damage"; public static final String CAT_ENTDMG = "entity_damage"; public static boolean explosionCommand; public static float sizeMultiplier; public static float dropChanceModifier; public static boolean disableExplosions; public static boolean preventChainExpl; public static boolean disableTNT; public static boolean disableTNTMinecart; public static boolean disableBlockDamage; public static boolean disableCreeperBlockDamage; public static String[] blacklistArray; public static Set<Block> blacklist = null; public static boolean blacklistActive = false; public static boolean spareTileEntities; public static boolean disableEntityDamage; public static boolean disablePlayerDamage; public static boolean disableNPCDamage; public static void loadConfig(File file) { if(conf == null) conf = new Configuration(file); conf.load(); loadValues(); FMLCommonHandler.instance().bus().register(new ChangeHandler()); } public static void loadValues() { explosionCommand = conf.get(CAT_GENERAL, "addExplosionCommand", true, "Adds the \"/explosion\" command").setRequiresMcRestart(true).getBoolean(); sizeMultiplier = (float)conf.get(CAT_GENERAL, "sizeMultiplier", 1.0, "Multiplies the size of all explosions by this", 0.0, 50.0).getDouble(); dropChanceModifier = (float)conf.get(CAT_GENERAL, "dropChanceIncrease", 0.0, "Increases the chance that explosions will drop destroyed blocks as items\n" + "0 = Vanilla behavior, 1 = always drop items.\n" + "Only affects explosions of size <= 10 since a large number of dropped items can cause lag.", 0.0, 1.0).getDouble(); disableExplosions = conf.get(CAT_GENERAL, "disableExplosions", false, "Entirely disables all effects from explosions").getBoolean(); preventChainExpl = conf.get(CAT_GENERAL, "preventChainExplosions", false, "Prevents explosions from triggering TNT and thus disables chain explosions").setRequiresMcRestart(true).getBoolean(); disableTNT = conf.get(CAT_GENERAL, "disableTNT", false, "Disables TNT explosions").setRequiresMcRestart(true).getBoolean(); disableTNTMinecart = conf.get(CAT_GENERAL, "disableTNTMinecart", false, "Disables the placement of TNT minecarts").setRequiresMcRestart(true).getBoolean(); //---------------- disableBlockDamage = conf.get(CAT_BLOCKDMG, "disableBlockDamage", false, "Disables all block damage from explosions").getBoolean(); disableCreeperBlockDamage = conf.get(CAT_BLOCKDMG, "disableCreeperBlockDamage", false, "\"Environmentally Friendly Creepers\": Makes creepers not destroy blocks").getBoolean(); blacklistArray = conf.get(CAT_BLOCKDMG, "destructionBlacklist", new String[0], "A list of blocks that will never be destroyed by explosions").getStringList(); spareTileEntities = conf.get(CAT_BLOCKDMG, "disableTileEntityDamage", false, "Makes explosions not destroy tile entities").getBoolean(); //---------------- disableEntityDamage = conf.get(CAT_ENTDMG, "disableEntityDamage", false, "Disables explosion damage to all entities (also includes items, minecarts etc.)").getBoolean(); disablePlayerDamage = conf.get(CAT_ENTDMG, "disablePlayerDamage", false, "Disables explosion damage to players").getBoolean(); disableNPCDamage = conf.get(CAT_ENTDMG, "disableNPCDamage", false, "Disables explosion damage to animals and mobs").getBoolean(); //---------------- if(conf.hasChanged()) conf.save(); } public static void createBlacklistSet() { blacklist = new HashSet<Block>(); for(String name: blacklistArray) { Block block = (Block)Block.blockRegistry.getObject(name); if(block == Blocks.air || block == null) { throw new InvalidConfigValueException("Invalid blacklist entry: " + name); } else { blacklist.add(block); LogHelper.debug("Added block to blacklist: %s", name); } } blacklistActive = blacklist.size() != 0; } /** Reloads the config values upon change */ public static class ChangeHandler { @SubscribeEvent public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) { if(event.modID.equals(Reference.MODID)) { loadValues(); createBlacklistSet(); } } } }
Comment out this config option for now
src/main/java/ljfa/tntutils/Config.java
Comment out this config option for now
<ide><path>rc/main/java/ljfa/tntutils/Config.java <ide> public static void loadValues() { <ide> explosionCommand = conf.get(CAT_GENERAL, "addExplosionCommand", true, "Adds the \"/explosion\" command").setRequiresMcRestart(true).getBoolean(); <ide> sizeMultiplier = (float)conf.get(CAT_GENERAL, "sizeMultiplier", 1.0, "Multiplies the size of all explosions by this", 0.0, 50.0).getDouble(); <del> dropChanceModifier = (float)conf.get(CAT_GENERAL, "dropChanceIncrease", 0.0, "Increases the chance that explosions will drop destroyed blocks as items\n" <add> /*dropChanceModifier = (float)conf.get(CAT_GENERAL, "dropChanceIncrease", 0.0, "Increases the chance that explosions will drop destroyed blocks as items\n" <ide> + "0 = Vanilla behavior, 1 = always drop items.\n" <del> + "Only affects explosions of size <= 10 since a large number of dropped items can cause lag.", 0.0, 1.0).getDouble(); <add> + "Only affects explosions of size <= 10 since a large number of dropped items can cause lag.", 0.0, 1.0).getDouble();*/ <ide> disableExplosions = conf.get(CAT_GENERAL, "disableExplosions", false, "Entirely disables all effects from explosions").getBoolean(); <ide> preventChainExpl = conf.get(CAT_GENERAL, "preventChainExplosions", false, "Prevents explosions from triggering TNT and thus disables chain explosions").setRequiresMcRestart(true).getBoolean(); <ide> disableTNT = conf.get(CAT_GENERAL, "disableTNT", false, "Disables TNT explosions").setRequiresMcRestart(true).getBoolean();
Java
apache-2.0
57d3259437bc91491569685f5ab298938d5ef613
0
spring-cloud/spring-cloud-release-tools,spring-cloud/spring-cloud-release-tools,spring-cloud/spring-cloud-release-tools,spring-cloud/spring-cloud-release-tools,spring-cloud/spring-cloud-release-tools,spring-cloud/spring-cloud-release-tools
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.release.internal.project; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.release.internal.ReleaserProperties; import org.springframework.cloud.release.internal.ReleaserPropertiesAware; import org.springframework.util.StringUtils; /** * @author Marcin Grzejszczak */ public class ProjectCommandExecutor implements ReleaserPropertiesAware { private static final Logger log = LoggerFactory .getLogger(ProjectCommandExecutor.class); private static final String VERSION_MUSTACHE = "{{version}}"; private ReleaserProperties properties; public ProjectCommandExecutor(ReleaserProperties properties) { this.properties = properties; } // If you want to call commands that are not parameterized via the props public ProjectCommandExecutor() { this.properties = new ReleaserProperties(); } public void build(ProjectVersion versionFromReleaseTrain) { build(versionFromReleaseTrain, this.properties.getWorkingDir()); } public String version() { return executeCommand( new CommandPicker(this.properties, this.properties.getWorkingDir()) .version()); } public String groupId() { return executeCommand( new CommandPicker(this.properties, this.properties.getWorkingDir()) .groupId()); } private String executeCommand(String command) { try { String projectRoot = this.properties.getWorkingDir(); String[] commands = command.split(" "); return runCommand(projectRoot, commands); } catch (IllegalStateException e) { throw e; } catch (Exception e) { throw new IllegalStateException(e); } } public void build(ProjectVersion versionFromReleaseTrain, String projectRoot) { try { String[] commands = new CommandPicker(this.properties, projectRoot) .buildCommand(versionFromReleaseTrain).split(" "); runCommand(projectRoot, commands); assertNoHtmlFilesInDocsContainUnresolvedTags(projectRoot); log.info("No HTML files from docs contain unresolved tags"); } catch (Exception e) { throw new IllegalStateException(e); } } public void generateReleaseTrainDocs(String version, String projectRoot) { try { String updatedCommand = new CommandPicker(properties, projectRoot) .generateReleaseTrainDocsCommand( new ProjectVersion(new File(projectRoot))) .replace(VERSION_MUSTACHE, version); runCommand(projectRoot, updatedCommand.split(" ")); assertNoHtmlFilesInDocsContainUnresolvedTags(this.properties.getWorkingDir()); log.info("No HTML files from docs contain unresolved tags"); } catch (Exception e) { throw new IllegalStateException(e); } } private void assertNoHtmlFilesInDocsContainUnresolvedTags(String workingDir) { try { File docs = new File(workingDir, "docs"); if (!docs.exists()) { return; } Files.walkFileTree(docs.toPath(), new HtmlFileWalker()); } catch (IOException e) { throw new IllegalStateException(e); } } public void deploy(ProjectVersion version) { doDeploy(new CommandPicker(properties, this.properties.getWorkingDir()) .deployCommand(version)); } public void deployGuides(ProjectVersion version) { doDeploy(new CommandPicker(properties, this.properties.getWorkingDir()) .deployGuidesCommand(version)); } private void doDeploy(String command) { try { String[] commands = command.split(" "); runCommand(commands); log.info("The project has successfully been deployed"); } catch (Exception e) { throw new IllegalStateException(e); } } private void runCommand(String[] commands) { runCommand(this.properties.getWorkingDir(), commands); } private String runCommand(String projectRoot, String[] commands) { String[] substitutedCommands = substituteSystemProps(commands); long waitTimeInMinutes = new CommandPicker(properties, projectRoot) .waitTimeInMinutes(); return executor(projectRoot).runCommand(substitutedCommands, waitTimeInMinutes); } ProcessExecutor executor(String workDir) { return new ProcessExecutor(workDir); } public void publishDocs(String version) { try { for (String command : new CommandPicker(properties).publishDocsCommands()) { command = command.replace(VERSION_MUSTACHE, version); String[] commands = command.split(" "); runCommand(commands); } log.info("The docs got published successfully"); } catch (Exception e) { throw new IllegalStateException(e); } } /** * We need to insert the system properties as a list of -Dkey=value entries instead of * just pasting the String that contains these values. */ private String[] substituteSystemProps(String... commands) { String systemProperties = new CommandPicker(this.properties).systemProperties(); String systemPropertiesPlaceholder = new CommandPicker(this.properties) .systemPropertiesPlaceholder(); boolean containsSystemProps = systemProperties.contains("-D"); String[] splitSystemProps = StringUtils .delimitedListToStringArray(systemProperties, "-D"); // first element might be empty even though the second one contains values if (splitSystemProps.length > 1) { splitSystemProps = StringUtils.isEmpty(splitSystemProps[0]) ? Arrays.copyOfRange(splitSystemProps, 1, splitSystemProps.length) : splitSystemProps; } String[] systemPropsWithPrefix = containsSystemProps ? Arrays .stream(splitSystemProps).map(s -> "-D" + s.trim()) .collect(Collectors.toList()).toArray(new String[splitSystemProps.length]) : splitSystemProps; final AtomicInteger index = new AtomicInteger(-1); for (int i = 0; i < commands.length; i++) { if (commands[i].contains(systemPropertiesPlaceholder)) { index.set(i); break; } } return toCommandList(systemPropsWithPrefix, index, commands); } private String[] toCommandList(String[] systemPropsWithPrefix, AtomicInteger index, String[] commands) { List<String> commandsList = new ArrayList<>(Arrays.asList(commands)); List<String> systemPropsList = Arrays.asList(systemPropsWithPrefix); if (index.get() != -1) { commandsList.remove(index.get()); if (index.get() >= commandsList.size()) { commandsList.addAll(systemPropsList); } else { // we need to reverse to set the objects in the same order as passed in // the prop List<String> reversedSystemProps = new ArrayList<>(systemPropsList); Collections.reverse(reversedSystemProps); reversedSystemProps.forEach(s -> commandsList.add(index.get(), s)); } } return commandsList.toArray(new String[commandsList.size()]); } @Override public void setReleaserProperties(ReleaserProperties properties) { this.properties = properties; } } class ProcessExecutor implements ReleaserPropertiesAware { private static final Logger log = LoggerFactory.getLogger(ProcessExecutor.class); private String workingDir; ProcessExecutor(String workingDir) { this.workingDir = workingDir; } String runCommand(String[] commands, long waitTimeInMinutes) { try { String workingDir = this.workingDir; log.info( "Will run the command from [{}] and wait for result for [{}] minutes", workingDir, waitTimeInMinutes); ProcessBuilder builder = builder(commands, workingDir); Process process = startProcess(builder); boolean finished = process.waitFor(waitTimeInMinutes, TimeUnit.MINUTES); if (!finished) { log.error("The command hasn't managed to finish in [{}] minutes", waitTimeInMinutes); process.destroyForcibly(); throw new IllegalStateException("Process waiting time of [" + waitTimeInMinutes + "] minutes exceeded"); } if (process.exitValue() != 0) { throw new IllegalStateException("The process has exited with exit code [" + process.exitValue() + "]"); } return convertStreamToString(process.getInputStream()); } catch (InterruptedException | IOException e) { throw new IllegalStateException(e); } } private String convertStreamToString(InputStream is) { Scanner scanner = new Scanner(is).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; } Process startProcess(ProcessBuilder builder) throws IOException { return builder.start(); } ProcessBuilder builder(String[] commands, String workingDir) { // TODO: Improve this to not pass arrays in the first place String lastArg = String.join(" ", commands); String[] commandsWithBash = commandToExecute(lastArg); log.info( "Will run the command {}", commandsWithBash); return new ProcessBuilder(commandsWithBash).directory(new File(workingDir)) .inheritIO(); } String[] commandToExecute(String lastArg) { return new String[] { "/bin/bash", "-c", lastArg }; } @Override public void setReleaserProperties(ReleaserProperties properties) { this.workingDir = properties.getWorkingDir(); } } class CommandPicker { private static final Log log = LogFactory.getLog(CommandPicker.class); private final ReleaserProperties releaserProperties; private final ProjectType projectType; CommandPicker(ReleaserProperties releaserProperties, String projectRoot) { this.releaserProperties = releaserProperties; this.projectType = guessProjectType(projectRoot); } CommandPicker(ReleaserProperties releaserProperties) { this.releaserProperties = releaserProperties; String projectRoot = releaserProperties.getWorkingDir(); this.projectType = guessProjectType(projectRoot); } private ProjectType guessProjectType(String projectRoot) { if (new File(projectRoot, "pom.xml").exists()) { return ProjectType.MAVEN; } else if (new File(projectRoot, "build.gradle").exists()) { return ProjectType.GRADLE; } return ProjectType.BASH; } String systemProperties() { if (projectType == ProjectType.GRADLE) { return releaserProperties.getGradle().getSystemProperties(); } else if (projectType == ProjectType.MAVEN) { return releaserProperties.getMaven().getSystemProperties(); } return releaserProperties.getBash().getSystemProperties(); } public String[] publishDocsCommands() { if (projectType == ProjectType.GRADLE) { return releaserProperties.getGradle().getPublishDocsCommands(); } else if (projectType == ProjectType.MAVEN) { return releaserProperties.getMaven().getPublishDocsCommands(); } return releaserProperties.getBash().getPublishDocsCommands(); } String systemPropertiesPlaceholder() { if (projectType == ProjectType.GRADLE) { return ReleaserProperties.Gradle.SYSTEM_PROPS_PLACEHOLDER; } else if (projectType == ProjectType.MAVEN) { return ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER; } return ReleaserProperties.Bash.SYSTEM_PROPS_PLACEHOLDER; } String buildCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getBuildCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getBuildCommand(), version); } return bashCommandWithSystemProps(releaserProperties.getBash().getBuildCommand()); } String version() { // makes more sense to use PomReader if (projectType == ProjectType.GRADLE) { return "./gradlew properties | grep version: | awk '{print $2}'"; } return "./mvnw -q" + " -Dexec.executable=\"echo\"" + " -Dexec.args=\"\\${project.version}\"" + " --non-recursive" + " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1"; } String groupId() { // makes more sense to use PomReader if (projectType == ProjectType.GRADLE) { return "./gradlew groupId -q | tail -1"; } return "./mvnw -q" + " -Dexec.executable=\"echo\"" + " -Dexec.args=\"\\${project.groupId}\"" + " --non-recursive" + " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1"; } String generateReleaseTrainDocsCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getGenerateReleaseTrainDocsCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getGenerateReleaseTrainDocsCommand(), version); } return bashCommandWithSystemProps( releaserProperties.getBash().getGenerateReleaseTrainDocsCommand()); } String deployCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getDeployCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getDeployCommand(), version); } return bashCommandWithSystemProps( releaserProperties.getBash().getDeployCommand()); } String deployGuidesCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getDeployGuidesCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getDeployGuidesCommand(), version, MavenProfile.GUIDES, MavenProfile.INTEGRATION); } return bashCommandWithSystemProps( releaserProperties.getBash().getDeployGuidesCommand()); } long waitTimeInMinutes() { if (projectType == ProjectType.GRADLE) { return releaserProperties.getGradle().getWaitTimeInMinutes(); } else if (projectType == ProjectType.MAVEN) { return releaserProperties.getMaven().getWaitTimeInMinutes(); } return releaserProperties.getBash().getWaitTimeInMinutes(); } private String gradleCommandWithSystemProps(String command) { if (command.contains(ReleaserProperties.Gradle.SYSTEM_PROPS_PLACEHOLDER)) { return command; } return command + " " + ReleaserProperties.Gradle.SYSTEM_PROPS_PLACEHOLDER; } private String mavenCommandWithSystemProps(String command, ProjectVersion version, MavenProfile... profiles) { if (command.contains(ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER)) { return appendMavenProfile(command, version, profiles); } return appendMavenProfile(command, version, profiles) + " " + ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER; } private String bashCommandWithSystemProps(String command) { if (command.contains(ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER)) { return command; } return command + " " + ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER; } private String appendMavenProfile(String command, ProjectVersion version, MavenProfile... profiles) { String trimmedCommand = command.trim(); if (version.isMilestone() || version.isRc()) { log.info("Adding the milestone profile to the Maven build"); return withProfile(trimmedCommand, MavenProfile.MILESTONE.asMavenProfile(), profiles); } else if (version.isRelease() || version.isServiceRelease()) { log.info("Adding the central profile to the Maven build"); return withProfile(trimmedCommand, MavenProfile.CENTRAL.asMavenProfile(), profiles); } else { log.info("The build is a snapshot one - will not add any profiles"); } return trimmedCommand; } private String withProfile(String command, String profile, MavenProfile... profiles) { if (command.contains(ReleaserProperties.Maven.PROFILE_PROPS_PLACEHOLDER)) { return command.replace(ReleaserProperties.Maven.PROFILE_PROPS_PLACEHOLDER, profile + appendProfiles(profiles)); } return command + " " + profile + appendProfiles(profiles); } private String appendProfiles(MavenProfile[] profiles) { return profiles.length > 0 ? " " + profilesToString(profiles) : ""; } private String profilesToString(MavenProfile... profiles) { return Arrays.stream(profiles).map(profile -> "-P" + profile) .collect(Collectors.joining(" ")); } private enum ProjectType { MAVEN, GRADLE, BASH; } /** * Enumeration over commonly used Maven profiles. */ private enum MavenProfile { /** * Profile used for milestone versions. */ MILESTONE, /** * Profile used for ga versions. */ CENTRAL, /** * Profile used to run integration tests. */ INTEGRATION, /** * Profile used to run guides publishing. */ GUIDES; /** * Converts the profile to lowercase, maven command line property. * @return profile with prepended -P */ public String asMavenProfile() { return "-P" + this.name().toLowerCase(); } } } class HtmlFileWalker extends SimpleFileVisitor<Path> { private static final String HTML_EXTENSION = ".html"; @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attr) { File file = path.toFile(); if (file.getName().endsWith(HTML_EXTENSION) && asString(file).contains("Unresolved")) { throw new IllegalStateException( "File [" + file + "] contains a tag that wasn't resolved properly"); } return FileVisitResult.CONTINUE; } private String asString(File file) { try { return new String(Files.readAllBytes(file.toPath())); } catch (IOException e) { throw new IllegalStateException(e); } } }
spring-cloud-release-tools-core/src/main/java/org/springframework/cloud/release/internal/project/ProjectCommandExecutor.java
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.release.internal.project; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.release.internal.ReleaserProperties; import org.springframework.cloud.release.internal.ReleaserPropertiesAware; import org.springframework.util.StringUtils; /** * @author Marcin Grzejszczak */ public class ProjectCommandExecutor implements ReleaserPropertiesAware { private static final Logger log = LoggerFactory .getLogger(ProjectCommandExecutor.class); private static final String VERSION_MUSTACHE = "{{version}}"; private ReleaserProperties properties; public ProjectCommandExecutor(ReleaserProperties properties) { this.properties = properties; } // If you want to call commands that are not parameterized via the props public ProjectCommandExecutor() { this.properties = new ReleaserProperties(); } public void build(ProjectVersion versionFromReleaseTrain) { build(versionFromReleaseTrain, this.properties.getWorkingDir()); } public String version() { return executeCommand( new CommandPicker(this.properties, this.properties.getWorkingDir()) .version()); } public String groupId() { return executeCommand( new CommandPicker(this.properties, this.properties.getWorkingDir()) .groupId()); } private String executeCommand(String command) { try { String projectRoot = this.properties.getWorkingDir(); String[] commands = command.split(" "); return runCommand(projectRoot, commands); } catch (IllegalStateException e) { throw e; } catch (Exception e) { throw new IllegalStateException(e); } } public void build(ProjectVersion versionFromReleaseTrain, String projectRoot) { try { String[] commands = new CommandPicker(this.properties, projectRoot) .buildCommand(versionFromReleaseTrain).split(" "); runCommand(projectRoot, commands); assertNoHtmlFilesInDocsContainUnresolvedTags(projectRoot); log.info("No HTML files from docs contain unresolved tags"); } catch (Exception e) { throw new IllegalStateException(e); } } public void generateReleaseTrainDocs(String version, String projectRoot) { try { String updatedCommand = new CommandPicker(properties, projectRoot) .generateReleaseTrainDocsCommand( new ProjectVersion(new File(projectRoot))) .replace(VERSION_MUSTACHE, version); runCommand(projectRoot, updatedCommand.split(" ")); assertNoHtmlFilesInDocsContainUnresolvedTags(this.properties.getWorkingDir()); log.info("No HTML files from docs contain unresolved tags"); } catch (Exception e) { throw new IllegalStateException(e); } } private void assertNoHtmlFilesInDocsContainUnresolvedTags(String workingDir) { try { File docs = new File(workingDir, "docs"); if (!docs.exists()) { return; } Files.walkFileTree(docs.toPath(), new HtmlFileWalker()); } catch (IOException e) { throw new IllegalStateException(e); } } public void deploy(ProjectVersion version) { doDeploy(new CommandPicker(properties, this.properties.getWorkingDir()) .deployCommand(version)); } public void deployGuides(ProjectVersion version) { doDeploy(new CommandPicker(properties, this.properties.getWorkingDir()) .deployGuidesCommand(version)); } private void doDeploy(String command) { try { String[] commands = command.split(" "); runCommand(commands); log.info("The project has successfully been deployed"); } catch (Exception e) { throw new IllegalStateException(e); } } private void runCommand(String[] commands) { runCommand(this.properties.getWorkingDir(), commands); } private String runCommand(String projectRoot, String[] commands) { String[] substitutedCommands = substituteSystemProps(commands); long waitTimeInMinutes = new CommandPicker(properties, projectRoot) .waitTimeInMinutes(); return executor(projectRoot).runCommand(substitutedCommands, waitTimeInMinutes); } ProcessExecutor executor(String workDir) { return new ProcessExecutor(workDir); } public void publishDocs(String version) { try { for (String command : new CommandPicker(properties).publishDocsCommands()) { command = command.replace(VERSION_MUSTACHE, version); String[] commands = command.split(" "); runCommand(commands); } log.info("The docs got published successfully"); } catch (Exception e) { throw new IllegalStateException(e); } } /** * We need to insert the system properties as a list of -Dkey=value entries instead of * just pasting the String that contains these values. */ private String[] substituteSystemProps(String... commands) { String systemProperties = new CommandPicker(this.properties).systemProperties(); String systemPropertiesPlaceholder = new CommandPicker(this.properties) .systemPropertiesPlaceholder(); boolean containsSystemProps = systemProperties.contains("-D"); String[] splitSystemProps = StringUtils .delimitedListToStringArray(systemProperties, "-D"); // first element might be empty even though the second one contains values if (splitSystemProps.length > 1) { splitSystemProps = StringUtils.isEmpty(splitSystemProps[0]) ? Arrays.copyOfRange(splitSystemProps, 1, splitSystemProps.length) : splitSystemProps; } String[] systemPropsWithPrefix = containsSystemProps ? Arrays .stream(splitSystemProps).map(s -> "-D" + s.trim()) .collect(Collectors.toList()).toArray(new String[splitSystemProps.length]) : splitSystemProps; final AtomicInteger index = new AtomicInteger(-1); for (int i = 0; i < commands.length; i++) { if (commands[i].contains(systemPropertiesPlaceholder)) { index.set(i); break; } } return toCommandList(systemPropsWithPrefix, index, commands); } private String[] toCommandList(String[] systemPropsWithPrefix, AtomicInteger index, String[] commands) { List<String> commandsList = new ArrayList<>(Arrays.asList(commands)); List<String> systemPropsList = Arrays.asList(systemPropsWithPrefix); if (index.get() != -1) { commandsList.remove(index.get()); if (index.get() >= commandsList.size()) { commandsList.addAll(systemPropsList); } else { // we need to reverse to set the objects in the same order as passed in // the prop List<String> reversedSystemProps = new ArrayList<>(systemPropsList); Collections.reverse(reversedSystemProps); reversedSystemProps.forEach(s -> commandsList.add(index.get(), s)); } } return commandsList.toArray(new String[commandsList.size()]); } @Override public void setReleaserProperties(ReleaserProperties properties) { this.properties = properties; } } class ProcessExecutor implements ReleaserPropertiesAware { private static final Logger log = LoggerFactory.getLogger(ProcessExecutor.class); private String workingDir; ProcessExecutor(String workingDir) { this.workingDir = workingDir; } String runCommand(String[] commands, long waitTimeInMinutes) { try { String workingDir = this.workingDir; log.info( "Will run the command from [{}] via {} and wait for result for [{}] minutes", workingDir, commands, waitTimeInMinutes); ProcessBuilder builder = builder(commands, workingDir); Process process = startProcess(builder); boolean finished = process.waitFor(waitTimeInMinutes, TimeUnit.MINUTES); if (!finished) { log.error("The command hasn't managed to finish in [{}] minutes", waitTimeInMinutes); process.destroyForcibly(); throw new IllegalStateException("Process waiting time of [" + waitTimeInMinutes + "] minutes exceeded"); } if (process.exitValue() != 0) { throw new IllegalStateException("The process has exited with exit code [" + process.exitValue() + "]"); } return convertStreamToString(process.getInputStream()); } catch (InterruptedException | IOException e) { throw new IllegalStateException(e); } } private String convertStreamToString(InputStream is) { Scanner scanner = new Scanner(is).useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; } Process startProcess(ProcessBuilder builder) throws IOException { return builder.start(); } ProcessBuilder builder(String[] commands, String workingDir) { // TODO: Improve this to not pass arrays in the first place String lastArg = String.join(" ", commands); String[] commandsWithBash = commandToExecute(lastArg); return new ProcessBuilder(commandsWithBash).directory(new File(workingDir)) .inheritIO(); } String[] commandToExecute(String lastArg) { return new String[] { "/bin/bash", "-c", lastArg }; } @Override public void setReleaserProperties(ReleaserProperties properties) { this.workingDir = properties.getWorkingDir(); } } class CommandPicker { private static final Log log = LogFactory.getLog(CommandPicker.class); private final ReleaserProperties releaserProperties; private final ProjectType projectType; CommandPicker(ReleaserProperties releaserProperties, String projectRoot) { this.releaserProperties = releaserProperties; this.projectType = guessProjectType(projectRoot); } CommandPicker(ReleaserProperties releaserProperties) { this.releaserProperties = releaserProperties; String projectRoot = releaserProperties.getWorkingDir(); this.projectType = guessProjectType(projectRoot); } private ProjectType guessProjectType(String projectRoot) { if (new File(projectRoot, "pom.xml").exists()) { return ProjectType.MAVEN; } else if (new File(projectRoot, "build.gradle").exists()) { return ProjectType.GRADLE; } return ProjectType.BASH; } String systemProperties() { if (projectType == ProjectType.GRADLE) { return releaserProperties.getGradle().getSystemProperties(); } else if (projectType == ProjectType.MAVEN) { return releaserProperties.getMaven().getSystemProperties(); } return releaserProperties.getBash().getSystemProperties(); } public String[] publishDocsCommands() { if (projectType == ProjectType.GRADLE) { return releaserProperties.getGradle().getPublishDocsCommands(); } else if (projectType == ProjectType.MAVEN) { return releaserProperties.getMaven().getPublishDocsCommands(); } return releaserProperties.getBash().getPublishDocsCommands(); } String systemPropertiesPlaceholder() { if (projectType == ProjectType.GRADLE) { return ReleaserProperties.Gradle.SYSTEM_PROPS_PLACEHOLDER; } else if (projectType == ProjectType.MAVEN) { return ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER; } return ReleaserProperties.Bash.SYSTEM_PROPS_PLACEHOLDER; } String buildCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getBuildCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getBuildCommand(), version); } return bashCommandWithSystemProps(releaserProperties.getBash().getBuildCommand()); } String version() { // makes more sense to use PomReader if (projectType == ProjectType.GRADLE) { return "./gradlew properties | grep version: | awk '{print $2}'"; } return "./mvnw -q" + " -Dexec.executable=\"echo\"" + " -Dexec.args=\"\\${project.version}\"" + " --non-recursive" + " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1"; } String groupId() { // makes more sense to use PomReader if (projectType == ProjectType.GRADLE) { return "./gradlew groupId -q | tail -1"; } return "./mvnw -q" + " -Dexec.executable=\"echo\"" + " -Dexec.args=\"\\${project.groupId}\"" + " --non-recursive" + " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1"; } String generateReleaseTrainDocsCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getGenerateReleaseTrainDocsCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getGenerateReleaseTrainDocsCommand(), version); } return bashCommandWithSystemProps( releaserProperties.getBash().getGenerateReleaseTrainDocsCommand()); } String deployCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getDeployCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getDeployCommand(), version); } return bashCommandWithSystemProps( releaserProperties.getBash().getDeployCommand()); } String deployGuidesCommand(ProjectVersion version) { if (projectType == ProjectType.GRADLE) { return gradleCommandWithSystemProps( releaserProperties.getGradle().getDeployGuidesCommand()); } else if (projectType == ProjectType.MAVEN) { return mavenCommandWithSystemProps( releaserProperties.getMaven().getDeployGuidesCommand(), version, MavenProfile.GUIDES, MavenProfile.INTEGRATION); } return bashCommandWithSystemProps( releaserProperties.getBash().getDeployGuidesCommand()); } long waitTimeInMinutes() { if (projectType == ProjectType.GRADLE) { return releaserProperties.getGradle().getWaitTimeInMinutes(); } else if (projectType == ProjectType.MAVEN) { return releaserProperties.getMaven().getWaitTimeInMinutes(); } return releaserProperties.getBash().getWaitTimeInMinutes(); } private String gradleCommandWithSystemProps(String command) { if (command.contains(ReleaserProperties.Gradle.SYSTEM_PROPS_PLACEHOLDER)) { return command; } return command + " " + ReleaserProperties.Gradle.SYSTEM_PROPS_PLACEHOLDER; } private String mavenCommandWithSystemProps(String command, ProjectVersion version, MavenProfile... profiles) { if (command.contains(ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER)) { return appendMavenProfile(command, version, profiles); } return appendMavenProfile(command, version, profiles) + " " + ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER; } private String bashCommandWithSystemProps(String command) { if (command.contains(ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER)) { return command; } return command + " " + ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER; } private String appendMavenProfile(String command, ProjectVersion version, MavenProfile... profiles) { String trimmedCommand = command.trim(); if (version.isMilestone() || version.isRc()) { log.info("Adding the milestone profile to the Maven build"); return withProfile(trimmedCommand, MavenProfile.MILESTONE.asMavenProfile(), profiles); } else if (version.isRelease() || version.isServiceRelease()) { log.info("Adding the central profile to the Maven build"); return withProfile(trimmedCommand, MavenProfile.CENTRAL.asMavenProfile(), profiles); } else { log.info("The build is a snapshot one - will not add any profiles"); } return trimmedCommand; } private String withProfile(String command, String profile, MavenProfile... profiles) { if (command.contains(ReleaserProperties.Maven.PROFILE_PROPS_PLACEHOLDER)) { return command.replace(ReleaserProperties.Maven.PROFILE_PROPS_PLACEHOLDER, profile + appendProfiles(profiles)); } return command + " " + profile + appendProfiles(profiles); } private String appendProfiles(MavenProfile[] profiles) { return profiles.length > 0 ? " " + profilesToString(profiles) : ""; } private String profilesToString(MavenProfile... profiles) { return Arrays.stream(profiles).map(profile -> "-P" + profile) .collect(Collectors.joining(" ")); } private enum ProjectType { MAVEN, GRADLE, BASH; } /** * Enumeration over commonly used Maven profiles. */ private enum MavenProfile { /** * Profile used for milestone versions. */ MILESTONE, /** * Profile used for ga versions. */ CENTRAL, /** * Profile used to run integration tests. */ INTEGRATION, /** * Profile used to run guides publishing. */ GUIDES; /** * Converts the profile to lowercase, maven command line property. * @return profile with prepended -P */ public String asMavenProfile() { return "-P" + this.name().toLowerCase(); } } } class HtmlFileWalker extends SimpleFileVisitor<Path> { private static final String HTML_EXTENSION = ".html"; @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attr) { File file = path.toFile(); if (file.getName().endsWith(HTML_EXTENSION) && asString(file).contains("Unresolved")) { throw new IllegalStateException( "File [" + file + "] contains a tag that wasn't resolved properly"); } return FileVisitResult.CONTINUE; } private String asString(File file) { try { return new String(Files.readAllBytes(file.toPath())); } catch (IOException e) { throw new IllegalStateException(e); } } }
Debug for command executor
spring-cloud-release-tools-core/src/main/java/org/springframework/cloud/release/internal/project/ProjectCommandExecutor.java
Debug for command executor
<ide><path>pring-cloud-release-tools-core/src/main/java/org/springframework/cloud/release/internal/project/ProjectCommandExecutor.java <ide> try { <ide> String workingDir = this.workingDir; <ide> log.info( <del> "Will run the command from [{}] via {} and wait for result for [{}] minutes", <del> workingDir, commands, waitTimeInMinutes); <add> "Will run the command from [{}] and wait for result for [{}] minutes", <add> workingDir, waitTimeInMinutes); <ide> ProcessBuilder builder = builder(commands, workingDir); <ide> Process process = startProcess(builder); <ide> boolean finished = process.waitFor(waitTimeInMinutes, TimeUnit.MINUTES); <ide> // TODO: Improve this to not pass arrays in the first place <ide> String lastArg = String.join(" ", commands); <ide> String[] commandsWithBash = commandToExecute(lastArg); <add> log.info( <add> "Will run the command {}", commandsWithBash); <ide> return new ProcessBuilder(commandsWithBash).directory(new File(workingDir)) <ide> .inheritIO(); <ide> }
Java
mit
8f12a58ccee6bbd16286e76dec91e8fc725f482c
0
evgenyneu/walk-to-circle-android
package com.evgenii.walktocircle.WalkWalk; import java.util.HashSet; import java.util.Set; import java.util.Vector; public class WalkRandomQuote { // Random number generator used to pick a random quote. // The property is null normally but in the unit test it is set with a fake random number generator. public static WalkRandomQuoteNumberGenerator mRandomNumberGenerator; /** * The main method to be called on the main screen to get the current quote to be shown * to the user and the list of already shown quotes. * @param allQuotes all the quotes. * @param alreadyShownQuotes the list of quotes that are already shown to the user. * @return the quote to be shown now and the set of already shown quotes. */ public static WalkQuoteToShow quoteToShow(WalkQuote[] allQuotes, Set<String> alreadyShownQuotes) { WalkQuoteToShow result = new WalkQuoteToShow(); WalkQuote[] newQuotes = excludeQuotes(allQuotes, alreadyShownQuotes); result.quoteToShow = pickRandom(newQuotes); // Add the picked quote to the list of shown quotes to avoid showing it soon again Set<String> newAlreadyShownQuotes = new HashSet<String>(); newAlreadyShownQuotes.addAll(alreadyShownQuotes); newAlreadyShownQuotes.add(result.quoteToShow.text); result.alreadyShownQuotes = newAlreadyShownQuotes; return result; } public static WalkRandomQuoteNumberGenerator getRandomNumberGenerator() { if (mRandomNumberGenerator == null) { return new WalkRandomQuoteNumberGenerator(); } else { return mRandomNumberGenerator; } } public static WalkQuote pickOne(boolean isTutorial) { return WalkManyQuotes.tutorialText; } /** * * @param fromQuotes * @return a random quote form the array. */ public static WalkQuote pickRandom(WalkQuote[] fromQuotes) { int randomIndex = getRandomNumberGenerator().getRandomIntUntil(fromQuotes.length); if (randomIndex > (fromQuotes.length - 1)) { return null; } return fromQuotes[randomIndex]; } /** * @return quotes from "fromQuotes" array excluding that ones that match the ones in "exclude" set. */ public static WalkQuote[] excludeQuotes(WalkQuote[] fromQuotes, Set<String> exclude) { Vector filteredQuotes = new Vector(); for (WalkQuote quote : fromQuotes){ if (!exclude.contains(quote.text)) { filteredQuotes.addElement(quote); } } WalkQuote[] filteredQuotesArray = new WalkQuote[filteredQuotes.size()]; filteredQuotes.copyInto(filteredQuotesArray); return filteredQuotesArray; } }
app/src/main/java/com/evgenii/walktocircle/WalkWalk/WalkRandomQuote.java
package com.evgenii.walktocircle.WalkWalk; import java.util.Set; import java.util.Vector; public class WalkRandomQuote { // Random number generator used to pick a random quote. // The property is null normally but in the unit test it is set with a fake random number generator. public static WalkRandomQuoteNumberGenerator mRandomNumberGenerator; /** * The main method to be called on the main screen to get the current quote to be shown * to the user and the list of already shown quotes. * @param allQuotes all the quotes. * @param alreadyShownQuotes the list of quotes that are already shown to the user. * @return the quote to be shown now and the set of already shown quotes. */ public static WalkQuoteToShow quoteToShow(WalkQuote[] allQuotes, Set<String> alreadyShownQuotes) { WalkQuoteToShow result = new WalkQuoteToShow(); WalkQuote[] newQuotes = excludeQuotes(allQuotes, alreadyShownQuotes); result.quoteToShow = pickRandom(newQuotes); // Add the picked quote to the list of shown quotes to avoid showing it soon again alreadyShownQuotes.add(result.quoteToShow.text); result.alreadyShownQuotes = alreadyShownQuotes; return result; } public static WalkRandomQuoteNumberGenerator getRandomNumberGenerator() { if (mRandomNumberGenerator == null) { return new WalkRandomQuoteNumberGenerator(); } else { return mRandomNumberGenerator; } } public static WalkQuote pickOne(boolean isTutorial) { return WalkManyQuotes.tutorialText; } /** * * @param fromQuotes * @return a random quote form the array. */ public static WalkQuote pickRandom(WalkQuote[] fromQuotes) { int randomIndex = getRandomNumberGenerator().getRandomIntUntil(fromQuotes.length); if (randomIndex > (fromQuotes.length - 1)) { return null; } return fromQuotes[randomIndex]; } /** * @return quotes from "fromQuotes" array excluding that ones that match the ones in "exclude" set. */ public static WalkQuote[] excludeQuotes(WalkQuote[] fromQuotes, Set<String> exclude) { Vector filteredQuotes = new Vector(); for (WalkQuote quote : fromQuotes){ if (!exclude.contains(quote.text)) { filteredQuotes.addElement(quote); } } WalkQuote[] filteredQuotesArray = new WalkQuote[filteredQuotes.size()]; filteredQuotes.copyInto(filteredQuotesArray); return filteredQuotesArray; } }
Walk screen
app/src/main/java/com/evgenii/walktocircle/WalkWalk/WalkRandomQuote.java
Walk screen
<ide><path>pp/src/main/java/com/evgenii/walktocircle/WalkWalk/WalkRandomQuote.java <ide> package com.evgenii.walktocircle.WalkWalk; <ide> <add>import java.util.HashSet; <ide> import java.util.Set; <ide> import java.util.Vector; <ide> <ide> result.quoteToShow = pickRandom(newQuotes); <ide> <ide> // Add the picked quote to the list of shown quotes to avoid showing it soon again <del> alreadyShownQuotes.add(result.quoteToShow.text); <del> result.alreadyShownQuotes = alreadyShownQuotes; <add> Set<String> newAlreadyShownQuotes = new HashSet<String>(); <add> newAlreadyShownQuotes.addAll(alreadyShownQuotes); <add> newAlreadyShownQuotes.add(result.quoteToShow.text); <add> result.alreadyShownQuotes = newAlreadyShownQuotes; <ide> <ide> return result; <ide> }
Java
apache-2.0
d71a8b14aaf8c6318a4226713fd83dbfb2d25f3a
0
jabbrwcky/selenium,davehunt/selenium,joshbruning/selenium,titusfortner/selenium,asashour/selenium,titusfortner/selenium,chrisblock/selenium,carlosroh/selenium,juangj/selenium,joshmgrant/selenium,jabbrwcky/selenium,carlosroh/selenium,jabbrwcky/selenium,HtmlUnit/selenium,mach6/selenium,joshmgrant/selenium,joshbruning/selenium,joshbruning/selenium,GorK-ChO/selenium,valfirst/selenium,krmahadevan/selenium,mach6/selenium,juangj/selenium,titusfortner/selenium,GorK-ChO/selenium,Ardesco/selenium,twalpole/selenium,oddui/selenium,twalpole/selenium,SeleniumHQ/selenium,juangj/selenium,chrisblock/selenium,titusfortner/selenium,HtmlUnit/selenium,5hawnknight/selenium,carlosroh/selenium,jabbrwcky/selenium,krmahadevan/selenium,GorK-ChO/selenium,lmtierney/selenium,dibagga/selenium,asashour/selenium,bayandin/selenium,joshbruning/selenium,titusfortner/selenium,Dude-X/selenium,lmtierney/selenium,GorK-ChO/selenium,bayandin/selenium,jabbrwcky/selenium,Ardesco/selenium,jabbrwcky/selenium,dibagga/selenium,joshmgrant/selenium,xmhubj/selenium,HtmlUnit/selenium,chrisblock/selenium,dibagga/selenium,joshmgrant/selenium,davehunt/selenium,carlosroh/selenium,juangj/selenium,lmtierney/selenium,valfirst/selenium,markodolancic/selenium,joshmgrant/selenium,krmahadevan/selenium,krmahadevan/selenium,chrisblock/selenium,asashour/selenium,bayandin/selenium,carlosroh/selenium,markodolancic/selenium,titusfortner/selenium,dibagga/selenium,SeleniumHQ/selenium,joshbruning/selenium,Tom-Trumper/selenium,xmhubj/selenium,markodolancic/selenium,SeleniumHQ/selenium,SeleniumHQ/selenium,Tom-Trumper/selenium,mach6/selenium,HtmlUnit/selenium,asashour/selenium,Tom-Trumper/selenium,Dude-X/selenium,oddui/selenium,SeleniumHQ/selenium,Dude-X/selenium,valfirst/selenium,asolntsev/selenium,valfirst/selenium,joshbruning/selenium,valfirst/selenium,joshmgrant/selenium,krmahadevan/selenium,Ardesco/selenium,lmtierney/selenium,krmahadevan/selenium,jabbrwcky/selenium,carlosroh/selenium,jabbrwcky/selenium,xmhubj/selenium,chrisblock/selenium,jsakamoto/selenium,asolntsev/selenium,mach6/selenium,HtmlUnit/selenium,HtmlUnit/selenium,mach6/selenium,davehunt/selenium,markodolancic/selenium,valfirst/selenium,oddui/selenium,jsakamoto/selenium,lmtierney/selenium,davehunt/selenium,titusfortner/selenium,titusfortner/selenium,SeleniumHQ/selenium,krmahadevan/selenium,mach6/selenium,bayandin/selenium,davehunt/selenium,carlosroh/selenium,twalpole/selenium,asolntsev/selenium,lmtierney/selenium,oddui/selenium,HtmlUnit/selenium,jsakamoto/selenium,chrisblock/selenium,Dude-X/selenium,asolntsev/selenium,Tom-Trumper/selenium,asashour/selenium,mach6/selenium,asolntsev/selenium,valfirst/selenium,GorK-ChO/selenium,asashour/selenium,SeleniumHQ/selenium,asolntsev/selenium,5hawnknight/selenium,lmtierney/selenium,joshbruning/selenium,GorK-ChO/selenium,5hawnknight/selenium,Ardesco/selenium,bayandin/selenium,markodolancic/selenium,juangj/selenium,jsakamoto/selenium,xmhubj/selenium,SeleniumHQ/selenium,xmhubj/selenium,carlosroh/selenium,jsakamoto/selenium,twalpole/selenium,chrisblock/selenium,krmahadevan/selenium,twalpole/selenium,lmtierney/selenium,markodolancic/selenium,joshmgrant/selenium,davehunt/selenium,Tom-Trumper/selenium,asashour/selenium,Dude-X/selenium,SeleniumHQ/selenium,bayandin/selenium,Ardesco/selenium,dibagga/selenium,bayandin/selenium,carlosroh/selenium,dibagga/selenium,asashour/selenium,juangj/selenium,lmtierney/selenium,valfirst/selenium,mach6/selenium,joshmgrant/selenium,SeleniumHQ/selenium,GorK-ChO/selenium,chrisblock/selenium,mach6/selenium,dibagga/selenium,markodolancic/selenium,oddui/selenium,joshmgrant/selenium,Ardesco/selenium,bayandin/selenium,5hawnknight/selenium,HtmlUnit/selenium,5hawnknight/selenium,titusfortner/selenium,jsakamoto/selenium,5hawnknight/selenium,bayandin/selenium,markodolancic/selenium,Ardesco/selenium,Tom-Trumper/selenium,xmhubj/selenium,juangj/selenium,krmahadevan/selenium,joshbruning/selenium,titusfortner/selenium,xmhubj/selenium,oddui/selenium,asolntsev/selenium,jsakamoto/selenium,juangj/selenium,HtmlUnit/selenium,twalpole/selenium,Ardesco/selenium,Dude-X/selenium,jsakamoto/selenium,twalpole/selenium,Dude-X/selenium,oddui/selenium,joshmgrant/selenium,xmhubj/selenium,dibagga/selenium,GorK-ChO/selenium,asashour/selenium,titusfortner/selenium,davehunt/selenium,Tom-Trumper/selenium,HtmlUnit/selenium,Dude-X/selenium,juangj/selenium,joshbruning/selenium,jabbrwcky/selenium,Tom-Trumper/selenium,valfirst/selenium,xmhubj/selenium,davehunt/selenium,oddui/selenium,asolntsev/selenium,5hawnknight/selenium,jsakamoto/selenium,valfirst/selenium,SeleniumHQ/selenium,chrisblock/selenium,Tom-Trumper/selenium,twalpole/selenium,5hawnknight/selenium,valfirst/selenium,5hawnknight/selenium,Ardesco/selenium,GorK-ChO/selenium,oddui/selenium,Dude-X/selenium,dibagga/selenium,markodolancic/selenium,twalpole/selenium,davehunt/selenium,joshmgrant/selenium,asolntsev/selenium
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.remote.server.handler.internal; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.remote.server.KnownElements; import java.util.List; import java.util.Map; public class ArgumentConverter implements Function<Object, Object> { private final KnownElements knownElements; public ArgumentConverter(KnownElements knownElements) { this.knownElements = knownElements; } public Object apply(Object arg) { if (arg instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> paramAsMap = (Map<String, Object>) arg; if (paramAsMap.containsKey("ELEMENT")) { KnownElements.ProxiedElement element = (KnownElements.ProxiedElement) knownElements .get((String) paramAsMap.get("ELEMENT")); return element.getWrappedElement(); } Map<String, Object> converted = Maps.newHashMapWithExpectedSize(paramAsMap.size()); for (Map.Entry<String, Object> entry : paramAsMap.entrySet()) { converted.put(entry.getKey(), apply(entry.getValue())); } return converted; } if (arg instanceof RemoteWebElement) { return knownElements.get(((RemoteWebElement) arg).getId()); } if (arg instanceof List<?>) { return Lists.newArrayList(Iterables.transform((List<?>) arg, this)); } return arg; } }
java/server/src/org/openqa/selenium/remote/server/handler/internal/ArgumentConverter.java
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium.remote.server.handler.internal; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.openqa.selenium.remote.server.KnownElements; import java.util.List; import java.util.Map; public class ArgumentConverter implements Function<Object, Object> { private final KnownElements knownElements; public ArgumentConverter(KnownElements knownElements) { this.knownElements = knownElements; } public Object apply(Object arg) { if (arg instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> paramAsMap = (Map<String, Object>) arg; if (paramAsMap.containsKey("ELEMENT")) { KnownElements.ProxiedElement element = (KnownElements.ProxiedElement) knownElements .get((String) paramAsMap.get("ELEMENT")); return element.getWrappedElement(); } Map<String, Object> converted = Maps.newHashMapWithExpectedSize(paramAsMap.size()); for (Map.Entry<String, Object> entry : paramAsMap.entrySet()) { converted.put(entry.getKey(), apply(entry.getValue())); } return converted; } if (arg instanceof List<?>) { return Lists.newArrayList(Iterables.transform((List<?>) arg, this)); } return arg; } }
Convert RemoteWebElements decoded from JSON to "known elements". As of commit e32b83dc4321b05ecf9c7a9bbe21722a06b046ad, the decoded JSON parameters may include a WebElement. It's necessary to convert the element when a RemoteWebElement is passed as the "id" param to SwitchToFrame. Fixes #4083.
java/server/src/org/openqa/selenium/remote/server/handler/internal/ArgumentConverter.java
Convert RemoteWebElements decoded from JSON to "known elements".
<ide><path>ava/server/src/org/openqa/selenium/remote/server/handler/internal/ArgumentConverter.java <ide> import com.google.common.collect.Lists; <ide> import com.google.common.collect.Maps; <ide> <add>import org.openqa.selenium.remote.RemoteWebElement; <ide> import org.openqa.selenium.remote.server.KnownElements; <ide> <ide> import java.util.List; <ide> return converted; <ide> } <ide> <add> if (arg instanceof RemoteWebElement) { <add> return knownElements.get(((RemoteWebElement) arg).getId()); <add> } <add> <ide> if (arg instanceof List<?>) { <ide> return Lists.newArrayList(Iterables.transform((List<?>) arg, this)); <ide> }
Java
apache-2.0
0d41211747b9e8628ca8b7674b94d7334533f5db
0
prnncl/Reminiscence,nicofromspace/Reminiscence
package it.unitn.vanguard.reminiscence; import it.unitn.vanguard.reminiscence.utils.FinalFunctionsUtilities; import java.util.Calendar; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class DataNascitaActivity extends Activity { private Context context; private String day, month, year; // Date values private int dayValue = 1, monthValue = 0, yearValue = 1940; private int maxYear, maxDay, maxMonth; // Day views private Button btnDayUp, btnDayDown; private TextView txtDay; // Month Views private Button btnMonthUp, btnMonthDown; private TextView txtMonth; // Year Views private Button btnYearUp, btnYearDown; private TextView txtYear; // Back - Confirm Buttons private Button btnBack, arrowBackBtn; private Button btnConfirm, arrowConfirmBtn; private String[] mesi = {"Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno", "Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); String language = FinalFunctionsUtilities.getSharedPreferences("language", context); FinalFunctionsUtilities.switchLanguage(new Locale(language), context); setContentView(R.layout.activity_data_nascita); initializeButtons(); initializeVars(); initializeListeners(); //getting current day, month and year Calendar rightNow = Calendar.getInstance(); maxYear = rightNow.get(Calendar.YEAR); maxMonth = rightNow.get(Calendar.MONTH); maxDay = rightNow.get(Calendar.DATE); } private void initializeVars() { Context context = getApplicationContext(); day = FinalFunctionsUtilities.getSharedPreferences("day", context); month = FinalFunctionsUtilities.getSharedPreferences("month", context); year = FinalFunctionsUtilities.getSharedPreferences("year", context); //inizializza le variabili dayValue = Integer.parseInt(day); yearValue = Integer.parseInt(year); for(int i = 0; i < mesi.length; i++){ if(mesi[i].equals(month)){ monthValue = i; } } //setta i campi di testo txtDay.setText(day); txtMonth.setText(month); txtYear.setText(year); } private void initializeButtons() { //add day buttons btnDayUp = (Button) findViewById(R.id.btn_day_up); btnDayDown = (Button) findViewById(R.id.btn_day_down); txtDay = (TextView) findViewById(R.id.txt_day); //add month buttons btnMonthUp = (Button) findViewById(R.id.btn_month_up); btnMonthDown = (Button) findViewById(R.id.btn_month_down); txtMonth = (TextView) findViewById(R.id.txt_month); //add year buttons btnYearUp = (Button) findViewById(R.id.btn_year_up); btnYearDown = (Button) findViewById(R.id.btn_year_down); txtYear = (TextView) findViewById(R.id.txt_year); btnBack = (Button) findViewById(R.id.datanascita_back_btn); btnConfirm = (Button) findViewById(R.id.datanascita_confirm_btn); arrowConfirmBtn = (Button) findViewById(R.id.datanascita_arrow_confirm_btn); arrowBackBtn = (Button) findViewById(R.id.datanascita_arrow_back_btn); } private void initializeListeners() { // DAY UP-DOWN EVENTS btnDayUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dayValue--; dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else { txtDay.setText(String.valueOf(dayValue)); } } }); btnDayDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dayValue++; dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else { txtDay.setText(String.valueOf(dayValue)); } } }); // MONTH UP-DOWN EVENTS btnMonthUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(monthValue == 0) { monthValue = 11; } else { monthValue--; } if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else { dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtMonth.setText(mesi[monthValue]); txtDay.setText(String.valueOf(dayValue)); } } }); btnMonthDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(monthValue == 11) { monthValue = 0; } else { monthValue++; } if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else{ dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtMonth.setText(mesi[monthValue]); txtDay.setText(String.valueOf(dayValue)); } } }); // YEAR UP-DOWN EVENTS btnYearUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { yearValue++; if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ yearValue--; currentDateMsg(); } else{ txtYear.setText(String.valueOf(yearValue)); } dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtDay.setText(String.valueOf(dayValue)); } }); btnYearDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { yearValue--; if(yearValue == maxYear-120) { txtYear.setText(String.valueOf(yearValue = maxYear-120)); } else { txtYear.setText(String.valueOf(yearValue)); } dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtDay.setText(String.valueOf(dayValue)); } }); OnClickListener onclickback = new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), RegistrationActivity.class); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); finish(); } }; OnClickListener onclickconfirm = new View.OnClickListener() { @Override public void onClick(View v) { Intent passwordIntent = new Intent(v.getContext(), PasswordActivity.class); // Get shared preferences Context context = getApplicationContext(); FinalFunctionsUtilities.setSharedPreferences("day", txtDay.getText().toString(), context); FinalFunctionsUtilities.setSharedPreferences("month", txtMonth.getText().toString(), context); FinalFunctionsUtilities.setSharedPreferences("year", txtYear.getText().toString(), context); startActivityForResult(passwordIntent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); finish(); } }; //Button back btnBack.setOnClickListener(onclickback); arrowBackBtn.setOnClickListener(onclickback); // Button confirm btnConfirm.setOnClickListener(onclickconfirm); arrowConfirmBtn.setOnClickListener(onclickconfirm); } //control on current date (easter egg toast) void currentDateMsg(){ Context context = getApplicationContext(); CharSequence text = "Davvero? Sei nato nel futuro?"; Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); toast.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.login, menu); String language = FinalFunctionsUtilities.getSharedPreferences("language", getApplicationContext()); Locale locale = new Locale(language); if(locale.toString().equals(Locale.ITALIAN.getLanguage()) || locale.toString().equals(locale.ITALY.getLanguage())) { menu.getItem(0).setIcon(R.drawable.it); } else if(locale.toString().equals(Locale.ENGLISH.getLanguage())) { menu.getItem(0).setIcon(R.drawable.en); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Locale locale = null; switch (item.getItemId()) { case R.id.action_language_it: { locale = Locale.ITALY; break; } case R.id.action_language_en: { locale = Locale.ENGLISH; break; } } if(locale != null && FinalFunctionsUtilities.switchLanguage(locale, context)) { // Refresh activity finish(); startActivity(getIntent()); } return true; } }
src/it/unitn/vanguard/reminiscence/DataNascitaActivity.java
package it.unitn.vanguard.reminiscence; import it.unitn.vanguard.reminiscence.utils.FinalFunctionsUtilities; import java.util.Calendar; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class DataNascitaActivity extends Activity { private Context context; private String name, surname, mail, day, month, year; // Date values private int dayValue = 1, monthValue = 0, yearValue = 1940; private int maxYear, maxDay, maxMonth; // Day views private Button btnDayUp, btnDayDown; private TextView txtDay; // Month Views private Button btnMonthUp, btnMonthDown; private TextView txtMonth; // Year Views private Button btnYearUp, btnYearDown; private TextView txtYear; // Back - Confirm Buttons private Button btnBack, arrowBackBtn; private Button btnConfirm, arrowConfirmBtn; private String[] mesi = {"Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno", "Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); String language = FinalFunctionsUtilities.getSharedPreferences("language", context); FinalFunctionsUtilities.switchLanguage(new Locale(language), context); setContentView(R.layout.activity_data_nascita); initializeButtons(); initializeVars(); initializeListeners(); //getting current day, month and year Calendar rightNow = Calendar.getInstance(); maxYear = rightNow.get(Calendar.YEAR); maxMonth = rightNow.get(Calendar.MONTH); maxDay = rightNow.get(Calendar.DATE); } private void initializeVars() { Context context = getApplicationContext(); day = FinalFunctionsUtilities.getSharedPreferences("day", context); month = FinalFunctionsUtilities.getSharedPreferences("month", context); year = FinalFunctionsUtilities.getSharedPreferences("year", context); //inizializza le variabili dayValue = Integer.parseInt(day); yearValue = Integer.parseInt(year); for(int i = 0; i < mesi.length; i++){ if(mesi[i].equals(month)){ monthValue = i; } } //setta i campi di testo txtDay.setText(day); txtMonth.setText(month); txtYear.setText(year); } private void initializeButtons() { //add day buttons btnDayUp = (Button) findViewById(R.id.btn_day_up); btnDayDown = (Button) findViewById(R.id.btn_day_down); txtDay = (TextView) findViewById(R.id.txt_day); //add month buttons btnMonthUp = (Button) findViewById(R.id.btn_month_up); btnMonthDown = (Button) findViewById(R.id.btn_month_down); txtMonth = (TextView) findViewById(R.id.txt_month); //add year buttons btnYearUp = (Button) findViewById(R.id.btn_year_up); btnYearDown = (Button) findViewById(R.id.btn_year_down); txtYear = (TextView) findViewById(R.id.txt_year); btnBack = (Button) findViewById(R.id.datanascita_back_btn); btnConfirm = (Button) findViewById(R.id.datanascita_confirm_btn); arrowConfirmBtn = (Button) findViewById(R.id.datanascita_arrow_confirm_btn); arrowBackBtn = (Button) findViewById(R.id.datanascita_arrow_back_btn); } private void initializeListeners() { // DAY UP-DOWN EVENTS btnDayUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dayValue--; dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else { txtDay.setText(String.valueOf(dayValue)); } } }); btnDayDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dayValue++; dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else { txtDay.setText(String.valueOf(dayValue)); } } }); // MONTH UP-DOWN EVENTS btnMonthUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(monthValue == 0) { monthValue = 11; } else { monthValue--; } if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else { dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtMonth.setText(mesi[monthValue]); txtDay.setText(String.valueOf(dayValue)); } } }); btnMonthDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(monthValue == 11) { monthValue = 0; } else { monthValue++; } if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ currentDateMsg(); } else{ dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtMonth.setText(mesi[monthValue]); txtDay.setText(String.valueOf(dayValue)); } } }); // YEAR UP-DOWN EVENTS btnYearUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { yearValue++; if(FinalFunctionsUtilities.isOverCurrentDate(dayValue, monthValue, yearValue, maxDay, maxMonth, maxYear)){ yearValue--; currentDateMsg(); } else{ txtYear.setText(String.valueOf(yearValue)); } dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtDay.setText(String.valueOf(dayValue)); } }); btnYearDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { yearValue--; if(yearValue == maxYear-120) { txtYear.setText(String.valueOf(yearValue = maxYear-120)); } else { txtYear.setText(String.valueOf(yearValue)); } dayValue = FinalFunctionsUtilities.valiDate(dayValue, monthValue, yearValue); txtDay.setText(String.valueOf(dayValue)); } }); OnClickListener onclickback = new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), RegistrationActivity.class); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); finish(); } }; OnClickListener onclickconfirm = new View.OnClickListener() { @Override public void onClick(View v) { Intent passwordIntent = new Intent(v.getContext(), PasswordActivity.class); // Get shared preferences Context context = getApplicationContext(); FinalFunctionsUtilities.setSharedPreferences("day", txtDay.getText().toString(), context); FinalFunctionsUtilities.setSharedPreferences("month", txtMonth.getText().toString(), context); FinalFunctionsUtilities.setSharedPreferences("year", txtYear.getText().toString(), context); startActivityForResult(passwordIntent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); finish(); } }; //Button back btnBack.setOnClickListener(onclickback); arrowBackBtn.setOnClickListener(onclickback); // Button confirm btnConfirm.setOnClickListener(onclickconfirm); arrowConfirmBtn.setOnClickListener(onclickconfirm); } //control on current date (easter egg toast) void currentDateMsg(){ Context context = getApplicationContext(); CharSequence text = "Davvero? Sei nato nel futuro?"; Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT); toast.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.login, menu); String language = FinalFunctionsUtilities.getSharedPreferences("language", getApplicationContext()); Locale locale = new Locale(language); if(locale.toString().equals(Locale.ITALIAN.getLanguage()) || locale.toString().equals(locale.ITALY.getLanguage())) { menu.getItem(0).setIcon(R.drawable.it); } else if(locale.toString().equals(Locale.ENGLISH.getLanguage())) { menu.getItem(0).setIcon(R.drawable.en); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Locale locale = null; switch (item.getItemId()) { case R.id.action_language_it: { locale = Locale.ITALY; break; } case R.id.action_language_en: { locale = Locale.ENGLISH; break; } } if(locale != null && FinalFunctionsUtilities.switchLanguage(locale, context)) { // Refresh activity finish(); startActivity(getIntent()); } return true; } }
mi ero dimenticato di cancellare una roba
src/it/unitn/vanguard/reminiscence/DataNascitaActivity.java
mi ero dimenticato di cancellare una roba
<ide><path>rc/it/unitn/vanguard/reminiscence/DataNascitaActivity.java <ide> <ide> private Context context; <ide> <del> private String name, surname, mail, day, month, year; <add> private String day, month, year; <ide> <ide> // Date values <ide> private int dayValue = 1, monthValue = 0, yearValue = 1940;